Merge branch 'master' into fix/4823-message-overflow-review-menu

This commit is contained in:
sjw1231 committed 2026-09-21 19:25:06 +08:00
commit 719cc56276
661 files changed
+13380 -11424

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-04-configuration-source-ownership.md
2026-08-04-configuration-source-ownership.md: 6dea1f08a9f2a0319f894a504082ff70bbe1118f
2026-08-04-configuration-source-ownership.zh.md: 1ccf2c266c3e52f2f10d3bceb3b1505ae6266b15
2026-08-04-configuration-source-ownership.md: b8c146ed76e500fcde3affd92bc5188b83083223
2026-08-04-configuration-source-ownership.zh.md: 22afc15aec97a40829655fcb8179ad90a369bf0c
@@ -4,6 +4,8 @@ Status: implemented
English | [中文](2026-08-04-configuration-source-ownership.zh.md)
The non-secret settings tier below is superseded by [profile-owned live configuration](2026-09-19-profile-owned-live-configuration.md). Credential ordering and environment restrictions remain current.
## Problem
`$DSH_HOME/.env` had just [become an ordinary environment layer](../../archived/architecture/2026-08-04-credentials-yaml-and-user-environment-layer.md), which left the harness resolving user-facing values from a flattened `process.env` that could no longer say where a value came from. Three consequences followed.
@@ -4,6 +4,8 @@ Status: implemented
[English](2026-08-04-configuration-source-ownership.md) | 中文
下文的非秘密 settings 层已由 [profile 所属实时配置](2026-09-19-profile-owned-live-configuration.zh.md) 替代。凭据优先级与环境限制仍然适用。
## Problem
`$DSH_HOME/.env` 刚刚[变成普通环境层](../../archived/architecture/2026-08-04-credentials-yaml-and-user-environment-layer.md),这使得 harness 解析面向用户的值时面对的是一个压平的 `process.env`,再也说不清某个值来自哪里。由此产生三个后果。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-16-plugin-configuration-on-the-plugins-page.md
2026-09-16-plugin-configuration-on-the-plugins-page.md: 475580af48257f8c9f1d080617de1e672b74b028
2026-09-16-plugin-configuration-on-the-plugins-page.zh.md: 22d0aa4ff1e4d027ebfc3e019047c7d5e94497d7
2026-09-16-plugin-configuration-on-the-plugins-page.md: 700ada15385d0ff95e2f7f1cc58545a28677a507
2026-09-16-plugin-configuration-on-the-plugins-page.zh.md: 23935312d2b09a524a1571f81c18ad8b5ffafc3f
@@ -18,14 +18,14 @@ The page passes `view: 'page'` for each form. Official plugin cards and details
**Only a save writes.** The form has no discard control or unsaved marker; leaving a page drops its staged edits on unmount. A save writes through the client settings scope with the revision fence.
**The four host-plane pages register from `ui-settings-plugins` while the Host serves their namespaces.** The package keeps the Settings section as the **Built-in plugins** shell around the inventory tab and registers each page through `ctx.slots.inject` when the shared settings mirror shows the namespace, disposing it when the namespace goes, so a deployment that does not compose the owning plugin shows no trace of it. The `settings.plugin.item` slot is retired.
**The four host-plane pages register while the Host serves their namespaces.** Each page's package registers it through `ctx.slots.inject` when the shared settings mirror shows the namespace and disposes it when the namespace goes, so a deployment that does not compose the owning plugin shows no trace of it; since [settings pages as companion packages](2026-09-17-settings-pages-as-companion-packages.md) that is one companion package per page, and `ui-settings-plugins` keeps the Settings section as the **Built-in plugins** shell around the inventory tab. The `settings.plugin.item` slot is retired.
**The Official group.** The optional bundles the installation ships open the group, tagged **Beta** where the feature is one (Agent Teams), with no official tag; the configuration pages follow. Auto review is a published experimental package used as the install guide's example, not an `OPTIONAL_BUNDLES` entry or a CLI dependency.
## Consequences
- A bundle's browser half registers a form with one slot registration and its own dictionary; the bundle's patch must declare the row under the id in the key, and the registration exists while the row that carries the bundle's browser half is on: `dsh-client-modules` attaches that half to the row whose specifier is the bare package name, so a row-level page keyed to a subpath row disappears with the root row, not with its own.
- The four pages use the existing forms and settings write path; `ui-settings-plugins` owns the Settings section while its configuration pages live on the Plugins page.
- The four pages use the existing forms and settings write path; `ui-settings-plugins` owns the Settings section, and the configuration pages live on the Plugins page.
- Settings lists the inventory only; the Settings browser goldens cover that read-only section.
## Alternatives considered
@@ -18,14 +18,14 @@ Status: implemented
**只有保存才写入。** 表单没有放弃控件或未保存标记;离开页面时在卸载过程中丢弃暂存修改。保存经由客户端 settings scope,带 revision 栅栏。
**四个宿主平面页面由 `ui-settings-plugins` 在 Host 服务其命名空间期间注册。** 该包把设置分区保留为清单标签页外面的**内置插件**外壳,在共享的 settings 镜像显示某个命名空间时通过 `ctx.slots.inject` 注册对应页面,命名空间消失时销毁,因此没有组装该插件的部署不会留下它的痕迹。`settings.plugin.item` slot 退役。
**四个宿主平面页面在 Host 服务其命名空间期间注册。** 每个页面所在的包在共享的 settings 镜像显示某个命名空间时通过 `ctx.slots.inject` 注册对应页面,命名空间消失时销毁,因此没有组装该插件的部署不会留下它的痕迹;自[设置页作为伴生包](2026-09-17-settings-pages-as-companion-packages.zh.md)起,每个页面各是一个伴生包,`ui-settings-plugins` 把设置分区保留为清单标签页外面的**内置插件**外壳。`settings.plugin.item` slot 退役。
**官方分组。** 安装随附的可选组合包开启这个分组,属于 beta 功能的(Agent Teams)带 **Beta** 标签,没有官方标签;配置页排在其后。Auto review 是安装引导用作示例的已发布实验包,不属于 `OPTIONAL_BUNDLES` 或 CLI 依赖。
## 后果
- 组合包的浏览器半侧用一次 slot 注册加自己的词典就能提供表单;组合包的 patch 必须以键里的 id 声明这一行,注册只在承载组合包浏览器半侧的那一行开启期间存在:`dsh-client-modules` 把该半侧挂在说明符恰为包名的那一行上,因此键指向子路径行的行级页面随根行消失,而不随它自己的行。
- 四个页面使用现有表单和 settings 写入路径;`ui-settings-plugins` 拥有设置分区,其配置页则位于插件页。
- 四个页面使用现有表单和 settings 写入路径;`ui-settings-plugins` 拥有设置分区,配置页则位于插件页。
- 设置只列出清单;Settings 浏览器 golden 覆盖该只读分区。
## 考虑过的替代方案
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-plugin-detail-page-extension-slots.md
2026-09-17-plugin-detail-page-extension-slots.md: d4bbca0c4466fbb78a8c56cfc4e327100385368f
2026-09-17-plugin-detail-page-extension-slots.zh.md: f07efc3d3cadded04a7551867680cc058d532943
@@ -0,0 +1,35 @@
# Agent Note: Plugin detail pages as an extension point
Status: implemented
English | [中文](2026-09-17-plugin-detail-page-extension-slots.zh.md)
## Problem
The Plugins page's detail pages — a bundle's page, a row's page, an official plugin's page — carried only what the page drew itself and the object's own configuration ([plugin configuration on the Plugins page](2026-09-16-plugin-configuration-on-the-plugins-page.md)). A plugin with something to say about a bundle it does not own — a diagnostics plugin's health check, a market plugin's update badge, a documentation plugin's README section — had no place on that bundle's page, and importing the page to extend it is forbidden by the client bundle purity rule.
## Decision
**The page declares three list slots keyed by region, not by object.** `plugins.detail.actions` renders at the head of a page before the page's own switch and uninstall; `plugins.detail.badge` beside the title after the version, beta, and problem tags; `plugins.detail.section` under the page's own content — after the rows on a bundle's page, after the configuration on a row's or an official plugin's page. Each entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`. An entry decides from the subject whether to render and returns null otherwise; the page orders entries by `order`.
**The subject is a projection, not the store.** `PluginPackageRef` and `PluginRowRef` carry the name, version, installed and enabled facts, and the row list — the facts a contribution decides on — and nothing of the page's own state, so the page's store stays private and the contract stays small.
**A row's page still exists only for a configured row.** A list entry cannot say in advance which rows it has something for, and a row page with nothing on it shows nothing worth opening, so the configure control keeps its rule: a row is opened when a `plugins.row.config` entry names it, and contributions for the row render on that page.
## Alternatives considered
**One slot per object and region (`plugins.bundle.section`, `plugins.row.section`, ...).** Rejected: nine slots for three regions, and a contribution that spans objects would register three times. The subject discriminator carries the same information in three slots.
**Passing the page's `PackageView` and `PackageRow` as the subject.** Rejected: those types carry the Host's read-only reasons, errors, entry ids, and fiber phases, which are the page's business; exposing them would make store internals a public contract.
**Every row gets a page so row contributions always have a home.** Deferred: a row without configuration has nothing a page would show beyond its module and state; the rule can widen when a contribution needs it.
## Consequences
- A contribution is a slot registration with `import type` of `ui-plugin-manager` for the declarations; the page never names a contributing plugin.
- The e2e fixture bundle (`@fixture/live-client`) contributes to its own bundle and row pages through the three slots; its browser half registers them with the rest, and they leave with it.
- The slot catalog and the slots subsystem hierarchy list the three slots under `main`.
## Testing
`packages/client/ui-plugin-manager/tests/components.client.spec.tsx` renders contributions on a bundle's page, a row's page, and an official plugin's page with the subject each is about, and pins the projection; `browser-plugin.client.spec.tsx` pins the declarations. `apps/web/tests/plugin-config.e2e.ts` switches the fixture bundle on and asserts its action, badge, and section on the bundle's page and the row's page, their absence on an official plugin's page, and holds the bundle page's golden.
@@ -0,0 +1,35 @@
# Agent Note:插件详情页作为扩展点
状态:已实现
[English](2026-09-17-plugin-detail-page-extension-slots.md) | 中文
## 问题
插件页的详情页——组合包页、行页、官方插件页——只承载页面自绘的内容和对象自己的配置([插件配置放在插件页](2026-09-16-plugin-configuration-on-the-plugins-page.zh.md))。对不属于自己的组合包有话要说的插件——诊断插件的健康检查、市场插件的更新标签、文档插件的 README 区块——在那个组合包的页面上无处安放,而通过 import 页面来扩展它被客户端包纯净性规则禁止。
## 决策
**页面按区域而不是按对象声明三个 list slot。** `plugins.detail.actions` 渲染在页头,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁,位于版本、Beta 和异常标签之后;`plugins.detail.section` 在页面自身内容之下——组合包页在组件列表之后,行页与官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`。条目根据 subject 决定是否渲染,否则返回 null;页面按 `order` 排列条目。
**subject 是投影,不是 store。** `PluginPackageRef` 与 `PluginRowRef` 携带包名、版本、是否已安装、是否启用以及行列表——贡献者据以判断的事实——不带页面自己的任何状态,因此页面的 store 保持私有,契约保持精简。
**行页仍然只为已配置的行存在。** list 条目无法预先说明它对哪些行有话要说,而一个空空如也的行页没有值得打开的内容,所以配置控件保留原规则:有 `plugins.row.config` 条目点名这一行时才可打开,对该行的贡献渲染在那个页面上。
## 考虑过的替代方案
**按对象和区域各开一个 slot(`plugins.bundle.section`、`plugins.row.section` 等)。** 否决:三个区域要九个 slot,而跨对象的贡献要注册三次。subject 判别式在三个 slot 里承载同样的信息。
**把页面的 `PackageView` 与 `PackageRow` 直接作为 subject。** 否决:这些类型携带 Host 的只读原因、错误、条目 id 与 fiber 阶段,这些是页面自己的事;暴露它们会让 store 内部成为公共契约。
**每一行都有页面,让行级贡献总有落脚处。** 推迟:没有配置的行,页面除了模块名和状态之外无可展示;等有贡献需要时再放宽这条规则。
## 后果
- 一个贡献就是一次 slot 注册,只需 `import type` `ui-plugin-manager` 的声明;页面从不点名任何贡献插件。
- e2e 夹具组合包(`@fixture/live-client`)通过三个 slot 向它自己的组合包页和行页贡献内容;它的浏览器半侧与其余注册一起完成,也一起离开。
- slot 目录与 slots 子系统层级树在 `main` 下列出这三个 slot。
## 测试
`packages/client/ui-plugin-manager/tests/components.client.spec.tsx` 在组合包页、行页和官方插件页上渲染贡献并核对各自的 subject,钉住投影;`browser-plugin.client.spec.tsx` 钉住声明。`apps/web/tests/plugin-config.e2e.ts` 打开夹具组合包,断言组合包页与行页上的操作、标签和区块、官方插件页上没有它们,并保留组合包页的 golden。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-settings-pages-as-companion-packages.md
2026-09-17-settings-pages-as-companion-packages.md: de2f2897938fcc158c49bed772f399b4d9328d19
2026-09-17-settings-pages-as-companion-packages.zh.md: 27d00faa156f0f48c6dc3995930be9ca629a732d
@@ -0,0 +1,40 @@
# Agent Note: Settings pages as companion packages
Status: implemented
English | [中文](2026-09-17-settings-pages-as-companion-packages.zh.md)
## Problem
The four official settings pages — shell, agent loop, Subagent, web search — lived in one client package, `ui-settings-plugins`, beside the Built-in plugins section. Every new built-in page grew that package, and a community bundle that wanted a settings page had no worked example of a page living with the plugin that owns the namespace. Moving each page into the Host package that registers its namespace was considered and does not fit: the shell namespace is registered by the executor families under the sandbox row, the loop package would gain a browser build for one number field, and the Subagent namespaces are registered from a subpath row, which carries no browser half.
## Decision
**A community plugin's settings page lives in its own package's browser half.** It registers into `plugins.bundle.config` or `plugins.row.config`, owns its copy and styles, and reads and writes through `ctx.settingsScope`. Its i18n is the client locale service, as the shipped community bundles already do.
**A built-in namespace's page lives in a companion client package.** `ui-settings-shell`, `ui-settings-agent-loop`, `ui-settings-subagent`, and `ui-settings-web-search` are client-only packages with an empty Host `apply`, one bare-name row each in the web composition's roster, registering into `plugins.item` while the Host serves their namespace. Host packages stay free of browser code; the namespace they edit is spelled as a literal, never imported from the owner.
**The form machinery moves to `ui-primitives`.** `SettingsFormModel` with `settingsNumberField` and `settingsTextField`, `SettingsValueField` and `SettingsSecretField`, and the `SettingsForm` frame are the kit every page renders with; the frame takes its copy as `labels` and the model takes a structural scope, so the baseline package depends on neither a plugin nor its dictionary.
**`settingsScope.whileServed(namespaces, register)` is the registration rule.** A page exists exactly while the Host serves one of its namespaces: the service watches the shared describe mirror, runs the registration when a namespace appears, and disposes it when none is served, so four packages share one rule instead of four copies.
**`ui-settings-plugins` keeps the Built-in plugins section only:** the navigation entry and the tab row feature-owned tabs register into.
## Alternatives considered
**A schema-driven generic form.** Rejected: a generic renderer covers scalar fields and stops at the first dynamic control — the Subagent page's live model catalogue, its cross-field rule, its one-mutation save — and every exception would become a role the schema is not for. Every page is code; a community plugin that ships no page has none.
**Dual-face Host packages for the built-in pages.** Rejected for the reasons above; the companion keeps the option open for a package that can carry a half.
**Copy for the form frame in one shared dictionary.** Rejected: it would couple every page to another plugin's dictionary keys; each page's dictionary carries the few frame strings.
## Consequences
- The Plugins page's Official group lists the same four pages in the same order, from four packages instead of one; their labels and forms are unchanged, so the page goldens hold.
- The cookbook [adding a settings page](../../../../docs/cookbook/adding-a-settings-card.md) shows the community path and names the companion template.
- The client module system's rule stands: a browser half rides the Loader row whose specifier is the bare package name, so a bundle split into subpath rows keeps every page it registers on its root row.
- The shell page's `plugins.item` id is `shell`, where the old package registered `bash`: `subject.id` on an official page is now a discriminator `plugins.detail.*` contributions key on, so the id names the capability the page edits rather than one executor family.
## Testing
Each companion's `tests/apply.client.spec.ts` registers its page while the Host serves the namespace, withdraws it when the Host stops, and collapses on teardown; its card and controller specs carry the page's behavior from the former package. `packages/client/ui-primitives/tests/settings-form-model.client.spec.ts`, `packages/client/ui-primitives/tests/settings-form.client.spec.tsx`, and `packages/client/ui-primitives/tests/settings-fields.client.spec.tsx` pin the kit; `packages/client/ui-settings/tests/while-served.client.spec.ts` pins the registration rule. `apps/web/tests/plugin-config.e2e.ts` exercises the shell and Subagent pages over the real wire.
@@ -0,0 +1,40 @@
# Agent Note:设置页作为伴生包
状态:已实现
[English](2026-09-17-settings-pages-as-companion-packages.md) | 中文
## 问题
四个官方设置页——终端、Agent 循环、Subagent、网页搜索——都放在一个客户端包 `ui-settings-plugins` 里,与「内置插件」分区挨着。每新增一个内置页面都让这个包再长一截,而想要设置页的社区组合包也找不到"页面与拥有命名空间的插件放在一起"的现成样板。曾考虑把每个页面搬进注册其命名空间的宿主包,但行不通:shell 命名空间由执行器家族在 sandbox 行之下注册,循环包为了一个数字字段要长出浏览器构建,Subagent 的命名空间从子路径行注册,而子路径行不携带浏览器半侧。
## 决策
**社区插件的设置页放在自己包的浏览器半侧。** 它注册进 `plugins.bundle.config` 或 `plugins.row.config`,自己拥有文案和样式,通过 `ctx.settingsScope` 读写。它的 i18n 走客户端 locale 服务,已发布的社区组合包本来就是这么做的。
**内置命名空间的页面放在伴生客户端包里。** `ui-settings-shell`、`ui-settings-agent-loop`、`ui-settings-subagent`、`ui-settings-web-search` 是纯客户端包,宿主 `apply` 为空,各在 Web 组合花名册里占一条裸名行,在 Host 服务其命名空间期间注册进 `plugins.item`。宿主包不含浏览器代码;它们编辑的命名空间以字面量拼写,从不从 owner 导入。
**表单机制搬进 `ui-primitives`。** `SettingsFormModel` 及 `settingsNumberField`、`settingsTextField`,`SettingsValueField` 与 `SettingsSecretField`,以及 `SettingsForm` 框架,是每个页面共同渲染用的套件;框架以 `labels` 接收文案,模型接受结构化的 scope,因此基线包既不依赖任何插件也不依赖其字典。
**`settingsScope.whileServed(namespaces, register)` 是注册规则。** 页面恰好在 Host 服务其某个命名空间期间存在:服务监视共享的 describe 镜像,命名空间出现时执行注册,一个都不再服务时注销,四个包共用一条规则而不是四份副本。
**`ui-settings-plugins` 只保留「内置插件」分区:** 导航项和供功能插件注册标签页的标签行。
## 考虑过的替代方案
**由 schema 驱动的通用表单。** 否决:通用渲染器只覆盖标量字段,碰到第一个动态控件就止步——Subagent 页的实时模型目录、跨字段规则、一次 mutate 提交——而每个例外都会变成一个 schema 本不该承担的 role。每个页面都是代码;没有发页面的社区插件就没有页面。
**内置页面做成双面宿主包。** 因上述原因否决;伴生包给能带半侧的包留了这个选项。
**表单框架的文案放在一本共享字典里。** 否决:那会让每个页面耦合到另一个插件的字典键;每个页面的字典自带那几条框架文案。
## 后果
- 插件页官方分组列出同样四个页面、同样顺序,来自四个包而不是一个;标签与表单未变,页面 golden 保持不变。
- 手册[添加设置页](../../../../docs/cookbook/adding-a-settings-card.zh.md)展示社区路径并点名伴生包模板。
- 客户端模块系统的规则不变:浏览器半侧挂在说明符为裸包名的 Loader 行上,因此拆成子路径行的组合包,其注册的所有页面都留在根行上。
- 终端页在 `plugins.item` 里的 id 是 `shell`,旧包注册的是 `bash`:官方页面上的 `subject.id` 现在是 `plugins.detail.*` 贡献可以据以判断的标识,所以 id 以页面编辑的能力命名,而不是某一个执行器家族。
## 测试
每个伴生包的 `tests/apply.client.spec.ts` 在 Host 服务命名空间时注册页面、停止服务时注销、teardown 时收拢;其 card 与 controller 用例延续原包里的页面行为。`packages/client/ui-primitives/tests/settings-form-model.client.spec.ts`、`packages/client/ui-primitives/tests/settings-form.client.spec.tsx` 与 `packages/client/ui-primitives/tests/settings-fields.client.spec.tsx` 钉住套件;`packages/client/ui-settings/tests/while-served.client.spec.ts` 钉住注册规则。`apps/web/tests/plugin-config.e2e.ts` 走真实链路验证终端页与 Subagent 页。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-19-profile-owned-live-configuration.md
2026-09-19-profile-owned-live-configuration.md: 7acf10986987960a9748308c9fe19060a97cfcc0
2026-09-19-profile-owned-live-configuration.zh.md: c9b88462a5e0a8601d9dcd83f7d82b49e7ce5b5c
@@ -0,0 +1,29 @@
# Agent Note: Keep live configuration in the owning profile
Status: implemented
English | [中文](2026-09-19-profile-owned-live-configuration.zh.md)
## Problem
Separate settings registrations duplicated schemas, defaults, persistence, and notifications. They also placed stored user settings above deployment overlays without preserving which composition source supplied a value. Using the Loader's resolved Config gives validation and consumers one owner and preserves its lifecycle decisions.
## Decision
A plugin declares every configurable value in its Cordis Config. Fields that can change without remounting use `.volatile()`; consumers read their references during operations. Settings enumerates those fields for forms and never supplies business configuration. The profile editor writes `cordis.patch.yml` and applies the ordinary Loader reconciliation path.
Form writes target the active profile. Home patches and command-line overlays remain higher-priority deployment inputs; an edit they would shadow fails before persistence. Two plugin instances are addressed by their distinct profile entry ids. Nested Includes retain independent ownership and are not writable through the profile form.
Cordis config patches replace complete entry configs. An edit preserves ordinary fields and unedited secrets, including raw configuration expressions. A field reset restores the currently inherited value; resetting the complete entry removes its config overrides so later bundle changes are inherited. Other edits store the entry's complete config in the profile row: the ordinary fields as composed at write time plus every volatile field. Later bundle changes to those fields do not reach that profile until the entry's config override is removed. In the shipped bundles this pins `permission.presets` after a default-preset change, `agent-presets` after a preset choice, `agent-loop.agents` after a parallelism edit, and `web-search-deepseek.apiKeyEnv` after a Web Search edit, and the client marks every volatile field of such a row as overridden, not only the edited one. Narrowing a write to the edited fields needs merge semantics for patch `config`, which Include does not provide.
The removed `$DSH_HOME/settings.yaml` is imported once into the active profile when the Loader has settled every entry after Settings starts: section ids are entry ids, with `ui-developer-tools` → `ui-settings`, `ui-onboarding` → `ui-settings-general`, and `shell` → the platform's shell executor entry. The file is renamed to `settings.yaml.imported` before the first write, so the import never repeats; a rejected section is logged and stays in the renamed file.
## Alternatives considered
The rejected alternative is retaining settings as a second store behind a configuration adapter: that still requires reconciling two durable documents and deciding which wins after concurrent edits or restart. The removed global settings document offered cross-profile preferences; this design deliberately makes persisted form values profile-specific. Reintroducing shared preferences requires an explicit shared Cordis layer and a defined write destination.
## Consequences
This supersedes only the non-secret settings tier in [configuration source ownership](2026-08-04-configuration-source-ownership.md); its environment restrictions and credential ordering remain applicable. [Volatile references](2026-09-18-volatile-config-references.md) own reference lifetime and ordinary update behavior.
Real profile tests cover multiple instances, persisted restart, invalid edits, stale revisions, higher-layer rejection, secret redaction, and configuration expressions. Browser tests exercise form writes and reset through the assembled application. Runtime reference identity is checked across live edits.
@@ -0,0 +1,29 @@
# Agent Note: 将实时配置保存在所属 profile 中
Status: implemented
[English](2026-09-19-profile-owned-live-configuration.md) | 中文
## 问题
独立的 settings 注册重复了 schema、默认值、持久化和通知,也让已存用户设置高于部署 overlay,却未保留值来自哪个组合来源。采用 Loader 已解析的 Config,使校验与消费者共享同一所有者,并保留已有生命周期判定。
## 决定
插件在 Cordis Config 中声明全部可配置值。无需重新挂载即可变化的字段使用 `.volatile()`;消费者在操作时读取其引用。Settings 只枚举这些字段并生成表单,不向业务提供配置。profile 编辑器写入 `cordis.patch.yml`,并通过普通 Loader 协调路径应用变化。
表单写入当前 profile。home patch 和命令行 overlay 仍是优先级更高的部署输入;如果它们会遮蔽某次修改,编辑器会在持久化前拒绝写入。两个插件实例通过各自不同的 profile entry id 寻址。嵌套 Include 保留独立所有权,不能通过该 profile 表单写入。
Cordis config patch 替换完整 entry config。编辑会保留普通字段、未编辑的秘密值和原始配置表达式。字段重置恢复当前继承值;整个 entry 重置后会移除其 config override,从而继承后续 bundle 变化。其他编辑会把该 entry 的完整 config 存入 profile 行:写入时组合出的普通字段加上全部 volatile 字段。此后 bundle 对这些字段的修改在该 entry 的 config override 被移除之前不会到达该 profile。在已发布的 bundle 中,修改默认权限预设会钉住 `permission.presets`,选择预设会钉住 `agent-presets`,编辑并行度会钉住 `agent-loop.agents`,编辑网页搜索会钉住 `web-search-deepseek.apiKeyEnv`;客户端会把这类行的每个 volatile 字段都标为已覆盖,而不只是被编辑的那个。要把写入收窄到被编辑字段需要 patch `config` 的合并语义,Include 不提供。
被移除的 `$DSH_HOME/settings.yaml` 会在 Settings 启动后、Loader 完成所有条目加载时一次性导入当前 profile:section id 即 entry id,其中 `ui-developer-tools` → `ui-settings`、`ui-onboarding` → `ui-settings-general`、`shell` → 当前平台的 shell 执行器条目。文件在第一次写入前改名为 `settings.yaml.imported`,因此导入不会重复;被拒绝的 section 会记录日志并保留在改名后的文件中。
## 考虑过的替代方案
保留 settings 作为配置适配器背后的第二份存储仍需要协调两份持久化文档,并决定并发修改或重启后哪份优先,因此不采用。删除的全局 settings 文档曾提供跨 profile 偏好;本设计明确将表单值持久化到各 profile。若重新引入共享偏好,必须采用显式共享 Cordis 层并明确写入目标。
## 后果
本决定只替代 [配置来源所有权](2026-08-04-configuration-source-ownership.zh.md) 中的非秘密 settings 层;其中的环境限制和凭据优先级仍适用。[Volatile 引用](2026-09-18-volatile-config-references.zh.md) 负责引用生命周期和普通更新行为。
真实 profile 测试覆盖多实例、持久化重启、非法编辑、过期修订、高优先级层拒绝、秘密脱敏及配置表达式。浏览器测试通过完整应用执行表单写入和重置,并检查实时编辑前后的运行时引用身份。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md
2026-08-06-host-backed-web-preferences.md: 4ccd5cfe092e01fb266d51d5fc84b7cf1556214c
2026-08-06-host-backed-web-preferences.zh.md: fbfdda432821eba1d32cab781340fd5f7802c61d
2026-08-06-host-backed-web-preferences.md: 4b8d52887554899f2aee9253e65354e4c0fc7e46
2026-08-06-host-backed-web-preferences.zh.md: 9c61de71981c9e4950889cf94eba2645b9247aa8
@@ -12,11 +12,11 @@ The first theme implementation moved only Appearance to Host settings but awaite
## Decision
The owning Host halves register three schemas: optional `locale.preference` (`zh` or `en`, where absence delegates to the browser), `ui-theme.preference` (`light`, `dark`, or `system`, default `system`), and `ui-conversation.busyEnter` (`queue` or `steer`, default `queue`). The local settings provider stores explicit choices in `$DSH_HOME/settings.yaml`, which resolves to `~/.dsh/settings.yaml` under the default home. The API proxy serves every registered namespace behind Connection's browser authentication; field roles still redact secrets.
The owning Host Config schemas declare volatile locale, theme, and busy-Enter preferences. ConfigEditor stores explicit choices in the active profile patch. The authenticated settings API projects those Config fields and redacts secret roles.
`dsh-client-ui-settings` owns one browser-wide settings describe mirror and provides `ctx.settingsScope.bind(spec)` as a per-namespace selector over it. The mirror installs `settings/document-updated` and `connection/reset` listeners before starting its background read, so no settings transport can block plugin activation and an invalidation cannot fall into a read-before-subscribe gap. Each bound scope publishes a snapshot store (status, section value, revision, writability, host/memory mode) the domain service subscribes to, without adding a wire read or listener of its own. The default decoder validates each incoming section against the namespace's own serialized wire schema, rehydrated through the colocated `ctx.settingsSchema` service, so domains carry no hand-written wire guards. Domain services take the scope as an ordinary constructor collaborator, publish their provisional defaults immediately—browser-derived locale, system theme, and Queue—then adopt an accepted Host section without writing it back; a service constructed without a scope (standalone dictionary or policy fixtures) simply stays process-local. The shared read and invalidation lifecycle is specified by the later [settings describe mirror decision](../../archived/architecture/2026-08-17-settings-describe-mirror.md).
`dsh-client-ui-settings` owns one browser-wide settings describe mirror and provides `ctx.configForms.get(entryId)` as a per-namespace selector over it. The mirror installs `settings/document-updated` and `connection/reset` listeners before starting its background read, so no settings transport can block plugin activation and an invalidation cannot fall into a read-before-subscribe gap. Each shared entry form publishes a snapshot store (status, section value, revision, writability, host/memory mode) the domain service subscribes to, without adding a wire read or listener of its own. The default decoder validates each incoming section against the namespace's own serialized wire schema, rehydrated through the colocated `ctx.settingsSchema` service, so domains carry no hand-written wire guards. Domain services take the scope as an ordinary constructor collaborator, publish their provisional defaults immediately—browser-derived locale, system theme, and Queue—then adopt an accepted Host section without writing it back; a service constructed without a scope (standalone dictionary or policy fixtures) simply stays process-local. The shared read and invalidation lifecycle is specified by the later [settings describe mirror decision](../../archived/architecture/2026-08-17-settings-describe-mirror.md).
User changes update the live service synchronously and queue a `settings.mutate` path operation through `scope.set`. The scope serializes gestures, sends the latest known namespace revision as `expectedRevision`, records every successful revision, and lets only the latest write settlement republish live state. A rejected or failed latest write reloads Host state. Disposal rejects new work, skips queued operations, suppresses publication by the in-flight operation, and waits for that operation to settle before the plugin reaches quiescence.
User changes update the live preference immediately and queue a revision-fenced mutation through the shared entry form. The provider owns one write queue per entry; consumers release their subscriptions when they unload. Provider disposal skips queued work, suppresses late publication, and waits for the in-flight operation.
The Client keeps Host persistence disabled on non-loopback pages, so their preferences remain process-local even though Connection authenticates the complete API. Dynamic third-party theme ids remain in-process extensions outside the built-in Host schema; removing one resets the live registry without replacing the last durable built-in preference.
@@ -36,7 +36,7 @@ The Client keeps Host persistence disabled on non-loopback pages, so their prefe
## Consequences
Appearance, Language, and busy-Enter choices follow the DSH user home across reloads, ports, and loopback origins. Direct edits to `settings.yaml` converge through the existing invalidation stream, while legacy `dsh.theme`, `dsh.locale`, and `dsh.conversation.busyEnter` entries are neither read nor written.
Appearance, Language, and busy-Enter choices follow the active profile across reloads, ports, and loopback origins. ConfigEditor and volatile HMR apply profile changes; the form mirror follows accepted values through settings invalidations. Legacy browser preference keys remain unused.
Boot may briefly show the domain default before the background read settles. A transient read failure keeps that default or the last good in-process value; reconnect retries. A write rejection can visibly restore the durable preference after the immediate local change.
@@ -12,11 +12,11 @@ Web 的 Appearance、Language 和繁忙态 Enter 偏好原本存在浏览器 `lo
## 决策
各领域所属的 Host half 注册三份 schema:可选的 `locale.preference`(`zh` 或 `en`,缺失时交由浏览器决定)、`ui-theme.preference`(`light`、`dark` 或 `system`,默认为 `system`),以及 `ui-conversation.busyEnter`(`queue` 或 `steer`,默认为 `queue`)。本地 settings 提供方将显式选择存入 `$DSH_HOME/settings.yaml`,在使用默认 home 时,该路径解析为 `~/.dsh/settings.yaml`。API 代理在 Connection 浏览器认证之后服务每一个已注册的 namespace;字段角色仍会脱敏机密值。
对应 Host Config schema 声明 volatile 语言、主题和忙碌时 Enter 偏好。ConfigEditor 将显式选择保存到活跃 profile patch。经过认证的 settings API 投影这些 Config 字段,并对 secret 角色字段脱敏。
`dsh-client-ui-settings` 持有一个浏览器全局的 settings describe 镜像,并提供 `ctx.settingsScope.bind(spec)` 作为该镜像上的逐 namespace selector。镜像在开始后台读取之前安装 `settings/document-updated` 和 `connection/reset` 监听器,因此任何 settings 传输都不会阻塞插件激活,失效通知也不会掉入先读取、后订阅的空档。每个绑定的 scope 会发布一个供领域服务订阅的快照 store(状态、分节值、revision、可写性、host/内存模式),自身不再增加协议读取或监听器。默认解码器会对照该 namespace 自身的序列化 wire schema(经同包的 `ctx.settingsSchema` 服务还原)校验每个传入分节,因此各领域无需携带手写的 wire 校验器。领域服务把 scope 当作普通的构造函数协作者接收,立即发布各自的暂定默认值:由浏览器派生的 locale、系统主题和 Queue;随后采纳已获接受的 Host 分节,但不将其写回;不带 scope 构造的服务——独立词典或政策 fixture(测试前置数据)——则仅停留在进程本地。共享读取与失效生命周期由后续的 [settings describe 镜像决策](../../archived/architecture/2026-08-17-settings-describe-mirror.md)规定。
`dsh-client-ui-settings` 持有一个浏览器全局的 settings describe 镜像,并提供 `ctx.configForms.get(entryId)` 作为该镜像上的逐 namespace selector。镜像在开始后台读取之前安装 `settings/document-updated` 和 `connection/reset` 监听器,因此任何 settings 传输都不会阻塞插件激活,失效通知也不会掉入先读取、后订阅的空档。每个共享条目表单会发布一个供领域服务订阅的快照 store(状态、分节值、revision、可写性、host/内存模式),自身不再增加协议读取或监听器。默认解码器会对照该 namespace 自身的序列化 wire schema(经同包的 `ctx.settingsSchema` 服务还原)校验每个传入分节,因此各领域无需携带手写的 wire 校验器。领域服务把 scope 当作普通的构造函数协作者接收,立即发布各自的暂定默认值:由浏览器派生的 locale、系统主题和 Queue;随后采纳已获接受的 Host 分节,但不将其写回;不带 scope 构造的服务——独立词典或政策 fixture(测试前置数据)——则仅停留在进程本地。共享读取与失效生命周期由后续的 [settings describe 镜像决策](../../archived/architecture/2026-08-17-settings-describe-mirror.md)规定。
用户变更会同步更新实时服务,并经 `scope.set` 将一项 `settings.mutate` 路径操作排入队列。scope 会串行处理手势,以最新已知 namespace revision 作为 `expectedRevision` 发送,记录每次成功写入的 revision,并且只允许最新写入的结算结果重新发布实时状态。最新写入被拒或失败时,scope 会重新加载 Host 状态。插件释放会拒绝新工作、跳过已排队操作、抑制运行中操作发布状态,并等待该操作结算后才让插件达到完全停稳。
用户修改立即更新实时偏好,并通过共享条目表单排队提交带修订号检查的修改。提供者为每个条目持有一个写入队列;消费者在卸载时释放订阅。提供者销毁时跳过排队工作、禁止迟到发布,并等待正在执行的操作结束。
Client 在非 loopback 页面禁用 Host 持久化,因此这些页面的偏好仍只保留在进程内,尽管 Connection 认证完整 API。动态第三方主题 id 仍是内置 Host schema 之外的进程内扩展;移除其中一个会重置实时注册表,但不会替换上一个持久化的内置偏好。
@@ -36,7 +36,7 @@ Client 在非 loopback 页面禁用 Host 持久化,因此这些页面的偏好
## 后果
Appearance、Language 和繁忙态 Enter 选择会跟随 DSH 用户 home,跨越重新加载、端口与回环 origin。直接编辑 `settings.yaml` 所产生的变更会通过现有失效流收敛,而旧的 `dsh.theme`、`dsh.locale` 和 `dsh.conversation.busyEnter` 条目既不会被读取,也不会被写入。
外观、语言和忙碌时 Enter 偏好跟随活跃 profile,跨刷新、端口和回环 origin 保持一致。ConfigEditor 和 volatile HMR 应用 profile 更改;表单镜像通过 settings 失效通知跟随已接受值。旧浏览器偏好键保持不使用。
启动时可能会在后台读取结算前短暂显示领域默认值。短暂的读取失败会保留该默认值或上一个正确的进程内值;重连时会重试。写入被拒时,界面可能会在本地值立即变化后明显恢复为持久化偏好。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-17-developer-tools-settings.md
2026-09-17-developer-tools-settings.md: 7819b2a2df3c9eaf2db1e1271d7b419768affaff
2026-09-17-developer-tools-settings.zh.md: 5ff9f2c1e2380f086969cc392bf649edd13e2893
2026-09-17-developer-tools-settings.md: 5ae8861efa701042e0730310ddb23f6f559d14d7
2026-09-17-developer-tools-settings.zh.md: e7a9d3c28d53ba9fe14c970bd48f2a6031248e58
@@ -10,7 +10,7 @@ Diagnostic views, preset selection and changed-file summaries add complexity to
## Decision
The settings-owned `ctx.settingsScope.developerTools` preference binds a namespace scope and exposes one accepted `ui-developer-tools.enabled` preference. The initial default-off choice reduces routine-task complexity; [Developer tools default on after preference resolution](2026-09-20-developer-tools-default-on.md) supersedes that default and owns startup enablement. General Settings offers the same switch on Web and desktop. The existing settings transport owns validation, ordered writes, persistence and recovery; loopback Web and desktop follow Host acceptance. Remote Web owns one browser-local observable shared by all consumers until reload, with no Host writes.
The settings-owned `ctx.configForms.developerTools` preference uses a shared entry form and exposes one accepted `ui-settings.enabled` preference. The initial default-off choice reduces routine-task complexity; [Developer tools default on after preference resolution](2026-09-20-developer-tools-default-on.md) supersedes that default and owns startup enablement. General Settings offers the same switch on Web and desktop. The existing settings transport owns validation, ordered writes, persistence and recovery; loopback Web and desktop follow Host acceptance. Remote Web owns one browser-local observable shared by all consumers until reload, with no Host writes.
Off hides the Trajectory View, hides tool Inspect actions when no visible View declares tool-call inspection, hides the conversation View tab bar while fewer than two Views are available, hides the new-session preset chip and the settings row that allows switching Agent modes, and omits the changed-files card and its summary read. Views registered by other plugins stay available. Turning it off while Trajectory is active activates Chat. The preset composition, saved default, Session events and explicit delivery cards remain unchanged. This preference is presentation policy, not Host authorization.
@@ -10,7 +10,7 @@ Status: implemented
## Decision
设置域内的 `ctx.settingsScope.developerTools` 偏好对象绑定命名空间 scope,提供一个已接受的 `ui-developer-tools.enabled` 偏好。最初默认关闭的选择用于降低日常任务的复杂度;[偏好解析后默认开启开发者工具](2026-09-20-developer-tools-default-on.zh.md)取代该默认值并负责启动时的启用策略。Web 和桌面端的通用设置提供同一个开关。现有设置传输负责验证、有序写入、持久化和恢复;回环 Web 和桌面端跟随 Host 接受的状态。远程 Web 持有一个所有消费者共享的浏览器本地可观察值,刷新后重置,不发送 Host 写入。
设置域内的 `ctx.configForms.developerTools` 偏好对象使用共享条目表单,提供一个已接受的 `ui-settings.enabled` 偏好。最初默认关闭的选择用于降低日常任务的复杂度;[偏好解析后默认开启开发者工具](2026-09-20-developer-tools-default-on.zh.md)取代该默认值并负责启动时的启用策略。Web 和桌面端的通用设置提供同一个开关。现有设置传输负责验证、有序写入、持久化和恢复;回环 Web 和桌面端跟随 Host 接受的状态。远程 Web 持有一个所有消费者共享的浏览器本地可观察值,刷新后重置,不发送 Host 写入。
关闭时隐藏 Trajectory View,在没有可见 View 声明工具调用检查能力时隐藏 Inspect 操作,可见 View 少于两个时隐藏会话 View 标签栏,隐藏新会话预设入口和「允许切换agent模式」设置行,并省略改动文件卡片及其摘要读取。其他插件注册的 View 保持可用。在 Trajectory 中关闭开关会激活 Chat。预设组合、保存的默认值、Session 事件和显式交付卡片保持不变。此偏好是展示策略,不是 Host 授权。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-16-desktop-release-version-derivation.md
2026-09-16-desktop-release-version-derivation.md: 0f1d917cb0d382453fbb0dca561a1eae7d530d67
2026-09-16-desktop-release-version-derivation.zh.md: e9576e30232b5eb247de047cb67f51db5fa43ae3
2026-09-16-desktop-release-version-derivation.md: 54a7b9d52c63268f15209ad0a84bcd8da035dcee
2026-09-16-desktop-release-version-derivation.zh.md: dddf4b773217965380c4487803971311b57e0863
@@ -10,11 +10,11 @@ Replacing a dsh prerelease identifier with the update channel name loses the bas
## Decision
The [Desktop release rules](../../../../apps/desktop/README.md#release-versions) preserve the complete dsh base for production and derive dated, indexed test versions from that base. Final release-family package versions remain equal. The base is retained separately before manifests are retagged, so another test release cannot append a second date suffix.
The [Desktop release rules](../../../../apps/desktop/README.md#release-versions) preserve the complete dsh base for production and derive dated, indexed test versions from that base. The derived version is [passed to packaging as an argument](2026-09-21-desktop-build-version-as-input.md) rather than written into manifests, and it is derived from the dsh base so another test release cannot append a second date suffix.
The fixed Nightly feed is a distribution address, independent of version derivation. Existing clients continue to use that address with prerelease updates enabled and downgrades disabled. Test distribution does not publish the unsuffixed base. Operators check existing release records and objects before assigning an index.
The packaging decision retains runtime/version equality; the installed-update materials decision retains private identities and data isolation. Their Nightly naming examples do not define the test version policy. Historical release receipts and frozen archived records remain evidence of what was actually built.
The installed-update materials decision retains private identities and data isolation. Its Nightly naming examples do not define the test version policy. Historical release receipts and frozen archived records remain evidence of what was actually built.
## Alternatives considered
@@ -10,11 +10,11 @@ Status: implemented
## 决策
[Desktop 发布规则](../../../../apps/desktop/README.zh.md#release-versions)在 production 中保留完整 dsh 基础版本,并从该基础版本派生带日期和序号的测试版本。最终发布家族包版本保持一致。修改清单版本前单独记录基础版本,避免下一次测试发布追加第二个日期后缀。
[Desktop 发布规则](../../../../apps/desktop/README.zh.md#release-versions)在 production 中保留完整 dsh 基础版本,并从该基础版本派生带日期和序号的测试版本。派生出的版本[作为参数传给打包](2026-09-21-desktop-build-version-as-input.zh.md),不写入清单;它从 dsh 基础版本派生,因此下一次测试发布不会追加第二个日期后缀。
固定 Nightly feed 是分发地址,与版本派生独立。现有客户端继续使用该地址,允许预发布更新并禁止降级。test 分发不发布无后缀基础版本。操作者分配序号前检查已有发布记录和对象。
打包决策继续规定运行时与包版本一致性;安装版更新物料决策继续规定私有身份和数据隔离。其中的 Nightly 命名示例不定义测试版本规则。历史发布回执和已冻结归档保留为实际构建的证据。
安装版更新物料决策继续规定私有身份和数据隔离。其中的 Nightly 命名示例不定义测试版本规则。历史发布回执和已冻结归档保留为实际构建的证据。
## 考虑过的替代方案
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-21-desktop-build-version-as-input.md
2026-09-21-desktop-build-version-as-input.md: 8653c1ed580ac360e0c2f5145781303f15fc29b2
2026-09-21-desktop-build-version-as-input.zh.md: 0a995ab5740a73de00b2a417d07640b3c07e4690
@@ -0,0 +1,37 @@
# Agent Note: Pass the Desktop build version as an argument instead of rewriting manifests
Status: implemented
English | [中文](2026-09-21-desktop-build-version-as-input.zh.md)
## Problem
[Deriving Desktop test versions](2026-09-16-desktop-release-version-derivation.md) fixed what a test build is called but not where that name lives. Publishing one meant running `release:dsh` to rewrite the version in every release-family manifest and the lockfile — 295 files — because packaging, the update feed, and upload validation each read the version from the checkout. Those edits are never committed, so a test build left the working tree dirty until someone reverted it, and a reverted tree no longer describes the artifacts that were published. The index in `<base>.YYYYMMDD.index` was also chosen by hand against the records and the bucket, which is a lookup a script can do.
Two more facts about a build were unrecoverable afterwards. A build handed to a colleague or pushed to a test feed is reachable from no tag, and the build tree it came from is not a checkout, so nothing connected an installer to its sources. A production release was likewise recorded only in the bucket.
## Decision
The version a build publishes is an argument. `--build-version` names it, `--build-version auto` proposes the next index for the day, and the value reaches electron-builder through `extraMetadata`, the update feed, and the upload validation as one input. Manifests keep the product version, so no packaging run modifies tracked files.
The version rules in the [Desktop release rules](../../../../apps/desktop/README.md#release-versions) are unchanged: production publishes the dsh base, a prerelease base takes `.YYYYMMDD.index`, and a stable base takes `-test.YYYYMMDD.index`. Validation uses `semver` itself, because `electron-updater` compares feed versions with `semver.gt` against the installed `app.getVersion()`.
This supersedes two requirements of that note. Release-family manifests are no longer rewritten, and the shell version no longer equals the bundled runtime version: the runtime is the dsh package at the product version, and `verifyDesktopRuntime` receives the version whoever prepared that tree wrote, which installed-update qualification rewrites for its own materials. The application already reported the two separately to the mandatory update policy.
Every artifact records `dshBuildCommit` and `dshBuildDirty` in its manifest. A production upload tags the packaged commit as `desktop-v<version>` after the artifacts are public, and reports the command to run by hand rather than failing an upload that already completed; a build from a modified checkout is not tagged. Test and local builds are deliberately left untagged, because a tag per test build would bury the releases.
Upload reads the published version from the completion record packaging wrote, not from a variable, so [release fields still come only from the target file](../../../../apps/desktop/README.md#release-versions).
## Alternatives considered
**Keep rewriting manifests and revert afterwards.** The dirty tree is the defect, and a revert races anything else reading the workspace. It also leaves the published artifacts describing a state the repository no longer has.
**Rewrite only the packed runtime's manifest in a temporary copy.** The bundled dsh would then claim a version that does not exist on npm, and the copy would have to be kept consistent with the lockfile for no gain.
**Number every build automatically without an argument.** Operators confirm the version with the user before packaging. Automatic numbering is offered as `auto`, which prints what it chose, rather than as the default.
**Tag every build.** Test feeds receive builds continuously; tagging each one would make `desktop-v*` useless for finding releases. Artifacts carry their commit instead.
## Consequences
A packaging run leaves the repository unchanged, so the tree that built an artifact is the tree the tag or the recorded commit names. `auto` contacts the destination bucket, including under `--check`, and falls back to the local output directory when no bucket is configured or the listing cannot complete within its deadline; a partial listing is discarded rather than risking a reused index that would overwrite a published installer. Uploading a production release now writes to the repository, which earlier release automation deliberately avoided; the write is one tag, performed by the operator's own command after the upload succeeds.
@@ -0,0 +1,37 @@
# Agent Note:Desktop 发布版本改为命令参数,不再改写清单
Status: implemented
[English](2026-09-21-desktop-build-version-as-input.md) | 中文
## 问题
[从完整 dsh 版本派生 Desktop 测试版本](2026-09-16-desktop-release-version-derivation.zh.md)确定了测试构建叫什么,但没有确定这个名字存在哪里。发布一次测试构建要先运行 `release:dsh`,把版本写进所有发布家族清单和锁文件——295 个文件——因为打包、更新 feed 和上传校验都各自从工作区读取版本。这些改动从不提交,所以每次测试构建都会留下脏工作区直到有人还原,而还原后的工作区又不再描述已经发布出去的产物。`<base>.YYYYMMDD.index` 里的序号同样靠人对着发布记录和 bucket 挑选,而这是脚本可以完成的查询。
另有两件事在构建之后无法还原。交给同事或推到测试 feed 的构建没有任何标签可查,它来自的构建树也不是工作区,因此没有任何东西把安装包和源码连起来。production 发布同样只在 bucket 里留下痕迹。
## 决策
构建发布的版本是一个参数。`--build-version` 指定它,`--build-version auto` 给出当天的下一个序号,该值经 `extraMetadata` 进入 electron-builder,并作为同一个输入贯穿更新 feed 与上传校验。清单保留产品版本,因此任何打包运行都不修改被跟踪的文件。
[Desktop 发布规则](../../../../apps/desktop/README.zh.md#release-versions)中的版本规则不变:production 发布 dsh 基础版本,预发布基础版本追加 `.YYYYMMDD.index`,稳定基础版本追加 `-test.YYYYMMDD.index`。校验直接使用 `semver`,因为 `electron-updater` 就是用 `semver.gt` 把 feed 版本与已安装的 `app.getVersion()` 比较。
本决策取代上述 Note 的两条要求。发布家族清单不再被改写;外壳版本也不再等于内置运行时版本:内置运行时就是产品版本的 dsh 包,`verifyDesktopRuntime` 接收准备该运行时树的一方写入的版本,而安装升级验证会为自己的材料改写这个版本。应用本来就把两者分别上报给强制更新策略。
所有产物的清单都记录 `dshBuildCommit` 与 `dshBuildDirty`。production 上传在产物公开后把打包所用 commit 打成 `desktop-v<版本>` 标签,失败时只打印需要手工执行的命令,而不让已完成的上传变成失败;来自有改动工作区的构建不打标签。test 与本地构建有意不留标签,因为为每个测试构建打标签会淹没真正的发布。
上传从打包写下的完成记录中读取发布版本,而不是从变量读取,因此[发布字段仍然只来自目标文件](../../../../apps/desktop/README.zh.md#release-versions)。
## 考虑过的替代方案
**继续改写清单,事后还原。** 脏工作区本身就是缺陷,而还原会与任何同时读取工作区的操作竞争,也会让已发布产物所描述的状态在仓库中不复存在。
**只在临时副本里改写打包运行时的清单。** 内置 dsh 会因此宣称一个 npm 上不存在的版本,副本还得与锁文件保持一致,没有任何收益。
**不要参数,全部自动编号。** 操作者需要在打包前与用户确认版本。自动编号以 `auto` 提供并打印所选版本,而不是作为默认行为。
**为每个构建打标签。** 测试 feed 持续接收构建,逐个打标签会让 `desktop-v*` 无法再用于查找发布。改由产物自身携带 commit。
## 影响
打包运行不再改动仓库,因此构建产物的代码树就是标签或记录的 commit 所指的那棵树。`auto` 会访问目标 bucket,`--check` 下同样如此;未配置 bucket 或列举未能在期限内完成时回退到本地输出目录,不完整的列举结果会被丢弃,以免复用序号覆盖已发布的安装包。production 上传现在会写入仓库,而早先的发布自动化刻意避免这一点;这次写入只是一个标签,由操作者自己的命令在上传成功后执行。
+2
View File
@@ -54,8 +54,10 @@ External packages installed for runtime use or distributed inside the prebuilt b
| [`@openai/codex`](https://github.com/openai/codex) | Apache-2.0 |
| [`@opentelemetry/api`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/api-logs`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/core`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/exporter-logs-otlp-http`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/otlp-exporter-base`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/otlp-transformer`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/resources`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@opentelemetry/sdk-logs`](https://github.com/open-telemetry/opentelemetry-js) | Apache-2.0 |
| [`@playwright/mcp`](https://github.com/microsoft/playwright-mcp) | Apache-2.0 |
+5 -2
View File
@@ -46,7 +46,9 @@ flowchart LR
cfg --> plugin_dsh_base_jobs
plugin_dsh_base_llm_retry["llm-retry<br/>@deepseek-ai/dsh-llm-retry"]
cfg --> plugin_dsh_base_llm_retry
plugin_dsh_base_settings["settings<br/>@deepseek-ai/dsh-settings-file"]
plugin_dsh_base_config_editor["config-editor<br/>@deepseek-ai/dsh-config-editor"]
cfg --> plugin_dsh_base_config_editor
plugin_dsh_base_settings["settings<br/>@deepseek-ai/dsh-settings"]
cfg --> plugin_dsh_base_settings
plugin_dsh_base_credentials["credentials<br/>@deepseek-ai/dsh-credentials-local"]
cfg --> plugin_dsh_base_credentials
@@ -209,7 +211,8 @@ flowchart LR
| `agent-default-model` | `@deepseek-ai/dsh-agent-default-model` |
| `jobs` | `@deepseek-ai/dsh-jobs-local` |
| `llm-retry` | `@deepseek-ai/dsh-llm-retry` |
| `settings` | `@deepseek-ai/dsh-settings-file` |
| `config-editor` | `@deepseek-ai/dsh-config-editor` |
| `settings` | `@deepseek-ai/dsh-settings` |
| `credentials` | `@deepseek-ai/dsh-credentials-local` |
| `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` |
| `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` |
-1
View File
@@ -134,7 +134,6 @@
"@deepseek-ai/dsh-session-query": "workspace:^",
"@deepseek-ai/dsh-shell-env": "workspace:^",
"@deepseek-ai/dsh-settings": "workspace:^",
"@deepseek-ai/dsh-settings-file": "workspace:^",
"@deepseek-ai/dsh-subagent": "workspace:^",
"@deepseek-ai/dsh-subagent-fork-in-process": "workspace:^",
"@deepseek-ai/dsh-subagent-spawn-in-process": "workspace:^",
+22 -26
View File
@@ -19,11 +19,12 @@ import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-tool-subagent/model-selection-settings'
import { dump, load } from 'js-yaml'
import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
import { bundlePatchPaths, composeEntries } from '@deepseek-ai/dsh-app-boot'
const SETTINGS_NAMESPACE = 'agent-presets'
/** Profile entry ids whose volatile fields these scenarios edit through Settings. */
const SETTINGS_NAMESPACE = 'agent-preset-registry'
const SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE = 'subagent-model-selection-settings'
import { applyChildComposition, childSessionMeta } from '@deepseek-ai/dsh-subagent'
import { ToolCallId } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-compaction-basic'
@@ -59,25 +60,20 @@ const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
* agent's capabilities is the real thing, including both shipped presets.
*/
async function bootWeb(
settingsFile: string,
profileHome: string,
extra: PatchOptions[] = [],
profilePackages: readonly string[] = [],
profileBundles?: readonly string[],
): Promise<Context> {
const storageRoot = join(dirname(settingsFile), 'storages')
const storageRoot = join(profileHome, 'storages')
const overrides: PatchOptions[] = [
// The settings row defaults to `$DSH_HOME/settings.yaml`. Left alone it
// reads the developer's own document — and since the default preset is a
// setting, a stored `agent-presets.default` would decide this file's
// outcome. Point it at a temporary file to isolate settings.
{ id: 'settings', config: { path: settingsFile, watch: false } },
// storage-json's root is anchored to the real $DSH_HOME. Unpinned, this
// file writes the developer's own `~/.dsh/storages/` — and then reads it
// back on the next run, so a stored document from any other build decides
// this test's boot. Same reason the settings row above is pinned.
// this test's boot.
{ id: 'storage-json', config: { root: storageRoot } },
// Fixed Session IDs must stay inside this boot's temporary profile root.
{ id: 'session-persistence-jsonl', config: { root: join(dirname(settingsFile), 'sessions') } },
{ id: 'session-persistence-jsonl', config: { root: join(profileHome, 'sessions') } },
// Host rows with side effects outside this process: a bound port, a served
// asset tree, a telemetry exporter. `api-gateway` and `directory-picker`
// stay ENABLED on purpose — the api-proxy is the host row that injects
@@ -123,7 +119,7 @@ async function bootWeb(
{ id: 'agent-preset-registry', config: { default: 'standard' } },
...extra,
]
const home = dirname(settingsFile)
const home = profileHome
const profileDir = join(home, 'profiles', 'spec')
await mkdir(profileDir, { recursive: true })
if (profileBundles === undefined) initProfile(profileDir, ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'])
@@ -157,9 +153,15 @@ async function bootWeb(
profile = loadProfile('dsh-test', 'spec', INSTALL_ANCHOR, home, { userLayer: false })
bundlePatches = profile.layers.flatMap(layer => layer.patches)
}
const declarations = overrides.filter(patch => 'insert' in patch)
await writeFile(profile.patchPath, dump(declarations, { schema: entryListSchema }))
const launchOverrides = overrides.filter(patch => !('insert' in patch))
// Deployment defaults live in a bundle beneath the profile patch, so Settings writes are not shadowed by overlays.
const fixtureName = 'dsh-web-presets-defaults'
const fixtureDir = join(profileDir, 'node_modules', fixtureName)
await mkdir(fixtureDir, { recursive: true })
await writeFile(join(fixtureDir, 'package.json'), JSON.stringify({ name: fixtureName, version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(fixtureDir, 'cordis.patch.yml'), JSON.stringify(overrides))
const manifest = JSON.parse(await readFile(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
manifest.dsh.profile.bundles.push(fixtureName)
await writeFile(join(profileDir, 'package.json'), JSON.stringify(manifest))
const resolution = await createRuntimeResolution({ installAnchor: INSTALL_ANCHOR, home, profile })
const rootConfig = join(profileDir, 'cordis.yml')
await writeFile(rootConfig, '[]\n')
@@ -167,7 +169,7 @@ async function bootWeb(
bootCtx.provide('profileContext', { name: 'spec', dir: profileDir, patchPath: profile.patchPath,
installAnchor: INSTALL_ANCHOR, home, cwd: home,
startedBundles: profileBundles ?? ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'],
overlays: launchOverrides, telemetryDisabledEnv: '1' })
overlays: [], telemetryDisabledEnv: '1' })
await bootCtx.plugin(PluginPackages, { resolution })
bootCtx.provide('connection', {
fetch: { register: () => () => {} },
@@ -202,9 +204,7 @@ function enablePresetTool(composition: string, id: string): string {
let ctx: Context
beforeAll(async () => {
const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
await writeFile(settingsFile, '{}\n')
ctx = await bootWeb(settingsFile)
ctx = await bootWeb(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')))
}, 120_000)
describe('the shipped Web composition', () => {
@@ -544,10 +544,8 @@ describe('product Bundle and user-preset intersection', () => {
async function bootProducts(installed: readonly Product[]): Promise<Context> {
const root = await mkdtemp(join(tmpdir(), 'dsh-product-presets-'))
const definitions: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[] = []
const settingsFile = join(root, 'settings.yaml')
const standardConfig = composeEntries([webPatches('test')]).find(row => row.id === 'preset-standard')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition
const standard = dump(standardConfig.plugins, { schema: entryListSchema })
await writeFile(settingsFile, '{}\n')
for (const id of presetIds) {
let composition = standard
if (id === 'products-codex' || id === 'products-both') {
@@ -566,7 +564,7 @@ describe('product Bundle and user-preset intersection', () => {
? '@deepseek-ai/dsh-subagent-codex'
: '@deepseek-ai/dsh-subagent-claude-code'
)
return await bootWeb(settingsFile, [{ insert: definitions } ], installed.map(packageDir), [
return await bootWeb(root, [{ insert: definitions }], installed.map(packageDir), [
'@deepseek-ai/dsh-base',
'@deepseek-ai/dsh-web-app',
...installed.map(packageName),
@@ -639,10 +637,8 @@ describe('a user preset declared from the shipped cordis rows', () => {
// `tool-cordis` row only registers the tools. Before that split the copy
// failed to mount: its row re-registered provider "Service".
const root = await mkdtemp(join(tmpdir(), 'dsh-copied-preset-'))
const settingsFile = join(root, 'settings.yaml')
await writeFile(settingsFile, '{}\n')
const cordis = composeEntries([webPatches('test')]).find(row => row.id === 'preset-cordis')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition
const copyCtx = await bootWeb(settingsFile, [{ insert: [{
const copyCtx = await bootWeb(root, [{ insert: [{
id: 'preset-cordis-copy', name: '@deepseek-ai/dsh-agent-preset',
config: { ...cordis, id: 'cordis-copy', name: 'Cordis copy' },
}] }])
@@ -814,7 +810,7 @@ describe('the default preset as a user setting', () => {
expect((await ctx.agentPresets.remoteExportList()).modeSelectionEnabled).toBe(true)
expect(ctx.agentPresets.defaultId).toBe('standard')
await ctx.settings.update(SETTINGS_NAMESPACE, { default: 'minimal' })
await ctx.settings.update(SETTINGS_NAMESPACE, { selectedDefault: 'minimal' })
try {
expect(ctx.agentPresets.defaultId).toBe('minimal')
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/README.md
README.md: 0b22cc7325cea78e11df197dc3ccdc0210e21b32
README.zh.md: 1d4d807c4b263726ee58fc3c3a0066d2eb15bbb7
README.md: 4de8eb539bba42919fd29740bb2741566f460ab1
README.zh.md: 9e733caae70fc3fe4d0131548a14660cddbd2248
+17 -7
View File
@@ -105,9 +105,9 @@ The Web counterparts are `pnpm run dev:web` and `pnpm run start:web`, documented
### Release versions
Before each Desktop packaging run, first confirm the complete version string with the current user. Check the selected deployment, dsh base version, retained release records, and published objects, then propose the exact version for approval. Do not change release-family manifests or start packaging until the user confirms that version; the deployment setting alone does not authorize a version choice.
Before each Desktop packaging run, first confirm the complete version string with the current user. Check the selected deployment, dsh base version, retained release records, and published objects, then propose the exact version for approval. Do not start packaging until the user confirms that version; the deployment setting alone does not authorize a version choice.
Record the current dsh version as the base before changing any manifests. A production Desktop release uses that exact version, including any `alpha`, `beta`, or `rc` identifiers. A test release preserves the complete prerelease base and appends `.YYYYMMDD.index`; a stable base uses `-test.YYYYMMDD.index` instead.
Record the current dsh version as the base. A production Desktop release uses that exact version, including any `alpha`, `beta`, or `rc` identifiers. A test release preserves the complete prerelease base and appends `.YYYYMMDD.index`; a stable base uses `-test.YYYYMMDD.index` instead.
| dsh base | Production Desktop | Test Desktop example |
|---|---|---|
@@ -116,13 +116,23 @@ Record the current dsh version as the base before changing any manifests. A prod
| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` |
| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` |
Use the actual creation date in Asia/Shanghai. For each base and date, start the index at 1 and increment after checking retained release records and published objects; never reuse a published version. Derive once from the recorded base, not from a manifest already carrying a test suffix. The final root, Desktop, bundled dsh, private Desktop Host, and other release-family manifests must all carry the same derived version. Test distribution does not publish the corresponding unsuffixed base.
Use the actual creation date in Asia/Shanghai. For each base and date, start the index at 1 and increment after checking retained release records and published objects; never reuse a published version. Test distribution does not publish the corresponding unsuffixed base.
Pass the confirmed version to the packaging command as `--build-version`, which reaches the artifact names, the update feed, and the upload validation as one value. The manifests keep the product version, so a test build no longer rewrites the release family and leaves nothing to revert:
```sh
pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1
```
`--build-version auto` proposes the next index for today, reading the published objects in the destination bucket and falling back to this target's local output directory when no bucket is configured or the listing cannot finish within its deadline. Confirm the proposal it prints before an upload; a run script forwards `--` on its own, and the packaging entry accepts it either way.
A production release publishes the product version and takes no `--build-version`. Uploading one tags the packaged commit as `desktop-v<version>` once the artifacts are public; a build from a modified checkout is not tagged, and a tagging failure prints the command to run by hand rather than failing a completed upload. Test and local builds are deliberately left untagged, and every artifact records `dshBuildCommit` and `dshBuildDirty` in its manifest so a build handed over directly remains traceable.
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 [version decision](../../.agents/notes/implemented/process/2026-09-16-desktop-release-version-derivation.md) explains why the channel does not supply the prerelease identifier.
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. 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.
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.
Every package command checks the application ID, update origin, and mode-specific signing configuration before building or downloading. 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 and explicit unsigned builds 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. Run the same checks separately:
Every package command checks the application ID, update origin, and mode-specific 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 and explicit unsigned builds 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:
```sh
pnpm --dir apps/desktop run check:package
@@ -152,7 +162,7 @@ Desktop packs workspace packages locally and installs external dependencies thro
The [Office conversion provider](../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. Complete native engine packages, including executables, libraries, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai/`. The Desktop Host resolves engine manifests to these physical directories so native subprocesses can read their resources; the JavaScript API and WASM engine remain in ASAR. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in).
The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned Windows builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization.
The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. The payload smoke resolves the search tool’s ripgrep executable and verifies text search and file enumeration. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned Windows builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization.
Windows release qualification also runs [directory and replacement checks](scripts/smoke-windows.ps1) manually after the Desktop build. Set `$Makensis`, `$SevenZip`, and `$PluginDir` to the pinned builder’s NSIS compiler, 7-Zip executable, and x86-unicode NSIS plugin directory. From the repository root, run the command below. It verifies directory replacement and rollback, and both locked-file replacement modes; it is not part of the unit-test lane.
@@ -204,7 +214,7 @@ macOS signing visits real files without following Framework symlink aliases. PAK
macOS runtime preparation caches verified single-architecture Mach-O signatures in `.desktop-build/targets/<target>/signature-cache`. Keys include input bytes and permissions, the signing probe’s actual leaf certificate, identifier, entitlement bytes, macOS version, and signing tools and policy. Git commits do not determine reuse: uncommitted byte changes invalidate the affected file. Every hit verifies cached bytes, the strict signature, certificate, identifier, entitlements, secure timestamp and hardened runtime before replacing an unchanged input. Universal binaries are signed each time. Runtime integrity and smoke checks, App signing, and Apple notarization still run. The cache requires trusted local build storage. Cache corruption or unsafe links fail the build; stop packaging before deleting the affected cache directory and retrying. Successful signing stages prune complete entries to a one-GiB payload budget; interrupted temporary entries require manual removal. Concurrent eviction can fail a reader safely. Logs report hit, miss and uncached counts.
Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together.
Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (published version, product version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Runtime preparation records package staging, installation, materialization, signing, manifests, smoke checks, descriptor verification and cleanup separately. Nested phase durations overlap and must not be added together.
App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. Both platforms record parent-process packaging failures and print redacted diagnostics, including proxy recovery instructions, to the terminal. The configuration-only `check:package` command creates no run log.
+17 -7
View File
@@ -105,9 +105,9 @@ Web 侧的对应命令是 `pnpm run dev:web` 与 `pnpm run start:web`,见[开
### 发布版本
每次 Desktop 打包前,第一步都要与当前用户确认完整版本号。检查所选部署环境、dsh 基础版本、保留的发布记录和已发布对象,再提出准确版本供用户确认。用户确认前,不得修改发布家族清单或启动打包;仅选择部署环境不代表用户已认可版本号。
每次 Desktop 打包前,第一步都要与当前用户确认完整版本号。检查所选部署环境、dsh 基础版本、保留的发布记录和已发布对象,再提出准确版本供用户确认。用户确认前不得启动打包;仅选择部署环境不代表用户已认可版本号。
修改任何清单前,记录当前 dsh 版本作为基础版本。production Desktop 使用完全相同的版本,包括其中的 `alpha`、`beta` 或 `rc` 标识。test 发布保留完整的预发布基础版本并追加 `.YYYYMMDD.index`;稳定基础版本则追加 `-test.YYYYMMDD.index`。
记录当前 dsh 版本作为基础版本。production Desktop 使用完全相同的版本,包括其中的 `alpha`、`beta` 或 `rc` 标识。test 发布保留完整的预发布基础版本并追加 `.YYYYMMDD.index`;稳定基础版本则追加 `-test.YYYYMMDD.index`。
| dsh 基础版本 | production Desktop | test Desktop 示例 |
|---|---|---|
@@ -116,13 +116,23 @@ Web 侧的对应命令是 `pnpm run dev:web` 与 `pnpm run start:web`,见[开
| `0.1.6-rc.3` | `0.1.6-rc.3` | `0.1.6-rc.3.20260916.1` |
| `0.1.6` | `0.1.6` | `0.1.6-test.20260916.1` |
日期使用实际创建时的 Asia/Shanghai 日期。每个基础版本、每天的序号从 1 开始,检查保留的发布记录与已发布对象后递增;绝不复用已发布版本。只从记录的基础版本派生一次,不从已有测试后缀的清单继续追加。最终根包、Desktop、内置 dsh、私有 Desktop Host 和其他发布家族清单必须全部使用同一个派生版本。test 分发不发布对应的无后缀基础版本。
日期使用实际创建时的 Asia/Shanghai 日期。每个基础版本、每天的序号从 1 开始,检查保留的发布记录与已发布对象后递增;绝不复用已发布版本。test 分发不发布对应的无后缀基础版本。
把确认后的版本通过 `--build-version` 传给打包命令,该值同时决定产物文件名、更新 feed 与上传校验。清单保留产品版本,因此 test 打包不再改写发布家族,也不留下需要还原的改动:
```sh
pnpm --dir apps/desktop run package:win:x64 --build-version 0.1.6-alpha.1.20260916.1
```
`--build-version auto` 会给出当天的下一个序号:读取目标 bucket 中已发布的对象,未配置 bucket 或列举未能在期限内完成时回退到本目标的本地输出目录。上传前请确认它打印的版本号;run script 会自行透传 `--`,打包入口两种写法都接受。
production 发布使用产品版本本身,不传 `--build-version`。其上传成功后会把打包所用 commit 打成 `desktop-v<版本>` 标签;来自有改动工作区的构建不打标签,打标签失败也只打印手工命令,不会让已完成的上传变成失败。test 与本地构建有意不留标签,而所有产物的清单都记录 `dshBuildCommit` 与 `dshBuildDirty`,直接分发的构建同样可溯源。
版本派生不改变固定更新通道,也不改变 `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/implemented/process/2026-09-16-desktop-release-version-derivation.zh.md)解释为什么不能用通道名替换预发布标识。
打包、上传以及手动 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 同样在运行前生成目标文件。
打包、上传以及手动 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 同样在运行前生成目标文件。
每条打包命令在构建与下载前检查应用 ID、更新地址和该模式需要的签名配置。macOS 检查身份、Team ID、一套完整公证凭据、`CSC_LINK` 指定的可读本地 p12 文件、显式配置的 `CSC_KEY_PASSWORD`,以及引用的 API Key 和钥匙串文件;Windows 检查公开代码签名证书、SignTool 文件、容器名称和 PIN 格式。仅准备 Windows 资源或显式未签名打包不要求签名凭据。配置检查不验证 PIN 是否正确、Token 是否登录、钥匙串是否解锁或 Apple 是否接受凭据;实际签名与公证负责这些检查。单独运行相同检查:
每条打包命令在构建与下载前检查应用 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` 下同样如此。单独运行相同检查:
```sh
pnpm --dir apps/desktop run check:package
@@ -152,7 +162,7 @@ Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安
[Office 转换提供方](../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整原生引擎包(包括可执行文件、库、数据、许可证和 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai/` 下。Desktop Host 将引擎清单解析到这些物理目录,使原生子进程能读取资源;JavaScript API 和 WASM 引擎保留在 ASAR 中。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。
打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和 Windows 未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。
打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。产物 smoke 解析搜索工具使用的 ripgrep 可执行文件,并验证文本搜索和文件枚举。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和 Windows 未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。
Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检查](scripts/smoke-windows.ps1)。将 `$Makensis`、`$SevenZip` 和 `$PluginDir` 分别设为锁定版本构建器的 NSIS 编译器、7-Zip 可执行文件和 x86-unicode NSIS 插件目录。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。
@@ -204,7 +214,7 @@ macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK
macOS 运行时准备将已验证的单架构 Mach-O 签名缓存在 `.desktop-build/targets/<target>/signature-cache`。缓存键包含输入字节与权限、签名探针实际使用的叶证书、签名标识、entitlement 字节、macOS 版本,以及签名工具与策略。复用不取决于 Git 提交:未提交的字节变更会使对应文件失效。每次命中都验证缓存字节、严格签名、证书、标识、entitlements、安全时间戳和 hardened runtime,再替换未被并发修改的输入。通用二进制每次重新签名。运行时完整性与 smoke 检查、App 签名和 Apple 公证仍会执行。缓存要求受信任的本地构建存储。缓存损坏或不安全链接会令构建失败;停止打包后删除对应缓存目录再重试。成功的签名阶段会将完整缓存条目的内容总量裁剪至一 GiB;中断留下的临时条目需手动清理。并发淘汰可能使读取方安全失败。日志记录命中、未命中及未缓存数量。
Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。
Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(发布版本、产品版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。运行时准备分别记录包暂存、安装、依赖树复制、签名、清单生成、smoke 检查、描述文件校验和清理。嵌套阶段的耗时存在重叠,不能直接相加。
App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。两个平台均记录父进程打包失败,并在终端显示脱敏诊断,包括代理恢复操作指引。仅检查配置的 `check:package` 命令不创建运行日志。
@@ -61,6 +61,7 @@ export interface DesktopElectronBuilderConfig {
* @param hostPlatform - Build-host platform used when no explicit target is present.
* @param hostArch - Build-host architecture used when no explicit target is present.
* @param preparedRuntime - Verified private qualification runtime; ordinary releases use target-owned resources.
* @param preparedRuntimeVersion - Version that private runtime declares, which qualification rewrites away from the product version.
* @returns electron-builder configuration.
*/
export function createElectronBuilderConfig(
@@ -68,6 +69,7 @@ export function createElectronBuilderConfig(
hostPlatform?: NodeJS.Platform,
hostArch?: string,
preparedRuntime?: string,
preparedRuntimeVersion?: string,
): DesktopElectronBuilderConfig
declare const electronBuilderConfig: DesktopElectronBuilderConfig
@@ -0,0 +1,32 @@
/** Commit a build came from, and whether its checkout carried uncommitted changes. */
export interface DesktopBuildCommit {
readonly commit: string
readonly dirty: boolean
}
/** Environment variable that carries the packaged commit. */
export const DESKTOP_BUILD_COMMIT_ENV: 'DSH_DESKTOP_BUILD_COMMIT'
/** Environment variable that records whether the packaged checkout had uncommitted changes. */
export const DESKTOP_BUILD_DIRTY_ENV: 'DSH_DESKTOP_BUILD_DIRTY'
/**
* Read the checkout's current commit and whether it carries uncommitted changes.
* @param repositoryRoot - Directory to inspect.
* @returns The commit being packaged and whether its tree was modified.
*/
export function readDesktopBuildCommit(repositoryRoot: string): DesktopBuildCommit
/**
* Resolve the commit a parent packaging process recorded.
* @param env - Packaging environment.
* @returns The packaged commit, or undefined outside a packaging run.
*/
export function resolveDesktopBuildCommit(env: NodeJS.ProcessEnv): DesktopBuildCommit | undefined
/**
* Describe the packaged commit as the environment variables child processes read.
* @param packaged - Commit and tree state to pass down.
* @returns Variables to merge into a child environment.
*/
export function desktopBuildCommitEnvironment(packaged: DesktopBuildCommit): Record<string, string>
@@ -0,0 +1,57 @@
/**
* Carry the commit a build came from into its artifacts.
*
* A build that reaches a colleague or a test feed is not reachable from a tag,
* so the only way back to its sources is what the build recorded about itself.
* The packaging entry reads the checkout once and passes the result to every
* child process, which run against a build tree rather than a checkout.
*/
import { execFileSync } from 'node:child_process'
/** Environment variable that carries the packaged commit. */
export const DESKTOP_BUILD_COMMIT_ENV = 'DSH_DESKTOP_BUILD_COMMIT'
/** Environment variable that records whether the packaged checkout had uncommitted changes. */
export const DESKTOP_BUILD_DIRTY_ENV = 'DSH_DESKTOP_BUILD_DIRTY'
/**
* Read the checkout's current commit and whether it carries uncommitted changes.
* @param {string} repositoryRoot - Directory to inspect.
* @returns {{ commit: string, dirty: boolean }} The commit being packaged and whether its tree was modified.
*/
export function readDesktopBuildCommit(repositoryRoot) {
const git = (args) => execFileSync('git', args, { cwd: repositoryRoot, encoding: 'utf8' }).trim()
return {
commit: git(['rev-parse', 'HEAD']),
dirty: git(['status', '--porcelain', '--untracked-files=normal']) !== '',
}
}
/**
* Resolve the commit a parent packaging process recorded.
* @param {NodeJS.ProcessEnv} env - Packaging environment.
* @returns {{ commit: string, dirty: boolean } | undefined} The packaged commit, or undefined outside a packaging run.
*/
export function resolveDesktopBuildCommit(env) {
const commit = env[DESKTOP_BUILD_COMMIT_ENV]?.trim()
if (commit === undefined || commit === '') return undefined
if (!/^[0-9a-f]{40}$/u.test(commit)) throw new Error(`desktop build commit: ${DESKTOP_BUILD_COMMIT_ENV} must be a commit hash`)
const dirty = env[DESKTOP_BUILD_DIRTY_ENV]?.trim()
if (dirty !== undefined && dirty !== '' && dirty !== '0' && dirty !== '1') {
throw new Error(`desktop build commit: ${DESKTOP_BUILD_DIRTY_ENV} must be 0 or 1`)
}
return { commit, dirty: dirty === '1' }
}
/**
* Describe the packaged commit as the environment variables child processes read.
* @param {{ commit: string, dirty: boolean }} packaged - Commit and tree state to pass down.
* @returns {Record<string, string>} Variables to merge into a child environment.
*/
export function desktopBuildCommitEnvironment(packaged) {
return {
[DESKTOP_BUILD_COMMIT_ENV]: packaged.commit,
[DESKTOP_BUILD_DIRTY_ENV]: packaged.dirty ? '1' : '0',
}
}
@@ -0,0 +1,156 @@
/**
* Suggest the next build version for a product version, so the sequence number
* is derived rather than remembered.
*
* `apps/desktop/README.md` gives the form as `<product version>.<date>.<index>`
* for a prerelease base and `<product version>-test.<date>.<index>` for a
* stable one. What makes an index correct is which ones are taken, and that is
* recorded where the builds went: the update bucket for an uploaded build, the
* local output directory for one that was only handed over. Asking the bucket
* first is what keeps a test feed's numbering unique across machines, and a
* fresh CI checkout has no local artifacts to fall back on.
*
* Reusing an index would overwrite a published installer and invalidate the
* checksum in the feed that already points at it, so a bucket that answers
* must answer completely: the listing follows its pages, and a query that
* cannot finish within the deadline falls back to the local scan rather than
* numbering against a partial answer.
*/
import { readdir } from 'node:fs/promises'
import { parse } from 'semver'
import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs'
import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs'
import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts'
import type { DesktopPackageTargetName } from './package-target.ts'
/** How long the whole bucket listing may take before the suggestion falls back to local artifacts. */
const LISTING_DEADLINE_MS = 8_000
/** Objects one listing page may return. */
const LISTING_PAGE_SIZE = 1000
/** Artifact name electron-builder writes for one build, on either platform. */
const ARTIFACT = /(?:^|\/)deepseek-harness-(?<version>.+)-(?:mac|win)-(?:arm64|x64)\.(?:exe|dmg|zip)$/u
/** Inputs that decide which versions are already taken. */
export interface DesktopBuildVersionSuggestionOptions {
readonly productVersion: string
readonly target: DesktopPackageTargetName
readonly environment: NodeJS.ProcessEnv
/** Date segment to number within; defaults to today where the build runs. */
readonly date?: string
/** Directory electron-builder writes installers into for this build. */
readonly artifactsRoot: string
}
/**
* Format a date as the convention's segment.
* @param date - Date to format.
* @returns The date as `YYYYMMDD` in the build host's own time zone.
*/
export function desktopBuildDateSegment(date: Date = new Date()): string {
const month = String(date.getMonth() + 1).padStart(2, '0')
return `${String(date.getFullYear())}${month}${String(date.getDate()).padStart(2, '0')}`
}
/**
* Read the sequence numbers already used for one product version and date.
* @param versions - Versions found in a bucket or directory.
* @param prefix - Everything a numbered build carries before its index.
* @returns Every index present, unordered.
*/
function sequenceNumbers(versions: Iterable<string>, prefix: string): number[] {
const numbers: number[] = []
for (const version of versions) {
if (!version.startsWith(prefix)) continue
const index = version.slice(prefix.length)
if (/^\d+$/u.test(index)) numbers.push(Number(index))
}
return numbers
}
/**
* Read the versions one output directory already holds.
* @param artifactsRoot - Directory electron-builder wrote installers into.
* @returns Versions parsed from artifact names.
*/
async function localVersions(artifactsRoot: string): Promise<string[]> {
const entries = await readdir(artifactsRoot).catch(() => [])
return entries.map(entry => ARTIFACT.exec(entry)?.groups?.version)
.filter((version): version is string => version !== undefined && parse(version) !== null)
}
/**
* Read every version one update bucket publishes for a target.
* @param options - Product version, target, and environment naming the bucket.
* @returns Versions parsed from object names, or undefined when the bucket cannot be listed completely in time.
*/
async function remoteVersions(options: DesktopBuildVersionSuggestionOptions): Promise<string[] | undefined> {
const platform = options.target === 'win-x64' ? 'win32' as const : 'darwin' as const
const arch = options.target === 'mac-arm64' ? 'arm64' : 'x64'
// An unconfigured destination has nothing to be unique against; an invalid one must not be mistaken for it.
if (options.environment[DESKTOP_AUTO_UPDATE_ENV] === undefined
&& options.environment.DOWNLOAD_TEST_ORIGIN === undefined) return undefined
const update = resolveDesktopUploadConfig(options.environment, platform, arch)
const secretId = options.environment[update.secretIdEnvName]?.trim()
const secretKey = options.environment[update.secretKeyEnvName]?.trim()
if (secretId === undefined || secretId === '' || secretKey === undefined || secretKey === '') return undefined
// The SDK has no per-request abort, so its own timeout is what releases an unanswered socket.
const cos = createDesktopCos({ secretId, secretKey }, LISTING_DEADLINE_MS)
const deadline = Date.now() + LISTING_DEADLINE_MS
const versions: string[] = []
let marker: string | undefined
try {
do {
const page = await Promise.race([
new Promise<{ keys: string[]; next: string | undefined }>((resolveListing, rejectListing) => {
cos.getBucket({
Bucket: update.bucket, Region: DESKTOP_COS_REGION, MaxKeys: LISTING_PAGE_SIZE,
Prefix: `${update.binaryKeyPrefix}/deepseek-harness-`, ...marker === undefined ? {} : { Marker: marker },
}, (error, data) => {
if (error !== null && error !== undefined) rejectListing(error instanceof Error ? error : new Error(String(error)))
else {
resolveListing({
keys: (data?.Contents ?? []).map(object => object.Key),
next: data?.IsTruncated === 'true' ? data.NextMarker ?? data.Contents?.at(-1)?.Key : undefined,
})
}
})
}),
new Promise<never>((_resolveDeadline, rejectDeadline) => {
setTimeout(() => rejectDeadline(new Error('listing deadline')), Math.max(0, deadline - Date.now())).unref()
}),
])
for (const key of page.keys) {
const version = ARTIFACT.exec(key)?.groups?.version
if (version !== undefined && parse(version) !== null) versions.push(version)
}
marker = page.next
} while (marker !== undefined)
}
catch (unfinished) {
// Numbering against a partial listing could reuse a published index, so an unfinished query yields nothing.
process.stdout.write(`desktop package: the update bucket did not answer completely (${
unfinished instanceof Error ? unfinished.message : String(unfinished)}); numbering from local artifacts\n`)
return undefined
}
return versions
}
/**
* Suggest the next build version for today, numbering after what is already taken.
* @param options - Product version, target, and environment to search.
* @returns A validated build version whose index is free.
*/
export async function suggestDesktopBuildVersion(options: DesktopBuildVersionSuggestionOptions): Promise<string> {
const prefix = `${desktopBuildVersionPrefix(options.productVersion)}${options.date ?? desktopBuildDateSegment()}.`
const published = await remoteVersions(options)
const taken = published ?? await localVersions(options.artifactsRoot)
const used = sequenceNumbers(taken, prefix)
const next = used.length === 0 ? 1 : Math.max(...used) + 1
const suggestion = validateDesktopBuildVersion(`${prefix}${String(next)}`, options.productVersion)
process.stdout.write(`desktop package: numbering ${suggestion} after ${String(used.length)} ${
published === undefined ? 'local artifact' : 'published build'}${used.length === 1 ? '' : 's'} for ${prefix}*\n`)
return suggestion
}
@@ -0,0 +1,25 @@
/** Environment variable that carries the build version through one packaging and upload run. */
export const DESKTOP_BUILD_VERSION_ENV: 'DSH_DESKTOP_BUILD_VERSION'
/**
* Validate a build version against the product version it extends.
* @param buildVersion - Version this build publishes.
* @param productVersion - Version the manifests declare.
* @returns The version as semver normalizes it, which is what the artifacts will carry.
*/
export function validateDesktopBuildVersion(buildVersion: string, productVersion: string): string
/**
* Resolve the version a build publishes.
* @param env - Packaging or upload environment.
* @param productVersion - Version the manifests declare.
* @returns The build version when one is present, otherwise the product version.
*/
export function resolveDesktopBuildVersion(env: NodeJS.ProcessEnv, productVersion: string): string
/**
* Everything a build version carries before its date, including the trailing separator.
* @param productVersion - Version the manifests declare.
* @returns The prefix shared by every build version of that product version.
*/
export function desktopBuildVersionPrefix(productVersion: string): string
@@ -0,0 +1,100 @@
/**
* Resolve the version one build publishes, which is not always the version the
* repository declares.
*
* A production release publishes the version in the manifests, aligned with the
* `dsh` npm package. A test build publishes a version that appends a date and a
* sequence number, so one test feed can carry several builds of a single
* product version: `0.1.6-alpha.1.20260916.1` from a prerelease base and
* `0.1.6-test.20260916.1` from a stable one, as the release versions table in
* `apps/desktop/README.md` gives them. Passing that version here keeps it out
* of the manifests, so the tracked version stays the product's while the build
* version reaches electron-builder, the update feed, and the upload validation
* as one input.
*
* `electron-updater` compares feed versions with `semver.gt` against the
* installed `app.getVersion()`, so validation uses the same library. Sequence
* numbers order builds within a feed under either form. The forms differ only
* against the base itself: builds extending a prerelease outrank it, while
* `0.1.6-test.1` ranks below `0.1.6`, which is why the stable form belongs to a
* test feed that never serves the production release.
*/
import { parse } from 'semver'
/** Environment variable that carries the build version through one packaging and upload run. */
export const DESKTOP_BUILD_VERSION_ENV = 'DSH_DESKTOP_BUILD_VERSION'
/** Prerelease field that opens a test build's suffix on a stable product version. */
const STABLE_TEST_FIELD = 'test'
/**
* Parse a version the updater would accept.
* @param {string} version - Version to read.
* @param {string} label - Description used in failures.
* @returns {import('semver').SemVer} The parsed version.
*/
function parseVersion(version, label) {
const parsed = parse(version, { loose: false })
if (parsed === null) throw new Error(`desktop build version: ${label} ${version} is not a version`)
if (parsed.build.length > 0) {
// Build metadata does not participate in precedence, so two builds would compare equal to the updater.
throw new Error(`desktop build version: ${label} ${version} cannot carry build metadata`)
}
return parsed
}
/**
* The prerelease fields every build version for one product version starts with.
* @param {import('semver').SemVer} product - Parsed product version.
* @returns {readonly (string | number)[]} Fields a build version must repeat before its date.
*/
function requiredFields(product) {
return product.prerelease.length === 0 ? [STABLE_TEST_FIELD] : product.prerelease
}
/**
* Validate a build version against the product version it extends.
* @param {string} buildVersion - Version this build publishes.
* @param {string} productVersion - Version the manifests declare.
* @returns {string} The version as semver normalizes it, which is what the artifacts will carry.
*/
export function validateDesktopBuildVersion(buildVersion, productVersion) {
const build = parseVersion(buildVersion, 'build version')
const product = parseVersion(productVersion, 'product version')
if (build.version === product.version) return build.version
if (build.compareMain(product) !== 0) {
throw new Error(`desktop build version: ${buildVersion} must extend product version ${productVersion}`)
}
const required = requiredFields(product)
const extendsProduct = build.prerelease.length > required.length
&& required.every((field, index) => build.prerelease[index] === field)
if (!extendsProduct) {
throw new Error(`desktop build version: ${buildVersion} must extend ${productVersion} as ${
desktopBuildVersionPrefix(productVersion)}<date>.<sequence>`)
}
return build.version
}
/**
* Resolve the version a build publishes.
* @param {NodeJS.ProcessEnv} env - Packaging or upload environment.
* @param {string} productVersion - Version the manifests declare.
* @returns {string} The build version when one is present, otherwise the product version.
*/
export function resolveDesktopBuildVersion(env, productVersion) {
const buildVersion = env[DESKTOP_BUILD_VERSION_ENV]?.trim()
if (buildVersion === undefined || buildVersion === '') return productVersion
return validateDesktopBuildVersion(buildVersion, productVersion)
}
/**
* Everything a build version carries before its date, including the trailing separator.
* @param {string} productVersion - Version the manifests declare.
* @returns {string} The prefix shared by every build version of that product version.
*/
export function desktopBuildVersionPrefix(productVersion) {
const product = parseVersion(productVersion, 'product version')
const [release] = product.version.split('-')
return `${release}-${requiredFields(product).join('.')}.`
}
+3 -2
View File
@@ -29,9 +29,10 @@ interface CosRequestOptions {
* caller names none; that header is removed here so uploading leaves cache policy to deployment
* infrastructure.
* @param credentials SecretId and SecretKey for the selected deployment.
* @param timeoutMs Request-level inactivity deadline; a caller that must not wait out a transfer passes its own.
* @returns A COS client that sends HTTPS requests to the region named by each call.
*/
export function createDesktopCos(credentials: DesktopCosCredentials): COS {
export function createDesktopCos(credentials: DesktopCosCredentials, timeoutMs: number = TRANSFER_TIMEOUT_MS): COS {
const cos = new COS({
SecretId: credentials.secretId,
SecretKey: credentials.secretKey,
@@ -41,7 +42,7 @@ export function createDesktopCos(credentials: DesktopCosCredentials): COS {
AutoSwitchHost: false,
CorrectClockSkew: false,
ChunkRetryTimes: 0,
Timeout: TRANSFER_TIMEOUT_MS,
Timeout: timeoutMs,
UploadCheckContentMd5: false,
})
cos.on('before-send', (options: CosRequestOptions) => {
@@ -0,0 +1,80 @@
/**
* Record a production release in git after it reaches the download domain.
*
* A build that only goes to a colleague or a test feed carries its commit
* inside the artifact, which is enough to trace it. A build that external users
* install should also be reachable from the repository, so a production upload
* tags the commit it was packaged from. The tag is written after the upload
* succeeds: a tag for a release that never shipped would be worse than none.
*
* Tagging never fails an upload that already completed. The artifacts are
* public by then, and nothing about a missing tag can be repaired by reporting
* the upload as failed; the operator is told what to run instead.
*/
import { execFileSync } from 'node:child_process'
/** What tagging one uploaded release did, or why it did nothing. */
export interface DesktopReleaseTagResult {
readonly tag: string
readonly status: 'created' | 'present' | 'failed'
/** Commands that finish the tagging a failure interrupted, in order. */
readonly recovery?: readonly string[]
readonly detail?: string
}
/**
* Name the tag one published version carries.
* @param version - Version the release published.
* @returns The tag name, distinct from the `dsh-v*` tags the npm family publishes from.
*/
export function desktopReleaseTag(version: string): string {
return `desktop-v${version}`
}
/**
* Tag and push the commit a production release was packaged from.
* @param options - Published version, packaged commit, repository, and remote.
* @returns What tagging did; a failure is reported rather than thrown.
*/
export function tagDesktopRelease(options: {
readonly version: string
readonly commit: string
readonly repositoryRoot: string
readonly remote?: string
readonly run?: (command: string, args: readonly string[]) => string
}): DesktopReleaseTagResult {
const tag = desktopReleaseTag(options.version)
const remote = options.remote ?? 'origin'
const run = options.run
?? ((command: string, args: readonly string[]) =>
execFileSync(command, [...args], { cwd: options.repositoryRoot, encoding: 'utf8' }).trim())
const create = `git tag ${tag} ${options.commit}`
const push = `git push ${remote} ${tag}`
// A local tag that already exists makes `git tag` fail, so recovery must name only the steps still outstanding.
let tagged = false
try {
const existing = run('git', ['tag', '--list', tag])
if (existing !== '') {
const named = run('git', ['rev-list', '-n', '1', tag])
if (named !== options.commit) {
return { tag, status: 'failed', detail: `${tag} already names ${named}, not the uploaded commit ${options.commit}` }
}
tagged = true
run('git', ['push', remote, tag])
return { tag, status: 'present' }
}
run('git', ['tag', tag, options.commit])
tagged = true
run('git', ['push', remote, tag])
return { tag, status: 'created' }
}
catch (error) {
return {
tag,
status: 'failed',
recovery: tagged ? [push] : [create, push],
detail: error instanceof Error ? error.message : String(error),
}
}
}
@@ -0,0 +1,102 @@
/**
* Probe the external tools a packaging run will shell out to, before it starts.
*
* The packaging sequence reaches its first archive step minutes in, and its
* first installer step later still, so a tool that is absent or behaves
* differently than the scripts assume wastes a whole run. Each probe here
* exercises the specific behaviour the run depends on rather than merely
* checking that the executable resolves.
*/
import { execFile } from 'node:child_process'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { promisify } from 'node:util'
const run = promisify(execFile)
/** One tool the packaging run requires, and what went wrong with it. */
export interface DesktopToolchainProbeFailure {
readonly tool: string
readonly detail: string
}
async function probeTar(): Promise<string | undefined> {
// GNU tar reads the colon in an absolute Windows path as a remote-host separator, which the
// release scripts avoid by running beside the archive; this probe confirms the archive reader works there.
const directory = await mkdtemp(join(tmpdir(), 'dsh-tar-probe-'))
try {
const member = join(directory, 'probe.txt')
await writeFile(member, 'probe\n')
const archive = join(directory, 'probe.tar.gz')
await run('tar', ['-czf', basename(archive), basename(member)], { cwd: directory, windowsHide: true, timeout: 20_000 })
const listed = await run('tar', ['-tzf', basename(archive)], { cwd: dirname(archive), windowsHide: true, timeout: 20_000 })
if (!listed.stdout.includes('probe.txt')) return `tar listed ${JSON.stringify(listed.stdout)} instead of the archived member`
return undefined
}
catch (error) {
return error instanceof Error ? error.message : String(error)
}
finally {
await rm(directory, { recursive: true, force: true })
}
}
async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise<DesktopToolchainProbeFailure[]> {
const failures: DesktopToolchainProbeFailure[] = []
const programFiles = environment['ProgramFiles(x86)']
const vswhere = programFiles === undefined
? undefined
: join(programFiles, 'Microsoft Visual Studio/Installer/vswhere.exe')
if (vswhere === undefined) {
failures.push({ tool: 'vswhere', detail: 'ProgramFiles(x86) is not set, so Visual Studio cannot be located' })
}
else {
try {
const located = await run(vswhere, ['-latest', '-products', '*',
'-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64', '-property', 'installationPath'],
{ windowsHide: true, timeout: 30_000 })
if (located.stdout.trim() === '') {
failures.push({ tool: 'vswhere', detail: 'Visual Studio C++ build tools are not installed, so the installer helper cannot compile' })
}
}
catch (error) {
failures.push({ tool: 'vswhere', detail: error instanceof Error ? error.message : String(error) })
}
}
return failures
}
/**
* Probe every external tool one packaging run needs.
* @param platform - Target platform; a Windows target already requires a Windows build host.
* @param environment - Packaging environment used to locate Windows tooling.
* @returns Every probe that failed, empty when the host can run the packaging sequence.
*/
export async function probeDesktopToolchain(
platform: 'darwin' | 'win32',
environment: NodeJS.ProcessEnv = process.env,
): Promise<readonly DesktopToolchainProbeFailure[]> {
const failures: DesktopToolchainProbeFailure[] = []
const tar = await probeTar()
if (tar !== undefined) failures.push({ tool: 'tar', detail: tar })
if (platform === 'win32') failures.push(...await probeWindowsInstallerToolchain(environment))
return failures
}
/**
* Probe the toolchain and fail with every problem the host has.
* @param platform - Target platform; a Windows target already requires a Windows build host.
* @param environment - Packaging environment used to locate Windows tooling.
* @returns Resolves when every probe passes.
*/
export async function requireDesktopToolchain(
platform: 'darwin' | 'win32',
environment: NodeJS.ProcessEnv = process.env,
): Promise<void> {
const failures = await probeDesktopToolchain(platform, environment)
if (failures.length === 0) return
throw new Error(`desktop package: the build host cannot run this packaging sequence:\n${
failures.map(failure => ` ${failure.tool}: ${failure.detail}`).join('\n')}`)
}
+24 -8
View File
@@ -13,6 +13,7 @@ import {
resolveDesktopUploadConfig,
} from './desktop-auto-update-environment.mjs'
import { desktopTargetBuildPaths } from './desktop-build-paths.mjs'
import { validateDesktopBuildVersion } from './desktop-build-version.mjs'
const APP_ROOT = resolve(import.meta.dirname, '..')
const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..')
@@ -47,6 +48,10 @@ export interface DesktopUploadPlan {
readonly secretIdEnvName: string
readonly secretKeyEnvName: string
readonly artifacts: readonly DesktopUploadArtifact[]
/** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */
readonly commit?: string
/** Whether that checkout carried uncommitted changes. */
readonly dirty?: boolean
}
/** Filesystem and environment inputs used to validate one upload. */
@@ -191,15 +196,24 @@ export async function createDesktopUploadPlan(
join(artifactsRoot, desktopBuildRecordFilename(targetName)),
`${targetName} package completion record`,
)
// Packaging wrote the version it published; reading it back keeps release settings out of shell variables.
const recordedVersion = stringField(buildRecord.version, `${targetName} package completion record.version`)
let buildVersion: string
try {
buildVersion = validateDesktopBuildVersion(recordedVersion, dshVersion)
}
catch (error) {
throw new Error(`desktop upload: ${targetName} package completion record holds ${recordedVersion}, which is not a build of dsh ${dshVersion}: ${
error instanceof Error ? error.message : String(error)}`)
}
if (buildRecord.schemaVersion !== 1
|| buildRecord.target !== targetName
|| buildRecord.version !== dshVersion
|| buildRecord.environment !== update.environment
|| buildRecord.publicUrl !== update.publicUrl) {
throw new Error(`desktop upload: ${targetName} package completion record does not match dsh ${dshVersion} and ${update.environment} update destination`)
throw new Error(`desktop upload: ${targetName} package completion record for ${buildVersion} does not match the ${update.environment} update destination`)
}
const metadataFilename = desktopUpdateMetadataFilename(dshVersion, target.platform)
const metadataFilename = desktopUpdateMetadataFilename(buildVersion, target.platform)
const metadataPath = join(artifactsRoot, metadataFilename)
let metadataValue: unknown
try {
@@ -210,14 +224,14 @@ export async function createDesktopUploadPlan(
}
const metadata = object(metadataValue, metadataFilename)
const metadataVersion = stringField(metadata.version, `${metadataFilename}.version`)
if (metadataVersion !== dshVersion) {
throw new Error(`desktop upload: ${metadataFilename} version ${metadataVersion} does not match current dsh version ${dshVersion}`)
if (metadataVersion !== buildVersion) {
throw new Error(`desktop upload: ${metadataFilename} version ${metadataVersion} does not match published version ${buildVersion}`)
}
if (!Array.isArray(metadata.files) || metadata.files.length !== 1) {
throw new Error(`desktop upload: ${metadataFilename}.files must contain exactly one target update file`)
}
const base = `deepseek-harness-${dshVersion}-${target.os}-${target.arch}`
const base = `deepseek-harness-${buildVersion}-${target.os}-${target.arch}`
const updaterExtension = target.platform === 'darwin' ? 'zip' : 'exe'
const updaterInfo = updateFileInfo(metadata.files[0], `${metadataFilename}.files[0]`, `${base}.${updaterExtension}`)
const updaterPath = await verifyChecksummedArtifact(artifactsRoot, updaterInfo)
@@ -254,18 +268,20 @@ export async function createDesktopUploadPlan(
contents: dump(published),
}
artifacts.push(channelArtifact)
if (prerelease(dshVersion) === null) {
if (prerelease(buildVersion) === null) {
const stableFilename = metadataFilename.replace('nightly', 'latest')
artifacts.push({ ...channelArtifact, filename: stableFilename, key: `${update.keyPrefix}/${stableFilename}` })
}
return {
environment: update.environment,
target: targetName,
version: dshVersion,
version: buildVersion,
publicUrl: update.publicUrl,
bucket: update.bucket,
secretIdEnvName: update.secretIdEnvName,
secretKeyEnvName: update.secretKeyEnvName,
artifacts,
...typeof buildRecord.commit === 'string' ? { commit: buildRecord.commit } : {},
...typeof buildRecord.dirty === 'boolean' ? { dirty: buildRecord.dirty } : {},
}
}
@@ -1,4 +1,5 @@
import { X509Certificate } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -18,6 +19,8 @@ import {
scrubWindowsSigningEnvironment,
} from './windows-sign.mjs'
import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs'
import { resolveDesktopBuildCommit } from './desktop-build-commit.mjs'
import { resolveDesktopBuildVersion } from './desktop-build-version.mjs'
import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs'
import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs'
import { installWindowsDirectoryInstaller } from './windows-directory-installer.mjs'
@@ -36,6 +39,7 @@ import {
* @param {NodeJS.Platform} hostPlatform - Build-host platform used when no explicit target is present.
* @param {string} hostArch - Build-host architecture used when no explicit target is present.
* @param {string | undefined} preparedRuntime - Verified private dsh tree for installed-update qualification; ordinary releases use the target tree.
* @param {string | undefined} preparedRuntimeVersion - Version that private tree declares, which qualification rewrites away from the product version.
* @returns {object} electron-builder configuration.
*/
export function createElectronBuilderConfig(
@@ -43,6 +47,7 @@ export function createElectronBuilderConfig(
hostPlatform = process.platform,
hostArch = process.arch,
preparedRuntime = undefined,
preparedRuntimeVersion = undefined,
) {
const appId = resolveDesktopAppId(env)
const policy = resolveDesktopPolicyEnvironment(env)
@@ -63,7 +68,7 @@ export function createElectronBuilderConfig(
let primaryRuntimeDestination
let dshDestination
let windowsCode = []
const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep/bin/rg',
const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg',
`**/node_modules/@deepseek-ai/libreoffice-kit-${resolvedPlatform}-${resolvedArch}/**/*`]
const windowsSigner = packagesWindows && !unsigned
? createWindowsTokenSigner({
@@ -86,9 +91,19 @@ export function createElectronBuilderConfig(
}
const update = unsigned ? undefined : resolveDesktopAutoUpdateConfig(env, resolvedPlatform, resolvedArch)
if (preparedRuntime !== undefined) buildPaths.dsh = preparedRuntime
// electron-builder merges extraMetadata into the packaged manifest, so a build version here reaches
// the artifact names, the update feed, and the installed app.getVersion() the updater compares against.
const productVersion = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')).version
const buildVersion = resolveDesktopBuildVersion(env, productVersion)
const packaged = resolveDesktopBuildCommit(env)
return {
appId,
extraMetadata: { dshDesktopAppId: appId, dshMandatoryUpdatePolicy: policy },
extraMetadata: {
dshDesktopAppId: appId,
dshMandatoryUpdatePolicy: policy,
...buildVersion === productVersion ? {} : { version: buildVersion },
...packaged === undefined ? {} : { dshBuildCommit: packaged.commit, dshBuildDirty: packaged.dirty },
},
productName: 'DeepSeek Harness',
artifactName: 'deepseek-harness-${version}-${os}-${arch}.${ext}',
directories: { output: unsigned ? buildPaths.unsignedArtifacts : buildPaths.artifacts },
@@ -159,8 +174,10 @@ export function createElectronBuilderConfig(
await writeMacOSAppUpdateConfig(resourcesDir, resolveMacOSAppUpdateFeed(context.packager.config.publish),
context.packager.appInfo.updaterCacheDirName)
}
// The bundled runtime declares whichever version prepared it: the product version for an ordinary
// release, and a rewritten one for installed-update qualification.
await verifyDesktopRuntime(buildPaths.dsh,
context.packager.appInfo.version, { platform: resolvedPlatform, arch: resolvedArch })
preparedRuntimeVersion ?? productVersion, { platform: resolvedPlatform, arch: resolvedArch })
// Unsigned Windows builds skip electron-builder's afterSign hook.
if (packagesWindows && unsigned) await verifyWindowsAsarUnpack(buildPaths.dsh, resourcesDir, windowsCode)
},
@@ -23,7 +23,7 @@ export async function createInstalledUpdateBuilderConfig(manifest: string, versi
const dsh = join(run.root, version, 'dsh')
await verifyDesktopRuntime(dsh, version, { platform: 'win32', arch: 'x64' })
const config = createElectronBuilderConfig({ ...environment, DSH_DESKTOP_APP_ID: run.appId,
DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: '0' }, 'win32', 'x64', dsh)
DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: '0' }, 'win32', 'x64', dsh, version)
return { ...config,
productName: run.productName,
directories: { ...config.directories, output: join(run.root, version, 'installer') },
+63 -8
View File
@@ -1,6 +1,6 @@
/** Build one release target with matching Electron and dsh architecture. */
import { execFileSync, spawn } from 'node:child_process'
import { spawn } from 'node:child_process'
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { parseArgs } from 'node:util'
import { join, resolve } from 'node:path'
@@ -19,6 +19,10 @@ import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from './macos-p
import { packagingErrorDetails, packagingStep } from './packaging-step.mjs'
import { notarizeMacOS } from './notarize-macos.mjs'
import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs'
import { DESKTOP_BUILD_VERSION_ENV, resolveDesktopBuildVersion, validateDesktopBuildVersion } from './desktop-build-version.mjs'
import { suggestDesktopBuildVersion } from './desktop-build-version-discovery.ts'
import { desktopBuildCommitEnvironment, readDesktopBuildCommit, resolveDesktopBuildCommit } from './desktop-build-commit.mjs'
import { requireDesktopToolchain } from './desktop-toolchain-preflight.ts'
import { withMacOSNotarizationProxy } from './macos-notarization-proxy.ts'
const APP_ROOT = resolve(import.meta.dirname, '..')
@@ -39,6 +43,9 @@ const DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES = new Set([
'DOWNLOAD_PROD_COS_SECRET_KEY',
])
/** `--build-version` value that numbers a build after the ones already taken. */
const AUTOMATIC_BUILD_VERSION = 'auto'
/** Fixed platform and architecture identifiers exposed by package scripts. */
export type DesktopPackageTargetName = 'mac-arm64' | 'mac-x64' | 'win-x64'
@@ -136,15 +143,19 @@ function writeReleaseRecord(
if (desktopVersion !== dshVersion) {
throw new Error(`desktop package: desktop version ${desktopVersion} does not match dsh version ${dshVersion}`)
}
const buildVersion = resolveDesktopBuildVersion(environment, dshVersion)
const packaged = resolveDesktopBuildCommit(environment)
const update = resolveDesktopAutoUpdateConfig(environment, target.platform, target.arch)
const recordPath = join(artifactsRoot, desktopBuildRecordFilename(target.name))
const temporaryPath = `${recordPath}.tmp`
writeFileSync(temporaryPath, `${JSON.stringify({
schemaVersion: 1,
target: target.name,
version: dshVersion,
version: buildVersion,
environment: update.environment,
publicUrl: update.publicUrl,
// Upload reads this to tag the commit a production release was packaged from.
...packaged === undefined ? {} : { commit: packaged.commit, dirty: packaged.dirty },
}, null, 2)}\n`)
renameSync(temporaryPath, recordPath)
}
@@ -186,6 +197,8 @@ interface DesktopPackageInvocation {
readonly prepareOnly: boolean
readonly unsigned: boolean
readonly check: boolean
/** Build identifier to publish under, when this build does not publish the product version. */
readonly requestedBuildVersion: string | undefined
}
function hostTargetName(platform: NodeJS.Platform, arch: string): DesktopPackageTargetName {
@@ -207,25 +220,33 @@ export function parseDesktopPackageInvocation(
hostArch: string = process.arch,
): DesktopPackageInvocation {
const { values, positionals } = parseArgs({
args: [...argv],
// `pnpm run <script> -- --build-version x` forwards the separator itself, and the script's own
// preset arguments come first, so it can land anywhere; parseArgs would read the rest as targets.
args: argv.filter(argument => argument !== '--'),
allowPositionals: true,
options: {
dir: { type: 'boolean', default: false },
'prepare-only': { type: 'boolean', default: false },
unsigned: { type: 'boolean', default: false },
check: { type: 'boolean', default: false },
'build-version': { type: 'string' },
},
})
if (positionals.length > 1) throw new Error('desktop package: expected at most one target')
const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch)
if (values.unsigned && name !== 'win-x64') throw new Error('desktop package: --unsigned requires win-x64')
if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only')
const requestedBuildVersion = values['build-version']?.trim()
if (values['build-version'] !== undefined && (requestedBuildVersion === undefined || requestedBuildVersion === '')) {
throw new Error('desktop package: --build-version requires a value')
}
return {
target: resolveDesktopPackageTarget(name, hostPlatform, hostArch),
directory: values.dir,
prepareOnly: values['prepare-only'],
unsigned: values.unsigned,
check: values.check,
requestedBuildVersion,
}
}
@@ -285,21 +306,53 @@ function runPnpm(
})
}
/**
* Resolve the version one run publishes from what its command line asked for.
* @param invocation - Validated packaging request.
* @param productVersion - Version the manifests declare.
* @param environment - Release settings, which name the bucket automatic numbering reads.
* @returns The product version, the requested version, or the next free index for today.
*/
async function resolveRequestedBuildVersion(
invocation: DesktopPackageInvocation,
productVersion: string,
environment: NodeJS.ProcessEnv,
): Promise<string> {
const requested = invocation.requestedBuildVersion
if (requested === undefined) return productVersion
if (requested !== AUTOMATIC_BUILD_VERSION) return validateDesktopBuildVersion(requested, productVersion)
const paths = desktopTargetBuildPaths(invocation.target.name)
return suggestDesktopBuildVersion({
productVersion, target: invocation.target.name, 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,
})
}
async function main(): Promise<void> {
const invocation = parseDesktopPackageInvocation(process.argv.slice(2))
const { target } = invocation
const environment = loadDesktopPackageEnvironment(target.platform)
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
// 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
if (invocation.check) {
validateDesktopPackageEnvironment(environment, target, invocation)
process.stdout.write(`desktop package: ${target.name} local configuration valid; signing and notarization were not attempted\n`)
await requireDesktopToolchain(target.platform, environment)
process.stdout.write(`desktop package: ${target.name} would publish ${buildVersion}; local configuration and toolchain valid, signing and notarization were not attempted\n`)
return
}
process.stdout.write(`desktop package: ${target.name} publishes ${buildVersion}${buildVersion === productVersion ? '' : ` for product version ${productVersion}`}\n`)
const packaged = readDesktopBuildCommit(REPOSITORY_ROOT)
Object.assign(environment, desktopBuildCommitEnvironment(packaged))
const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')
const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), {
target: target.name, unsigned: invocation.unsigned, directory: invocation.directory, prepareOnly: invocation.prepareOnly,
version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'), node: process.version,
commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim(),
dirty: execFileSync('git', ['status', '--porcelain', '--untracked-files=normal'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim() !== '',
version: buildVersion, productVersion, node: process.version,
commit: packaged.commit,
dirty: packaged.dirty,
}, { parallel: target.platform === 'darwin', secrets })
console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`)
const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
@@ -307,6 +360,7 @@ async function main(): Promise<void> {
let success = false
try {
await packagingStep(run.directory, 'configuration', async () => { validateDesktopPackageEnvironment(environment, target, invocation) }, secrets)
await packagingStep(run.directory, 'toolchain', () => requireDesktopToolchain(target.platform, environment), secrets)
if (target.platform === 'darwin') {
const settings = resolveMacOSPackageSettings(environment)
recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency,
@@ -427,7 +481,8 @@ export async function packageTarget(
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
await withMacOSNotarizationProxy(mac?.notarizationProxy, () => packageMacOSArtifacts({
arch: target.arch,
version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'),
// electron-builder named these artifacts after the published version, so locating them uses the same identifier.
version: resolveDesktopBuildVersion(environment, packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')),
artifactsRoot: buildPaths.artifacts,
environment: electronBuilderEnv,
}, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)), undefined, undefined, proxyEvent)
+29 -1
View File
@@ -6,7 +6,8 @@ import type { DesktopPackageTargetName } from './package-target.ts'
import { createDesktopCos } from './desktop-cos.ts'
import { resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs'
import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs'
import { createDesktopUploadPlan } from './desktop-upload-plan.ts'
import { createDesktopUploadPlan, type DesktopUploadPlan } from './desktop-upload-plan.ts'
import { desktopReleaseTag, tagDesktopRelease } from './desktop-release-tag.ts'
import { uploadDesktopRelease } from './desktop-upload-run.ts'
const SUPPORTED_TARGETS = new Set<DesktopPackageTargetName>(['mac-arm64', 'mac-x64', 'win-x64'])
@@ -85,6 +86,33 @@ async function main(): Promise<void> {
})
process.stdout.write(`desktop upload: ${plan.target} ${plan.version} -> ${plan.publicUrl}\n`)
await uploadDesktopRelease(plan, cos, resolve(import.meta.dirname, '../.desktop-build/upload-records'))
if (plan.environment === 'production') recordProductionRelease(plan)
}
/**
* Tag the commit an external release was packaged from, after its artifacts are public.
* @param plan Completed production upload.
*/
function recordProductionRelease(plan: DesktopUploadPlan): void {
const tag = desktopReleaseTag(plan.version)
if (plan.commit === undefined) {
process.stdout.write(`desktop upload: this package was built before builds recorded their commit; tag it by hand as ${tag}\n`)
return
}
if (plan.dirty === true) {
// A tag would name a commit whose tree is not what the users received.
process.stderr.write(`desktop upload: packaged from ${plan.commit} with uncommitted changes, so ${tag} was not created\n`)
return
}
const result = tagDesktopRelease({ version: plan.version, commit: plan.commit, repositoryRoot: resolve(import.meta.dirname, '../../..') })
if (result.status === 'failed') {
process.stderr.write(`desktop upload: the release is published but ${result.tag} was not recorded: ${result.detail ?? 'unknown error'}\n`)
if (result.recovery !== undefined) {
process.stderr.write(`desktop upload: record it with: ${result.recovery.join(' && ')}\n`)
}
return
}
process.stdout.write(`desktop upload: ${result.tag} ${result.status === 'created' ? 'records' : 'already recorded'} ${plan.commit}\n`)
}
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
+4 -3
View File
@@ -181,12 +181,13 @@ export function readDesktopRuntime(root: string): DesktopRuntimeDescriptor {
/**
* Verify every packaged runtime file against its recorded bytes and permissions at build time.
* @param root - Materialized runtime resources.
* @param electronVersion - Expected shell version.
* @param expectedVersion - Version the bundled runtime must declare: the product version ordinarily,
* and a rewritten one for installed-update qualification.
* @param target - Required execution target; defaults to the current process.
* @returns Validated runtime descriptor.
*/
export async function verifyDesktopRuntime(
root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process,
root: string, expectedVersion: string, target: { platform: NodeJS.Platform; arch: string } = process,
): Promise<DesktopRuntimeDescriptor> {
const descriptor = readDesktopRuntime(root)
// readDesktopRuntime preserves the disk schema value without validating release compatibility.
@@ -195,7 +196,7 @@ export async function verifyDesktopRuntime(
throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture')
}
const release = parseDesktopRelease(descriptor.release)
if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`)
if (release.version !== expectedVersion) throw new Error(`desktop runtime: bundled ${release.version} is not the expected ${expectedVersion}`)
for (const entry of descriptor.sharedPackages) {
const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8'))
if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) {
@@ -0,0 +1,83 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
DESKTOP_BUILD_COMMIT_ENV,
DESKTOP_BUILD_DIRTY_ENV,
desktopBuildCommitEnvironment,
readDesktopBuildCommit,
resolveDesktopBuildCommit,
} from '../scripts/desktop-build-commit.mjs'
import { probeDesktopToolchain } from '../scripts/desktop-toolchain-preflight.ts'
const COMMIT = '0123456789abcdef0123456789abcdef01234567'
const directories: string[] = []
afterEach(async () => {
for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true })
})
describe('desktop build commit', () => {
it('reads nothing outside a packaging run', () => {
expect(resolveDesktopBuildCommit({})).toBeUndefined()
expect(resolveDesktopBuildCommit({ [DESKTOP_BUILD_COMMIT_ENV]: ' ' })).toBeUndefined()
})
it('round-trips a commit and its tree state through a child environment', () => {
for (const dirty of [true, false]) {
expect(resolveDesktopBuildCommit(desktopBuildCommitEnvironment({ commit: COMMIT, dirty })))
.toEqual({ commit: COMMIT, dirty })
}
})
it.each(['abc', `${COMMIT}0`, 'Z'.repeat(40)])('rejects %j, which is not a commit hash', (commit) => {
expect(() => resolveDesktopBuildCommit({ [DESKTOP_BUILD_COMMIT_ENV]: commit })).toThrow(/must be a commit hash/u)
})
it('rejects a tree state that is neither 0 nor 1', () => {
expect(() => resolveDesktopBuildCommit({ [DESKTOP_BUILD_COMMIT_ENV]: COMMIT, [DESKTOP_BUILD_DIRTY_ENV]: 'yes' }))
.toThrow(/must be 0 or 1/u)
})
it('reads the checkout this repository is in', () => {
const packaged = readDesktopBuildCommit(join(import.meta.dirname, '..', '..', '..'))
expect(packaged.commit).toMatch(/^[0-9a-f]{40}$/u)
expect(typeof packaged.dirty).toBe('boolean')
})
})
describe('desktop toolchain preflight', () => {
it('passes on a host that can read archives', async () => {
expect(await probeDesktopToolchain('darwin', {})).toEqual([])
})
it('reports the archive reader when it cannot run', async () => {
const empty = await mkdtemp(join(tmpdir(), 'dsh-no-tools-'))
directories.push(empty)
const saved = { PATH: process.env.PATH, Path: process.env.Path }
try {
Object.assign(process.env, { PATH: empty, Path: empty })
const failures = await probeDesktopToolchain('darwin', {})
expect(failures.map(failure => failure.tool)).toEqual(['tar'])
expect(failures[0]?.detail).not.toBe('')
}
finally {
Object.assign(process.env, saved)
}
})
it('reports the Windows installer compiler when the host cannot locate Visual Studio', async () => {
const failures = await probeDesktopToolchain('win32', {})
expect(failures.map(failure => failure.tool)).toContain('vswhere')
expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)')
})
it('writes nothing into the working directory while probing', async () => {
const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-'))
directories.push(directory)
await writeFile(join(directory, 'sentinel'), '')
await probeDesktopToolchain('darwin', {})
expect(await import('node:fs/promises').then(async fs => fs.readdir(directory))).toEqual(['sentinel'])
})
})
@@ -0,0 +1,73 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
desktopBuildDateSegment,
suggestDesktopBuildVersion,
} from '../scripts/desktop-build-version-discovery.ts'
const PRERELEASE = '0.1.6-alpha.2'
const STABLE = '0.1.6'
const DATE = '20260921'
const directories: string[] = []
async function artifactsWith(names: readonly string[]): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), 'dsh-discovery-'))
directories.push(directory)
for (const name of names) await writeFile(join(directory, name), '')
return directory
}
afterEach(async () => {
for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true })
})
describe('desktop build version discovery', () => {
it('formats the date segment in the build host time zone', () => {
expect(desktopBuildDateSegment(new Date(2026, 8, 21))).toBe('20260921')
expect(desktopBuildDateSegment(new Date(2026, 0, 5))).toBe('20260105')
})
it('starts at one when nothing is taken', async () => {
const artifactsRoot = await artifactsWith([])
await expect(suggestDesktopBuildVersion({ productVersion: PRERELEASE, target: 'win-x64', environment: {}, date: DATE, artifactsRoot }))
.resolves.toBe(`${PRERELEASE}.${DATE}.1`)
})
it('numbers a stable product version under the documented test prerelease', async () => {
const artifactsRoot = await artifactsWith([`deepseek-harness-${STABLE}-test.${DATE}.4-win-x64.exe`])
await expect(suggestDesktopBuildVersion({ productVersion: STABLE, target: 'win-x64', environment: {}, date: DATE, artifactsRoot }))
.resolves.toBe(`${STABLE}-test.${DATE}.5`)
})
it('numbers after the highest local artifact for the same date', async () => {
const artifactsRoot = await artifactsWith([
`deepseek-harness-${PRERELEASE}.${DATE}.1-win-x64.exe`,
`deepseek-harness-${PRERELEASE}.${DATE}.2-win-x64.exe`,
`deepseek-harness-${PRERELEASE}.${DATE}.10-win-x64.exe`,
])
await expect(suggestDesktopBuildVersion({ productVersion: PRERELEASE, target: 'win-x64', environment: {}, date: DATE, artifactsRoot }))
.resolves.toBe(`${PRERELEASE}.${DATE}.11`)
})
it('ignores artifacts from another date or product version', async () => {
const artifactsRoot = await artifactsWith([
`deepseek-harness-${PRERELEASE}.20260920.7-win-x64.exe`,
`deepseek-harness-0.1.5-alpha.1.${DATE}.9-win-x64.exe`,
`deepseek-harness-${PRERELEASE}-win-x64.exe`,
'unrelated.exe',
])
await expect(suggestDesktopBuildVersion({ productVersion: PRERELEASE, target: 'win-x64', environment: {}, date: DATE, artifactsRoot }))
.resolves.toBe(`${PRERELEASE}.${DATE}.1`)
})
it('reads macOS artifact names too', async () => {
const artifactsRoot = await artifactsWith([
`deepseek-harness-${PRERELEASE}.${DATE}.3-mac-arm64.dmg`,
`deepseek-harness-${PRERELEASE}.${DATE}.3-mac-arm64.zip`,
])
await expect(suggestDesktopBuildVersion({ productVersion: PRERELEASE, target: 'mac-arm64', environment: {}, date: DATE, artifactsRoot }))
.resolves.toBe(`${PRERELEASE}.${DATE}.4`)
})
})
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest'
import {
DESKTOP_BUILD_VERSION_ENV,
desktopBuildVersionPrefix,
resolveDesktopBuildVersion,
validateDesktopBuildVersion,
} from '../scripts/desktop-build-version.mjs'
const PRERELEASE = '0.1.6-alpha.2'
const STABLE = '0.1.6'
describe('desktop build version', () => {
it('publishes the product version when no build version is present', () => {
expect(resolveDesktopBuildVersion({}, PRERELEASE)).toBe(PRERELEASE)
expect(resolveDesktopBuildVersion({ [DESKTOP_BUILD_VERSION_ENV]: ' ' }, PRERELEASE)).toBe(PRERELEASE)
})
it.each(['0.1.6-alpha.2.20260921.1', '0.1.6-alpha.2.20260921.12'])(
'accepts %s, which outranks the prerelease base it extends', (buildVersion) => {
expect(resolveDesktopBuildVersion({ [DESKTOP_BUILD_VERSION_ENV]: buildVersion }, PRERELEASE)).toBe(buildVersion)
expect(validateDesktopBuildVersion(buildVersion, PRERELEASE)).toBe(buildVersion)
})
it('accepts the documented test form on a stable base', () => {
// 0.1.6-test.x ranks below 0.1.6, which is why this form only ever reaches a test feed.
expect(validateDesktopBuildVersion('0.1.6-test.20260921.1', STABLE)).toBe('0.1.6-test.20260921.1')
})
it.each([PRERELEASE, STABLE])('accepts %s, the product version itself', (productVersion) => {
expect(validateDesktopBuildVersion(productVersion, productVersion)).toBe(productVersion)
})
it.each(['', 'nightly', '0.1.6-alpha.2.'])(
'rejects %j as a version', (buildVersion) => {
expect(() => validateDesktopBuildVersion(buildVersion, PRERELEASE)).toThrow(/is not a version/u)
})
it('normalizes what the artifacts carry, so validation and publication agree', () => {
expect(validateDesktopBuildVersion('v0.1.6-alpha.2.1', PRERELEASE)).toBe('0.1.6-alpha.2.1')
})
it('rejects build metadata, which does not affect updater precedence', () => {
expect(() => validateDesktopBuildVersion('0.1.6-alpha.2.1+build', PRERELEASE)).toThrow(/build metadata/u)
})
it.each(['0.1.7-alpha.2.20260921.1', '0.2.6-alpha.2.20260921.1'])(
'rejects %s because it leaves the product release numbers', (buildVersion) => {
expect(() => validateDesktopBuildVersion(buildVersion, PRERELEASE)).toThrow(/must extend product version/u)
})
it.each(['0.1.6-beta.2.20260921.1', '0.1.6-alpha.3', '0.1.6'])(
'rejects %s because it does not extend the product prerelease', (buildVersion) => {
expect(() => validateDesktopBuildVersion(buildVersion, PRERELEASE)).toThrow(/must extend 0\.1\.6-alpha\.2 as/u)
})
it.each(['0.1.6-20260921.1', '0.1.6-nightly.20260921.1'])(
'rejects %s on a stable base, which the test form has to open', (buildVersion) => {
expect(() => validateDesktopBuildVersion(buildVersion, STABLE)).toThrow(/must extend 0\.1\.6 as 0\.1\.6-test\./u)
})
it.each([[PRERELEASE, '0.1.6-alpha.2.'], [STABLE, '0.1.6-test.']])(
'opens %s build versions with %s', (productVersion, prefix) => {
expect(desktopBuildVersionPrefix(productVersion)).toBe(prefix)
})
})
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest'
import { desktopReleaseTag, tagDesktopRelease } from '../scripts/desktop-release-tag.ts'
const COMMIT = '0'.repeat(40)
const OTHER = '1'.repeat(40)
const VERSION = '0.1.6-alpha.2'
function recorder(responses: Record<string, string | Error>): {
readonly run: (command: string, args: readonly string[]) => string
readonly calls: string[][]
} {
const calls: string[][] = []
return {
calls,
run: (command, args) => {
calls.push([command, ...args])
const response = responses[args[0] ?? '']
if (response instanceof Error) throw response
return response ?? ''
},
}
}
describe('desktop release tag', () => {
it('names a tag distinct from the npm family tags', () => {
expect(desktopReleaseTag(VERSION)).toBe(`desktop-v${VERSION}`)
})
it('creates and pushes a tag for the packaged commit', () => {
const { run, calls } = recorder({ tag: '' })
expect(tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run }))
.toEqual({ tag: `desktop-v${VERSION}`, status: 'created' })
expect(calls).toEqual([
['git', 'tag', '--list', `desktop-v${VERSION}`],
['git', 'tag', `desktop-v${VERSION}`, COMMIT],
['git', 'push', 'origin', `desktop-v${VERSION}`],
])
})
it('pushes an existing tag that already names the uploaded commit', () => {
const { run, calls } = recorder({ tag: `desktop-v${VERSION}`, 'rev-list': COMMIT })
expect(tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run }))
.toEqual({ tag: `desktop-v${VERSION}`, status: 'present' })
expect(calls.at(-1)).toEqual(['git', 'push', 'origin', `desktop-v${VERSION}`])
})
it('refuses to move a tag that names another commit', () => {
const { run, calls } = recorder({ tag: `desktop-v${VERSION}`, 'rev-list': OTHER })
const result = tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run })
expect(result.status).toBe('failed')
expect(result.detail).toMatch(new RegExp(`already names ${OTHER}`, 'u'))
expect(calls.some(call => call.includes('push'))).toBe(false)
})
it('reports a git failure instead of throwing, because the release is already public', () => {
const { run } = recorder({ tag: new Error('git unavailable') })
expect(tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run }))
.toMatchObject({ status: 'failed', detail: 'git unavailable' })
})
it('recovers a failed push without repeating the tag that already exists', () => {
// `git tag` would fail with "already exists" and short-circuit a combined command, leaving the push undone.
const { run } = recorder({ tag: '', push: new Error('remote rejected') })
expect(tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run }))
.toMatchObject({ status: 'failed', recovery: [`git push origin desktop-v${VERSION}`] })
})
it('recovers a failed tag by creating it before pushing', () => {
const { run } = recorder({ tag: new Error('cannot write ref') })
expect(tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', run }))
.toMatchObject({ recovery: [`git tag desktop-v${VERSION} ${COMMIT}`, `git push origin desktop-v${VERSION}`] })
})
it('pushes to a named remote', () => {
const { run, calls } = recorder({ tag: '' })
tagDesktopRelease({ version: VERSION, commit: COMMIT, repositoryRoot: '.', remote: 'upstream', run })
expect(calls.at(-1)).toEqual(['git', 'push', 'upstream', `desktop-v${VERSION}`])
})
})
+18 -1
View File
@@ -7,6 +7,7 @@ import { rm } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { delimiter, dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
const runtime = process.argv[2]
assert.ok(runtime, 'Pass the filtered resources/dsh directory')
@@ -98,6 +99,21 @@ async function checkPty() {
}
}
/** Exercise grep and glob operations with the search tool's resolved native executable. */
async function checkSearch() {
const { resolveRgPath } = await import(pathToFileURL(requireRuntime.resolve('@deepseek-ai/dsh-tool-fs-search')).href)
const executable = await resolveRgPath()
const name = 'ripgrep-smoke.txt'
const marker = 'desktop-ripgrep-smoke'
writeFileSync(join(scratch, name), `${marker}\n`, { flag: 'wx', mode: 0o600 })
const run = args => execFileSync(executable, ['--no-config', ...args], {
cwd: scratch, encoding: 'utf8', timeout: 45_000, windowsHide: true,
env: Object.fromEntries(Object.entries(process.env).filter(([name]) => /^(?:systemroot|windir)$/iu.test(name))),
}).trim().replaceAll('\\', '/')
assert.equal(run(['--no-heading', '--no-filename', '--line-number', '--fixed-strings', '--', marker, name]), `1:${marker}`)
assert.equal(run(['--files', '--glob', name, '.']), `./${name}`)
}
/** Resolve one system function through Koffi's packaged native module. */
function checkKoffi() {
const koffi = requireRuntime('koffi')
@@ -146,6 +162,7 @@ try {
await checkSharp()
checkHtml()
await checkPty()
await checkSearch()
} finally {
// This private tree contains only fixture files; Windows may release handles after terminal exit.
await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 })
@@ -154,5 +171,5 @@ try {
// Natural event-loop drain includes node-pty's worker and console-list helper teardown.
process.once('beforeExit', () => {
console.log(JSON.stringify({ node: process.versions.node, platform: process.platform, arch: process.arch,
koffi: true, sharp: true, html: true, pty: true, pnpm: true }))
koffi: true, sharp: true, html: true, pty: true, pnpm: true, grep: true, glob: true }))
})
+1 -1
View File
@@ -56,7 +56,7 @@ describe('desktop macOS release signature', () => {
expect(dshNodeModules.to).toBe('dsh/node_modules')
expect(config.asarUnpack).toEqual(expect.arrayContaining([
'**/*.{node,dylib,dll,so,exe}',
'**/@vscode/ripgrep/bin/rg',
'**/@vscode/ripgrep-*/bin/rg',
]))
expect(config).toMatchObject({
appId: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
@@ -12,6 +12,8 @@ vi.mock('../scripts/desktop-package-environment.mjs', () => ({
vi.mock('../scripts/macos-signing-keychain.mjs', () => ({
withMacOSSigningKeychain: async (_environment: object, action: (environment: object) => Promise<unknown>) => action({}),
}))
// This test fakes the host platform, so the real probes would report the absent Windows compilers rather than the failure under test.
vi.mock('../scripts/desktop-toolchain-preflight.ts', () => ({ requireDesktopToolchain: async () => {} }))
vi.mock('node:fs', async importOriginal => ({
...await importOriginal<typeof import('node:fs')>(),
rmSync: () => { throw new AggregateError([new Error('credential-sentinel')], 'restore:mac-proxy recovery required') },
@@ -51,6 +53,7 @@ it.each(['win32', 'darwin'] as const)('records and prints redacted parent failur
expect(JSON.parse(await readFile(join(state.directory, 'result.json'), 'utf8'))).toMatchObject({
success: false, stages: [
{ stage: 'configuration', success: true },
{ stage: 'toolchain', success: true },
{ stage: platform === 'win32' ? 'windows-package' : 'macos-package', success: false },
],
})
+14
View File
@@ -44,6 +44,20 @@ describe('desktop package target', () => {
.toThrow(/at most one target/u)
})
it('parses a build version, including the separator a pnpm run script forwards', () => {
expect(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64').requestedBuildVersion).toBeUndefined()
expect(parseDesktopPackageInvocation(['mac-arm64', '--build-version', '0.1.6-alpha.2.20260921.1'], 'darwin', 'arm64')
.requestedBuildVersion).toBe('0.1.6-alpha.2.20260921.1')
expect(parseDesktopPackageInvocation(['mac-arm64', '--build-version', 'auto'], 'darwin', 'arm64')
.requestedBuildVersion).toBe('auto')
// A run script's preset arguments come first, so pnpm forwards the separator after the target.
expect(parseDesktopPackageInvocation(['mac-arm64', '--', '--build-version', 'auto'], 'darwin', 'arm64'))
.toMatchObject({ requestedBuildVersion: 'auto', target: { name: 'mac-arm64' } })
expect(parseDesktopPackageInvocation(['--', '--check'], 'darwin', 'arm64').check).toBe(true)
expect(() => parseDesktopPackageInvocation(['mac-arm64', '--build-version', ' '], 'darwin', 'arm64'))
.toThrow(/--build-version requires a value/u)
})
it('keeps electron-builder publishing disabled for the separate validated upload', () => {
const target = resolveDesktopPackageTarget('mac-arm64', 'darwin', 'arm64')
expect(desktopElectronBuilderArguments(target, false)).toEqual([
@@ -0,0 +1,63 @@
import { describe, expect, it, vi } from 'vitest'
const { verifyDesktopRuntime } = vi.hoisted(() => ({
verifyDesktopRuntime: vi.fn<(root: string, expected: string) => Promise<void>>(async () => undefined),
}))
// The hook imports the built tree, which a clean checkout has not produced; this is the path it resolves.
vi.mock('/apps/desktop/lib/types/runtime-tree.js', () => ({ verifyDesktopRuntime }))
vi.mock('../scripts/windows-asar-unpack.mjs', async importOriginal => ({
...await importOriginal<typeof import('../scripts/windows-asar-unpack.mjs')>(),
verifyWindowsAsarUnpack: async () => undefined,
}))
const ENVIRONMENT = {
DSH_DESKTOP_APP_ID: 'com.example.installer',
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_TARGET_PLATFORM: 'win32',
DSH_DESKTOP_TARGET_ARCH: 'x64',
DSH_DESKTOP_UNSIGNED: '1',
DOWNLOAD_TEST_ORIGIN: 'https://desktop-updates.example.com',
DOWNLOAD_TEST_RELEASE_ID: '0123456789abcdef0123456789abcdef',
}
const CONTEXT = { appOutDir: 'out', packager: { getResourcesDir: () => 'out/resources' } }
/**
* Run the packaging hook that verifies the bundled runtime.
* @returns The version that hook required the runtime to declare.
*/
async function requiredRuntimeVersion(preparedRuntime?: string, preparedRuntimeVersion?: string): Promise<unknown> {
verifyDesktopRuntime.mockClear()
const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs')
const config = createElectronBuilderConfig(ENVIRONMENT, 'win32', 'x64', preparedRuntime, preparedRuntimeVersion)
await config.afterPack(CONTEXT as never)
return verifyDesktopRuntime.mock.calls[0]?.[1]
}
describe('packaged runtime verification', () => {
it('requires the product version when the target tree supplies the runtime', async () => {
const productVersion = (JSON.parse(
await import('node:fs/promises').then(async fs => fs.readFile(new URL('../package.json', import.meta.url), 'utf8')),
) as { version: string }).version
expect(await requiredRuntimeVersion()).toBe(productVersion)
})
it('requires the version installed-update qualification wrote into its private runtime', async () => {
// Qualification rewrites the runtime's own version, so comparing against the product version would always fail.
expect(await requiredRuntimeVersion('/qualification/dsh', '0.1.6-alpha.2.20260921.1')).toBe('0.1.6-alpha.2.20260921.1')
})
it('does not let a build version change what the bundled runtime must declare', async () => {
const productVersion = (JSON.parse(
await import('node:fs/promises').then(async fs => fs.readFile(new URL('../package.json', import.meta.url), 'utf8')),
) as { version: string }).version
const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs')
verifyDesktopRuntime.mockClear()
const config = createElectronBuilderConfig(
{ ...ENVIRONMENT, DSH_DESKTOP_BUILD_VERSION: `${productVersion}.20260921.1` }, 'win32', 'x64')
expect(config.extraMetadata).toMatchObject({ version: `${productVersion}.20260921.1` })
await config.afterPack(CONTEXT as never)
expect(verifyDesktopRuntime.mock.calls[0]?.[1]).toBe(productVersion)
})
})
+2 -2
View File
@@ -54,10 +54,10 @@ it.each(['missing', 'directory'])('checks a %s Host entry only during build veri
expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0')
await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u)
})
it('checks the shell version only during build verification', async () => {
it('checks the bundled version only during build verification', async () => {
const dsh = join(fixture(), 'dsh')
expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0')
await expect(verifyDesktopRuntime(dsh, '2.0.0')).rejects.toThrow(/does not match Electron/u)
await expect(verifyDesktopRuntime(dsh, '2.0.0')).rejects.toThrow(/bundled 1\.0\.0 is not the expected 2\.0\.0/u)
})
it.each([
{ schemaVersion: 2 },
+30 -5
View File
@@ -46,6 +46,14 @@ afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
function unsignedWindowsConfig(appId: string, source: string) {
return createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: appId, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_UNSIGNED: '1',
}, 'win32', 'x64', source)
}
async function fixture(external: boolean) {
const root = await mkdtemp(join(tmpdir(), 'windows-asar-'))
roots.push(root)
@@ -188,6 +196,27 @@ it.each([true, false])('validates the real builder hook for unsigned=%s', async
}
})
it.each([false, true])('unpacks platform ripgrep executables with external source=%s', async (external) => {
const input = await fixture(external)
// Windows rg.exe uses the general executable rule; macOS rg uses the platform-package rule.
const files = ['ripgrep-darwin-arm64/bin/rg', 'ripgrep-darwin-x64/bin/rg', 'ripgrep-win32-x64/bin/rg.exe']
for (const file of [...files, 'ripgrep/lib/index.js']) {
const path = join(input.source, 'node_modules', '@vscode', file)
await mkdir(dirname(path), { recursive: true })
await writeFile(path, 'ripgrep fixture')
}
const config = unsignedWindowsConfig('com.example.ripgrep', input.source)
input.config.asarUnpack = [...config.asarUnpack]
await packageFixture(input)
const archive = await readAsar(join(input.resources, 'app.asar'))
expect(archive.getFile(join('dsh', 'node_modules', '@vscode', 'ripgrep/lib/index.js')).unpacked).not.toBe(true)
for (const file of files) {
const path = join('dsh', 'node_modules', '@vscode', file)
expect(archive.getFile(path, false).unpacked).toBe(true)
expect(await readFile(join(input.resources, 'app.asar.unpacked', path), 'utf8')).toBe('ripgrep fixture')
}
})
it.each([false, true])('keeps the complete Office engine outside ASAR with external source=%s', async (external) => {
const input = await fixture(external)
const engine = join('node_modules', '@deepseek-ai', 'libreoffice-kit-win32-x64')
@@ -200,11 +229,7 @@ it.each([false, true])('keeps the complete Office engine outside ASAR with exter
const wasm = join(input.source, 'node_modules/@deepseek-ai/libreoffice-kit-wasm/package.json')
await mkdir(dirname(wasm), { recursive: true })
await writeFile(wasm, '{}')
const config = createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: 'com.example.office', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }),
DSH_DESKTOP_UNSIGNED: '1',
}, 'win32', 'x64', input.source)
const config = unsignedWindowsConfig('com.example.office', input.source)
input.config.asarUnpack = [...config.asarUnpack]
await config.beforePack(input.context)
await packageFixture(input)
+1
View File
@@ -34,6 +34,7 @@
"@deepseek-ai/dsh-client-modules": "workspace:^",
"@deepseek-ai/dsh-client-store": "workspace:^",
"@deepseek-ai/dsh-client-test-runtime": "workspace:^",
"@deepseek-ai/dsh-client-ui-deliverables": "workspace:^",
"@deepseek-ai/dsh-client-ui-dockkit": "workspace:^",
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
+2 -2
View File
@@ -144,9 +144,9 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
'settings/describe': ok({
...fixture.settingsDescribe.value,
namespaces: [...fixture.settingsDescribe.value.namespaces, {
ns: 'ui-developer-tools',
ns: 'ui-settings',
schema: { type: 'object', dict: { enabled: { type: 'boolean' } } },
value: { enabled: options.developerTools ?? true }, applies: 'live', secrets: [], revision: 0,
value: { enabled: options.developerTools ?? true }, autoGenerate: false, applies: 'live', secrets: [], revision: 0,
}],
}),
'credentials/describe': structuredClone(fixture.credentialsDescribe),
+183 -2
View File
@@ -5,8 +5,9 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, type Browser, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { afterAll, beforeAll, describe, expect, it, onTestFinished } from 'vitest'
import type {} from '@deepseek-ai/dsh-workspace-changes'
import type { ChangesSummary } from '@deepseek-ai/dsh-client-ui-deliverables/src/changes.ts'
import { deriveReplayScript, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
import {
assertFinalWorkspaceSnapshot, captureExpandedTurnProcessAria, compareOrRefreshGolden,
@@ -80,9 +81,10 @@ describe('web e2e: a git workspace turn ends with its changed files', () => {
})
await seedRepository(join(scaffold.workspaceCwd, 'workspace'))
browser = await chromium.launch()
page = await browser.newPage({
const context = await browser.newContext({
viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE, timezoneId: 'Asia/Shanghai',
})
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]')
@@ -307,6 +309,40 @@ describe('web e2e: a git workspace turn ends with its changed files', () => {
return [center(text), center(caret), center(counts)].map(value => Math.abs(value - buttonCenter))
})
for (const offset of headerAlignment) expect(offset).toBeLessThanOrEqual(0.5)
// The appended row has no old-side text; constrain the columns so the hunk header overflows it.
const emptyRowLayout = await page.addStyleTag({ content: `
[data-diff-side="left"] { width: 90px; }
[data-diff-side="right"] { width: 120px; }
` })
try {
const left = review.locator('[data-diff-side="left"]')
const emptyRow = left.locator('[data-diff-line="add"]')
const maximum = await left.evaluate(element => element.scrollWidth - element.clientWidth)
expect(maximum).toBeGreaterThan(0)
await left.evaluate((element) => { element.scrollLeft = element.scrollWidth })
await expect.poll(() => left.evaluate(element => element.scrollLeft)).toBe(maximum)
const fill = await emptyRow.evaluate((row) => {
const column = row.closest('[data-diff-side]')!
const columnBox = column.getBoundingClientRect()
const rowBox = row.getBoundingClientRect()
const y = rowBox.top + rowBox.height / 2
return {
rowWidth: rowBox.width,
contentWidth: column.scrollWidth,
background: getComputedStyle(row).backgroundColor,
coversViewport: [columnBox.left + 4, columnBox.right - 4].every(x =>
document.elementFromPoint(x, y)?.closest('[data-diff-line]') === row),
}
})
expect(fill.background).not.toBe('rgba(0, 0, 0, 0)')
expect(fill.rowWidth).toBeGreaterThanOrEqual(fill.contentWidth - 0.5)
expect(fill.coversViewport).toBe(true)
} finally {
await emptyRowLayout.evaluate(element => element.parentNode!.removeChild(element))
await review.locator('[data-diff-side]').evaluateAll((elements) => {
for (const element of elements) element.scrollLeft = 0
})
}
const addedLine = review.locator('[data-diff-side="right"] [data-diff-line="add"]')
const rightContextLine = review.locator('[data-diff-side="right"] [data-diff-line="context"]')
const addedRule = await addedLine.evaluate((line) => {
@@ -494,9 +530,154 @@ describe('web e2e: a git workspace turn ends with its changed files', () => {
expect(tripwire.warnings).toEqual([])
})
it('keeps edge gestures inside either diff column and accepts reverse scrolling', async () => {
const review = page.locator('[data-changes-review]')
await review.getByRole('button', { name: '自动换行' }).click()
const body = review.locator('[data-review-view="split"]:not([data-review-wrap])')
await body.waitFor({ state: 'visible' })
// A scrollable parent makes escaped edge gestures observable without native trackpad rebound.
const layout = await page.addStyleTag({ content: `
[data-changes-review] { height: 220px !important; }
[data-review-view="split"] { display: block; max-width: 220px; }
[data-review-view="split"] > div { width: 160px; height: 60px; margin: 160px; }
` })
onTestFinished(async () => {
await layout.evaluate(element => element.parentNode!.removeChild(element))
await body.evaluate((element) => { element.scrollTo(0, 0) })
await review.getByRole('button', { name: '自动换行' }).click()
})
const input = await page.context().newCDPSession(page)
try {
for (const side of ['left', 'right']) {
const column = review.locator(`[data-diff-side="${side}"]`)
for (const axis of ['x', 'y'] as const) {
for (const end of [false, true]) {
const parentPosition = await body.evaluate((element) => {
const x = (element.scrollWidth - element.clientWidth) / 2
const y = (element.scrollHeight - element.clientHeight) / 2
element.scrollTo(x, y)
return { x: element.scrollLeft, y: element.scrollTop }
})
expect(parentPosition.x).toBeGreaterThan(0)
expect(parentPosition.y).toBeGreaterThan(0)
const edge = await column.evaluate((element, { axis, end }) => {
const maximum = axis === 'x'
? element.scrollWidth - element.clientWidth
: element.scrollHeight - element.clientHeight
element.scrollTo(axis === 'x' && end ? maximum : 0, axis === 'y' && end ? maximum : 0)
return { maximum, offset: end ? maximum : 0 }
}, { axis, end })
expect(edge.maximum).toBeGreaterThan(0)
const position = () => column.evaluate((element, axis) => axis === 'x' ? element.scrollLeft : element.scrollTop, axis)
await expect.poll(position).toBe(edge.offset)
const box = await column.boundingBox()
if (box === null) throw new Error('diff column has no visible bounds')
const gesture = { x: box.x + box.width / 2, y: box.y + box.height / 2, gestureSourceType: 'mouse' as const }
const distance = end ? -80 : 80
// CDP acknowledges the completed gesture, including default scrolling, before observation.
await input.send('Input.synthesizeScrollGesture', {
...gesture, xDistance: axis === 'x' ? distance : 0, yDistance: axis === 'y' ? distance : 0,
})
expect(await body.evaluate(element => ({ x: element.scrollLeft, y: element.scrollTop }))).toEqual(parentPosition)
expect(await position()).toBe(edge.offset)
await input.send('Input.synthesizeScrollGesture', {
...gesture, xDistance: axis === 'x' ? -distance : 0, yDistance: axis === 'y' ? -distance : 0,
})
await expect.poll(position).not.toBe(edge.offset)
}
}
}
} finally {
await input.detach()
}
})
it.skipIf(MODE === 'record')('replays the workspace and the Chinese conversation', async () => {
await assertFinalWorkspaceSnapshot(DIR, cwd, { ignoredRootEntries: ['.git'] })
const aria = await captureExpandedTurnProcessAria(page, '[data-chat-flow]', scaffold.workspaceCwd)
await compareOrRefreshGolden(join(DIR, 'ui.expected.md'), aria, MODE)
})
it('preserves filename endings when the review narrows and updates the fade after resizing or selecting another file', async () => {
const preview = await page.context().newPage()
onTestFinished(async () => { await preview.close() })
const previewTripwire = watchConsole(preview)
const prefix = 'src/components/review/' + 'long-filename-'.repeat(8)
const names = [`${prefix}before.ts`, `${prefix}after.ts`] as const
// Project long display names into a separate page; recorded paths, comparisons, and Session data stay intact.
await preview.route('**/api/changes.summary?*', async (route) => {
const response = await route.fetch()
const summary = await response.json() as ChangesSummary
await route.fulfill({ response, json: {
...summary, files: summary.files.map((file, index) => ({ ...file, display: names[index] ?? file.display })),
} })
})
await preview.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await preview.locator('[data-changed-files]').getByRole('button', { name: '在侧边栏查看本轮改动' }).click()
const review = preview.locator('[data-changes-review]')
const selector = review.getByRole('button', { name: '选择要查看的文件' })
const label = selector.locator('[data-path-label]')
const layout = await preview.addStyleTag({ content: '[data-sidebar-right-panel] { width: 340px !important; }' })
const resize = async (width: number) => {
await layout.evaluate((element, width) => {
element.textContent = `[data-sidebar-right-panel] { width: ${width}px !important; }`
}, width)
}
const metrics = () => label.evaluate((element) => {
const text = element.firstElementChild!
const box = element.getBoundingClientRect()
const textBox = text.getBoundingClientRect()
const filename = text.lastElementChild!
const suffix = document.createRange()
const node = filename.firstChild!
suffix.setStart(node, Math.max(0, node.textContent!.length - 'before.ts'.length))
suffix.setEnd(node, node.textContent!.length)
const suffixBox = suffix.getBoundingClientRect()
return {
clipped: element.hasAttribute('data-path-clipped'), mask: getComputedStyle(element).maskImage,
left: textBox.left - box.left, right: box.right - textBox.right,
suffixVisible: suffixBox.left >= box.left && suffixBox.right <= box.right + 0.5,
directoryColor: getComputedStyle(text.firstElementChild!).color,
nameColor: getComputedStyle(filename).color,
}
})
await expect.poll(async () => (await metrics()).clipped).toBe(true)
const clipped = await metrics()
expect(clipped.left).toBeLessThan(0)
expect(Math.abs(clipped.right)).toBeLessThanOrEqual(0.5)
expect(clipped.suffixVisible).toBe(true)
expect(clipped.mask).toContain('linear-gradient')
expect(clipped.directoryColor).not.toBe(clipped.nameColor)
expect(await label.getAttribute('title')).toBe(names[0])
const controls = await selector.evaluate((button) => {
const header = button.parentElement!.parentElement!
const bounds = header.getBoundingClientRect()
const caret = button.querySelector('svg')!
const counts = button.parentElement!.nextElementSibling!
return [caret, counts, ...header.querySelectorAll('[data-review-tool]')].map((element) => {
const box = element.getBoundingClientRect()
return box.width > 0 && box.left >= bounds.left && box.right <= bounds.right
})
})
expect(controls.every(Boolean)).toBe(true)
await selector.click()
await preview.getByRole('menuitem').filter({ hasText: names[1] }).click()
await expect.poll(() => label.getAttribute('title')).toBe(names[1])
expect((await metrics()).suffixVisible).toBe(true)
await resize(1400)
await expect.poll(async () => (await metrics()).clipped).toBe(false)
expect((await metrics()).left).toBeCloseTo(0, 1)
expect((await metrics()).mask).toBe('none')
await resize(340)
await expect.poll(async () => (await metrics()).clipped).toBe(true)
await selector.click()
await preview.getByRole('menuitem').filter({ hasText: 'src/util.ts' }).click()
await expect.poll(() => label.getAttribute('title')).toBe('src/util.ts')
await expect.poll(async () => (await metrics()).clipped).toBe(false)
expect((await metrics()).left).toBeCloseTo(0, 1)
expect((await metrics()).mask).toBe('none')
expect(previewTripwire.pageErrors).toEqual([])
expect(previewTripwire.warnings).toEqual([])
})
})
@@ -458,7 +458,7 @@ describe('web e2e: clickable links gallery', () => {
await page.getByRole('button', { name: 'Settings', exact: true }).click()
await page.getByRole('button', { name: 'Built-in browser', exact: true }).click()
await page.getByRole('menuitem', { name: 'New browser tab', exact: true }).click()
await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ linkOpening: 'new-tab' })
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value).toMatchObject({ linkOpening: 'new-tab' })
await page.keyboard.press('Escape')
const popupPromise = page.waitForEvent('popup')
await guideLink.click()
@@ -475,7 +475,7 @@ describe('web e2e: clickable links gallery', () => {
await page.getByRole('button', { name: 'Settings', exact: true }).click()
await page.getByRole('button', { name: 'New browser tab', exact: true }).click()
await page.getByRole('menuitem', { name: 'Built-in browser', exact: true }).click()
await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ linkOpening: 'sidebar' })
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value).toMatchObject({ linkOpening: 'sidebar' })
await page.keyboard.press('Escape')
await guideLink.click()
await expect.poll(() => browserAddress.inputValue()).toBe(GUIDE_URL)
+1 -1
View File
@@ -99,7 +99,7 @@ describe.skipIf(MODE === 'record')('web e2e: declared reasoning efforts reach th
await page.keyboard.press('Tab')
await expect.poll(() => levels.count(), { timeout: 10_000 }).toBe(0)
await expect.poll(
async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'),
{ timeout: 10_000 },
).toContain('reasoningEffort: high')
await expect.poll(() => trigger.getAttribute('aria-label'), { timeout: 10_000 })
@@ -62,13 +62,13 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
await messages.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
const settings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const settings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(settings).toContain('https://messages.example/anthropic')
expect(settings).toContain('llm-deepseek:')
expect(settings).toContain('id: llm-deepseek')
await expect(scaffold.ctx.llm.resolveModelInfo('deepseek-official', 'deepseek-flash')).resolves.toMatchObject({
name: 'Messages Flash', inputModalities: ['text', 'image'], systemPromptUpdate: 'in-history',
})
expect(scaffold.ctx.settings.get('llm-deepseek')).not.toHaveProperty('protocol')
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'llm-deepseek')?.value).not.toHaveProperty('protocol')
expect(settings).not.toContain('sk-e2e-')
const credentials = await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')
expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
@@ -96,7 +96,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
await page.getByRole('menuitemradio', { name: 'Messages Flash', exact: true }).click()
await expect.poll(() => input.isEnabled()).toBe(true)
await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection().provider).toBe('deepseek-official')
const settings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const settings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(settings).toContain('provider: deepseek-official')
expect(tripwire.pageErrors).toEqual([])
}, 60_000)
+3 -3
View File
@@ -111,10 +111,10 @@ describe('web e2e: the composer model switch is the default for later sessions',
// The switch is what sets the default: the shared Agent-route settings section
// now names it, beside the provider profiles the Models page writes.
await expect.poll(
async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'),
{ timeout: 10_000 },
).toContain('agent-default-model:')
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
).toContain('id: agent-default-model')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain(`provider: ${ROUTE}`)
expect(document).toContain(`model: ${MODEL}`)
@@ -16,10 +16,10 @@ it('persists developer tools in the Host settings document and restores the acce
await page.getByRole('button', { name: 'Settings', exact: true }).click()
const toggle = page.getByRole('switch', { name: 'Developer tools' })
expect(await toggle.getAttribute('aria-checked')).toBe('true')
expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).not.toContain('ui-developer-tools:')
expect(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).not.toMatch(/id: ui-settings(?:\r?\n|$)/)
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).toContain('ui-developer-tools:\n enabled: false')
expect(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toContain('enabled: false')
await page.reload()
await page.getByRole('button', { name: 'Settings', exact: true }).click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
@@ -28,13 +28,13 @@ it('persists developer tools in the Host settings document and restores the acce
const pickerToggle = page.getByRole('switch', { name: 'Choose a mode for new tasks' })
await expect.poll(() => page.getByRole('heading', { name: 'Agent presets', exact: true }).count()).toBe(1)
expect(await pickerToggle.count()).toBe(0)
await scaffold.ctx.settings.update('ui-developer-tools', { enabled: true })
await scaffold.ctx.settings.update('ui-settings', { enabled: true })
await expect.poll(() => pickerToggle.count()).toBe(1)
await expect.poll(() => pickerToggle.isEnabled()).toBe(true)
const pickerEnabled = await pickerToggle.getAttribute('aria-checked')
await scaffold.ctx.settings.update('ui-developer-tools', { enabled: false })
await scaffold.ctx.settings.update('ui-settings', { enabled: false })
await expect.poll(() => pickerToggle.count()).toBe(0)
await scaffold.ctx.settings.update('ui-developer-tools', { enabled: true })
await scaffold.ctx.settings.update('ui-settings', { enabled: true })
await expect.poll(() => pickerToggle.isEnabled()).toBe(true)
await expect.poll(() => pickerToggle.getAttribute('aria-checked')).toBe(pickerEnabled)
})
+3 -3
View File
@@ -168,7 +168,7 @@ else process.exit(1);
await saveFailureShot(page, `screenshots/0908-document-preview/smoke-${process.pid}`)
})
expect(await page.locator('[data-slot="conversation.hero.agentPreset"] button').count()).toBe(0)
expect(scaffold.ctx.settings.get('ui-developer-tools')).toEqual({ enabled: false })
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toEqual({ enabled: false })
const settled = scaffold.whenTurnSettled()
const input = page.locator('[data-composer-input]').first()
await input.fill(PROMPT)
@@ -444,11 +444,11 @@ else process.exit(1);
await expect.poll(() => html.locator('#local-result').innerText()).toBe('LOCAL_JS_REFRESHED')
expect(await iframe.getAttribute('src')).not.toBe(beforeScriptSave)
await page.getByRole('tab', { name: /Trajectory/ }).click()
await scaffold.ctx.settings.update('ui-developer-tools', { enabled: false })
await scaffold.ctx.settings.update('ui-settings', { enabled: false })
await expect.poll(() => page.getByRole('tab', { name: /Trajectory/ }).count()).toBe(0)
await expect.poll(() => iframe.getAttribute('sandbox')).toBe('')
expect(await page.getByText('LIGHTHOUSE', { exact: true }).count()).toBeGreaterThan(0)
await scaffold.ctx.settings.update('ui-developer-tools', { enabled: true })
await scaffold.ctx.settings.update('ui-settings', { enabled: true })
await expect.poll(() => iframe.getAttribute('sandbox')).toBe('allow-scripts')
await expect.poll(() => html.locator('#result').innerText()).toBe('INLINE_OK')
await successShot(page, 'html')
@@ -0,0 +1,19 @@
- button "返回插件列表": 插件列表
- button "夹具操作"
- button "卸载 @fixture/live-client": 卸载
- switch "启用 @fixture/live-client" [checked]
- heading "@fixture/live-client" [level=3]
- text: v0.0.1 夹具标签
- paragraph:
- code: "@fixture/live-client"
- heading "包含的组件" [level=4]
- text: 共 1 个 · 1 运行中
- list:
- listitem:
- button "配置 @fixture/live-client": "@fixture/live-client"
- code: fixture-live-client
- text: 运行中
- switch "启用组件 @fixture/live-client" [checked]
- region "夹具区块":
- heading "夹具区块" [level=4]
- paragraph: 来自夹具的区块内容
@@ -26,8 +26,11 @@
- button "查看 网页搜索": 网页搜索
- text: 设置 DeepSeek 的搜索提供方。
- heading "已安装" [level=3]
- text: "1"
- text: "2"
- list:
- listitem:
- button "查看 @fixture/live-client": "@fixture/live-client"
- switch "启用 @fixture/live-client"
- listitem:
- button "查看 dsh-web-scaffold-defaults": dsh-web-scaffold-defaults
- switch "启用 dsh-web-scaffold-defaults" [checked]
@@ -1,5 +1,7 @@
- button "返回 @fixture/live-client": "@fixture/live-client"
- button "夹具操作"
- heading "@fixture/live-client" [level=3]
- text: 夹具标签
- paragraph:
- code: fixture-live-client
- paragraph:
@@ -9,3 +11,6 @@
- text: 问候语
- textbox "问候语": 你好
- button "保存"
- region "夹具区块":
- heading "夹具区块" [level=4]
- paragraph: 来自夹具的区块内容
@@ -26,9 +26,12 @@
- button "查看 网页搜索": 网页搜索
- text: 设置 DeepSeek 的搜索提供方。
- heading "已安装" [level=3]
- text: "1"
- text: "2"
- list:
- listitem:
- button "查看 @fixture/bundle": "@fixture/bundle"
- text: Registry description for the fixture bundle.
- switch "启用 @fixture/bundle" [checked]
- listitem:
- button "查看 dsh-web-scaffold-defaults": dsh-web-scaffold-defaults
- switch "启用 dsh-web-scaffold-defaults" [checked]
@@ -26,9 +26,12 @@
- button "查看 网页搜索": 网页搜索
- text: 设置 DeepSeek 的搜索提供方。
- heading "已安装" [level=3]
- text: "1"
- text: "2"
- list:
- listitem:
- button "查看 @fixture/bundle": "@fixture/bundle"
- text: Registry description for the fixture bundle.
- switch "启用 @fixture/bundle"
- listitem:
- button "查看 dsh-web-scaffold-defaults": dsh-web-scaffold-defaults
- switch "启用 dsh-web-scaffold-defaults" [checked]
@@ -16,13 +16,37 @@ window.__ModuleLoader__.load({
ctx.effect(() => ctx.locale.register('fixtureLive', {
zh: {
active: '动态插件已启用', configSummary: '示例配置项', configForm: '动态插件配置', configField: '问候语', configSave: '保存',
action: '夹具操作', badge: '夹具标签', section: '夹具区块', sectionBody: '来自夹具的区块内容',
exportSession: '导出会话', copySessionId: '复制会话 ID',
},
en: {
active: 'Live plugin enabled', configSummary: 'An example setting', configForm: 'Live plugin configuration', configField: 'Greeting', configSave: 'Save',
action: 'Fixture action', badge: 'Fixture badge', section: 'Fixture section', sectionBody: 'Section content from the fixture',
exportSession: 'Export session', copySessionId: 'Copy session ID',
},
}))
// Detail contributions for this bundle's own page and its row's page: an
// action at the head, a badge beside the title, and a section below.
// The subject says what the open page is about; another bundle's page
// gets nothing from these entries.
const mine = (subject) => (subject.kind === 'bundle' || subject.kind === 'row') && subject.pkg.name === '@fixture/live-client'
ctx.slots.inject('plugins.detail.actions', () => ctx.slots.register({
name: 'plugins.detail.actions', id: 'fixture-live-client', locale: 'fixtureLive',
}, ({ t, subject }) => mine(subject)
? React.createElement('button', { type: 'button', 'data-live-action': subject.kind }, t('action'))
: null))
ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({
name: 'plugins.detail.badge', id: 'fixture-live-client', locale: 'fixtureLive',
}, ({ t, subject }) => mine(subject)
? React.createElement('span', { 'data-live-badge': subject.kind }, t('badge'))
: null))
ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
name: 'plugins.detail.section', id: 'fixture-live-client', locale: 'fixtureLive',
}, ({ t, subject }) => mine(subject)
? React.createElement('section', { 'data-live-section': subject.kind, 'aria-label': t('section') },
React.createElement('h4', null, t('section')),
React.createElement('p', null, t('sectionBody')))
: null))
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
name: 'shell.overlay', id: 'fixture-live-client', locale: 'fixtureLive',
}, ({ t }) => React.createElement('div', { 'data-live-client': '' }, t('active'))))
+2 -2
View File
@@ -326,7 +326,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
const row = dialog.getByText('Performance & usage', { exact: true }).locator('../..')
await row.getByRole('button', { name: 'Detailed', exact: true }).click()
await page.getByRole('menuitem', { name: 'Compact', exact: true }).click()
await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ performanceUsage: 'compact' })
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value).toMatchObject({ performanceUsage: 'compact' })
await dialog.getByRole('button', { name: 'Close', exact: true }).click()
await expect.poll(() => stats.locator('button').count()).toBe(0)
expect(await stats.textContent()).not.toContain('turns')
@@ -341,7 +341,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
acknowledgeReloadConnectionLoss(tripwire, warningStart)
await row.getByRole('button', { name: 'Compact', exact: true }).click()
await page.getByRole('menuitem', { name: 'Detailed', exact: true }).click()
await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ performanceUsage: 'detailed' })
await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value).toMatchObject({ performanceUsage: 'detailed' })
await dialog.getByRole('button', { name: 'Close', exact: true }).click()
await expect.poll(() => stats.locator('button').count()).toBe(2)
expect(await page.locator('[data-turn-tail]').getByRole('button', { name: /Ran for/ }).count()).toBe(0)
+10 -9
View File
@@ -1,5 +1,5 @@
/** Stored catalog drift remains repairable through the assembled Models settings page. */
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -26,10 +26,11 @@ describe('web e2e: repairs a stored provider after catalog drift', () => {
beforeAll(async () => {
home = await mkdtemp(join(tmpdir(), 'dsh-models-recovery-'))
await writeFile(join(home, 'settings.yaml'), [
'llm-pi-ai:', ' providers:', ' openrouter:', ' models:',
' - id: "111"', ' zai: {}', ' acme-gateway:',
' baseURL: https://gateway.example/v1', ' models:', ' - id: "custom-model"', '',
await mkdir(join(home, 'profiles', 'scaffold'), { recursive: true })
await writeFile(join(home, 'profiles', 'scaffold', 'cordis.patch.yml'), [
'- id: llm-pi-ai', ' config:', ' providers:', ' openrouter:', ' models:',
' - id: "111"', ' zai: {}', ' acme-gateway:',
' baseURL: https://gateway.example/v1', ' models:', ' - id: "custom-model"', '',
].join('\n'))
scaffold = await launchWebScaffold({ harnessHome: home })
browser = await chromium.launch()
@@ -71,7 +72,7 @@ describe('web e2e: repairs a stored provider after catalog drift', () => {
await dialog.getByLabel('提供商', { exact: true }).selectOption('minimax-cn')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor()
expect(await readFile(join(home, 'settings.yaml'), 'utf8')).toContain('minimax-cn: {}')
expect(await readFile(join(home, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toContain('minimax-cn: {}')
expect(await dialog.getByText(FAILURE, { exact: true }).count()).toBe(1)
})
@@ -80,15 +81,15 @@ describe('web e2e: repairs a stored provider after catalog drift', () => {
await dialog.getByRole('button', { name: '编辑 openrouter', exact: true }).click()
await dialog.getByText('自定义设置', { exact: true }).click()
await dialog.getByLabel('API 地址', { exact: true }).fill('https://gateway.example/v1')
const before = await readFile(join(home, 'settings.yaml'), 'utf8')
const before = await readFile(join(home, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => dialog.getByText(FAILURE, { exact: true }).count()).toBe(2)
expect(await readFile(join(home, 'settings.yaml'), 'utf8')).toBe(before)
expect(await readFile(join(home, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toBe(before)
await dialog.getByRole('button', { name: '删除模型 1', exact: true }).click()
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 openrouter。', { exact: true }).waitFor()
expect(await dialog.getByText(FAILURE, { exact: true }).count()).toBe(0)
const repaired = await readFile(join(home, 'settings.yaml'), 'utf8')
const repaired = await readFile(join(home, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(repaired).not.toContain('111')
expect(repaired).toContain('baseURL: https://gateway.example/v1')
expect(tripwire.pageErrors).toEqual([])
+12 -12
View File
@@ -129,7 +129,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
expect(await dialog.getByRole('img', { name: 'API 密钥已配置' }).count()).toBe(0)
expect(await dialog.getByRole('img', { name: 'API 密钥缺失' }).count()).toBe(0)
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('minimax-cn: {}')
expect(document).not.toContain('MINIMAX_CN_API_KEY')
}, 60_000)
@@ -155,7 +155,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
await dialog.getByRole('textbox', { name: 'API 密钥', exact: true }).fill('sk-e2e-minimax')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
// The profile lands in settings.yaml with only the derived reference, the
// The profile lands in cordis.patch.yml with only the derived reference, the
// key value lands in the harness home's .credentials.yaml, the dormant route
// registers, and the topology frame invalidates the page into the row.
await expect.poll(
@@ -164,7 +164,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
).toBe(0)
await dialog.getByRole('img', { name: 'API 密钥已配置' }).waitFor({ timeout: 10_000 })
await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('minimax-cn:')
expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY')
expect(document).not.toContain('sk-e2e-minimax')
@@ -189,7 +189,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
// stored profile beside the reference.
await expect.poll(async () => dialog.getByLabel('API 地址').count(), { timeout: 10_000 }).toBe(0)
await dialog.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 10_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('baseURL: https://gateway.minimax.example/v1')
expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY')
const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
@@ -270,7 +270,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
const row = dialog.getByText('Acme Gateway', { exact: true }).first()
await row.waitFor({ timeout: 10_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('acme-gateway:')
await expect(scaffold.ctx.llm.resolveModelInfo('acme-gateway', 'acme-large')).resolves.toMatchObject({
inputModalities: ['text', 'image'],
@@ -294,7 +294,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await dialog.getByText('自定义设置').click()
// The create card asked this route for a name and a protocol because
// nothing can default them; the editor reaches the same two fields rather
// than sending the user to settings.yaml for what only this route names.
// than sending the user to cordis.patch.yml for what only this route names.
const protocol = dialog.getByLabel('API 协议')
await protocol.waitFor({ timeout: 10_000 })
expect(await protocol.inputValue()).toBe('openai-completions')
@@ -319,7 +319,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
// The status line names the route as the refreshed directory reports it;
// the target captured when the card opened still carries the old name.
await dialog.getByText('已保存 Acme 网关 (acme-gateway)。', { exact: true }).waitFor({ timeout: 10_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('api: anthropic-messages')
expect(document).toContain('displayName: Acme 网关')
await expect(scaffold.ctx.llm.resolveModelInfo('acme-gateway', 'acme-large')).resolves.toMatchObject({
@@ -371,12 +371,12 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
const image = types.getByRole('checkbox', { name: '图片', exact: true })
await expect.poll(() => image.isChecked()).toBe(true)
expect(await types.getByRole('checkbox', { name: '文本', exact: true }).isChecked()).toBe(true)
const before = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const before = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'catalog-inputs.expected.md'),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), MODE)
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await types.waitFor({ state: 'detached' })
expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).toBe(before)
expect(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toBe(before)
await edit.click()
await dialog.getByText('自定义设置').click()
@@ -414,7 +414,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
it('confirms an identified provider deletion before removing its profile and key', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-models-delete'))
expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).not.toContain('openai:')
expect(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).not.toContain('openai:')
const settingsDialog = page.getByRole('dialog', { name: '设置' })
await settingsDialog.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
const deleteDialog = page.getByRole('dialog', { name: '删除 minimax-cn?' })
@@ -427,12 +427,12 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
await compareOrRefreshGolden(DELETE_EXPECTED, snapshot, MODE)
await deleteDialog.getByRole('button', { name: '取消', exact: true }).click()
expect(await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')).toContain('minimax-cn:')
expect(await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')).toContain('minimax-cn:')
await settingsDialog.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
await page.getByRole('dialog', { name: '删除 minimax-cn?' })
.getByRole('button', { name: '删除 minimax-cn', exact: true }).click()
await expect.poll(
async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'),
async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'),
{ timeout: 10_000 },
).not.toContain('minimax-cn:')
expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8'))
@@ -91,7 +91,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
expect((await page.locator('body').ariaSnapshot()).includes(secret)).toBe(false)
expect(browserConsole.some(line => line.includes(secret))).toBe(false)
const acknowledgedSettings = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const acknowledgedSettings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(acknowledgedSettings).toContain(`${WELCOME_NOTICE_ACK_FIELD}: ${WELCOME_NOTICE_VERSION}`)
// The ordinary Models surface reuses the refreshed join and exposes the
@@ -217,7 +217,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await settings.getByRole('group', { name: '输入类型 1' }).getByRole('checkbox', { name: '图片' }).uncheck()
await settings.getByRole('button', { name: '保存', exact: true }).click()
await settings.getByLabel('模型 ID 1').waitFor({ state: 'detached', timeout: 15_000 })
const savedDefaults = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const savedDefaults = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(savedDefaults).toContain('id: deepseek-flash')
expect(savedDefaults).toContain('inputModalities:')
expect(savedDefaults).toContain('- text')
@@ -252,7 +252,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await settings.getByRole('button', { name: '保存', exact: true }).click()
await customModelId.waitFor({ state: 'detached', timeout: 15_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('id: private-preview')
expect(document).toContain('name: Private Preview')
expect(document).toContain('contextWindow: 131072')
@@ -93,7 +93,7 @@ describe.skipIf(MODE === 'record')('web e2e: another usable provider ends first-
await settings.getByText('已保存 minimax-cn。', { exact: true }).waitFor({ timeout: 15_000 })
// Only minimax-cn is reachable; DeepSeek still holds no credential.
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('apiKeyEnv: MINIMAX_CN_API_KEY')
const credentials = await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')
expect(credentials).toContain('MINIMAX_CN_API_KEY: sk-e2e-minimax')
+39 -6
View File
@@ -1,6 +1,6 @@
// Web e2e scenario: the configuration pages on the Plugins page — the official
// pages a deployment's exposed host-plane namespaces produce, one field edited
// through the real wire down to `$DSH_HOME/settings.yaml`, the override badge
// through the real wire down to `$DSH_HOME/cordis.patch.yml`, the override badge
// and reset that layering produces, and a community bundle's row configuration
// registered by its own browser half. Zero model calls: everything is client
// state plus the settings document and the profile on a blank frame, so there
@@ -20,6 +20,7 @@ import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/plugin-config', import.meta.url))
const OFFICIAL_EXPECTED = join(SNAPSHOT_DIR, 'official.expected.md')
const ROW_EXPECTED = join(SNAPSHOT_DIR, 'row.expected.md')
const BUNDLE_EXPECTED = join(SNAPSHOT_DIR, 'bundle.expected.md')
const FIXTURE_PLUGINS = fileURLToPath(new URL('./fixtures/plugins', import.meta.url))
const MODE = webSnapshotMode()
@@ -78,7 +79,7 @@ describe('web e2e: plugin configuration pages', () => {
/** The settings document as the Host has written it so far. */
async function settingsDocument(): Promise<string> {
return readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8').catch(() => '')
return readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8').catch(() => '')
}
it('lists one official page per exposed host-plane namespace after the official bundles', async () => {
@@ -181,7 +182,7 @@ describe('web e2e: plugin configuration pages', () => {
// The Save label returns only after both namespace controllers settle.
await expect.poll(() => save.isDisabled(), { timeout: 10_000 }).toBe(true)
const saved = await settingsDocument()
expect(saved).toContain('subagent-model-selection:')
expect(saved).toContain('id: subagent-model-selection-settings')
expect(saved).toContain('maxDepth: 2')
expect(saved).toContain('enabled: true')
expect(saved).toContain('allowedModels:')
@@ -201,6 +202,8 @@ describe('web e2e: plugin configuration pages', () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-write'))
const panel = await openPlugins()
await openPage(panel, '终端')
const entry = [...scaffold.ctx.loader.entries()].find(row => row.options.id === 'bash-sandbox')!
const fiber = entry.fiber
const timeout = panel.getByLabel('命令超时(毫秒)')
await timeout.waitFor({ timeout: 10_000 })
@@ -218,6 +221,8 @@ describe('web e2e: plugin configuration pages', () => {
await expect.poll(async () => (await settingsDocument()).includes('timeoutMs: 12000'), { timeout: 10_000 })
.toBe(true)
expect(scaffold.ctx.shell.resolve({ command: 'true' }).timeoutMs).toBe(12000)
expect(entry.fiber === fiber).toBe(true)
// Presence in the user layer is what the badge reports, and the reset is
// offered only for a field that has one.
await expect.poll(() => panel.getByText('已覆盖').count(), { timeout: 5_000 }).toBe(1)
@@ -292,17 +297,37 @@ describe('web e2e: plugin configuration pages', () => {
await row.waitFor({ timeout: 10_000 })
expect(await panel.getByRole('button', { name: '配置 @fixture/live-client' }).count()).toBe(0)
// Off, the bundle's page carries no contribution either: the browser half
// that would make them is not loaded.
const bundlePage = panel.locator('[data-plugin-detail="@fixture/live-client"]')
expect(await bundlePage.locator('[data-live-action]').count()).toBe(0)
// Switched on, the Host recomposes and the browser half mounts without a
// reload; its registration puts the configure control on the row.
// reload; its registration puts the configure control on the row, and
// its detail contributions on the bundle's page: the action before the
// page's own switch, the badge beside the title, the section after the rows.
await panel.getByRole('switch', { name: '启用 @fixture/live-client' }).click()
const configure = panel.getByRole('button', { name: '配置 @fixture/live-client' })
await configure.waitFor({ timeout: 30_000 })
await bundlePage.locator('[data-live-section="bundle"]').waitFor({ timeout: 10_000 })
// The page's own view of the row follows the Host's change event, which
// can land after the browser half mounted; the golden holds the settled page.
await row.getByText('运行中', { exact: true }).waitFor({ timeout: 10_000 })
expect(await bundlePage.getByRole('button', { name: '夹具操作' }).count()).toBe(1)
expect(await bundlePage.locator('[data-live-badge="bundle"]').textContent()).toBe('夹具标签')
expect(await bundlePage.getByRole('region', { name: '夹具区块' }).getByText('来自夹具的区块内容').count()).toBe(1)
const bundleSnapshot = await captureStableAria(page, '[data-plugin-panel]', scaffold.workspaceCwd)
await compareOrRefreshGolden(BUNDLE_EXPECTED, bundleSnapshot, MODE)
await configure.click()
const rowPage = panel.locator('[data-plugin-row-detail="@fixture/live-client#fixture-live-client"]')
await rowPage.waitFor({ timeout: 10_000 })
expect(await rowPage.getByRole('heading', { level: 3 }).textContent()).toBe('@fixture/live-client')
expect(await rowPage.getByText('示例配置项', { exact: true }).count()).toBe(1)
// The same entries render for the row's page, told it is about the row.
expect(await rowPage.locator('[data-live-action="row"]').count()).toBe(1)
expect(await rowPage.locator('[data-live-badge="row"]').count()).toBe(1)
expect(await rowPage.locator('[data-live-section="row"]').count()).toBe(1)
const form = rowPage.getByRole('form', { name: '动态插件配置' })
await form.getByLabel('问候语').fill('你好')
await form.getByRole('button', { name: '保存' }).click()
@@ -311,12 +336,20 @@ describe('web e2e: plugin configuration pages', () => {
const snapshot = await captureStableAria(page, '[data-plugin-panel]', scaffold.workspaceCwd)
await compareOrRefreshGolden(ROW_EXPECTED, snapshot, MODE)
await rowPage.getByRole('button', { name: '返回 @fixture/live-client' }).click()
await panel.locator('[data-plugin-detail="@fixture/live-client"]').waitFor({ timeout: 10_000 })
await bundlePage.waitFor({ timeout: 10_000 })
// An official plugin's page is another subject; the fixture's entries render nothing for it.
await panel.getByRole('button', { name: '返回插件列表' }).click()
await openPage(panel, '终端')
const itemPage = panel.locator('[data-plugin-item-detail]')
expect(await itemPage.locator('[data-live-action], [data-live-badge], [data-live-section]').count()).toBe(0)
expect(tripwire.pageErrors).toEqual([])
}, 90_000)
it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, ['official.expected.md', 'row.expected.md', 'subagent.expected.md'])
await assertFixtureInventory(SNAPSHOT_DIR, ['bundle.expected.md', 'official.expected.md', 'row.expected.md', 'subagent.expected.md'])
})
})
+12 -12
View File
@@ -11,7 +11,7 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { join } from 'node:path'
import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
SCAFFOLD_DEFAULTS_BUNDLE, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureShot } from './support.ts'
@@ -23,6 +23,8 @@ const EXPORTS_EXPECTED = join(SNAPSHOT_DIR, 'exports.expected.md')
const EXPORTS_EN_EXPECTED = join(SNAPSHOT_DIR, 'exports-en.expected.md')
const FIXTURE_PLUGINS = fileURLToPath(new URL('./fixtures/plugins', import.meta.url))
const MODE = webSnapshotMode()
/** The profile manifest's bundles as the scaffold initializes them. */
const SCAFFOLD_BUNDLES = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', SCAFFOLD_DEFAULTS_BUNDLE]
describe('web e2e: plugin manager', () => {
let scaffold: WebScaffold
@@ -107,7 +109,7 @@ describe('web e2e: plugin manager', () => {
await toggle.click()
await expect.poll(async () => (JSON.parse(await homeFile('profiles', 'scaffold', 'package.json')) as {
dsh: { profile: { bundles: string[] } }
}).dsh.profile.bundles, { timeout: 10_000 }).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'])
}).dsh.profile.bundles, { timeout: 10_000 }).toEqual(SCAFFOLD_BUNDLES)
await expect.poll(() => panel.getByText(/cannot resolve profile bundle/).count(), { timeout: 10_000 }).toBe(0)
expect((await scaffold.ctx.pluginManager.listBundles()).some(row => row.name === '@fixture/missing-bundle')).toBe(false)
expect(tripwire.pageErrors).toEqual([])
@@ -120,10 +122,10 @@ describe('web e2e: plugin manager', () => {
await panel.getByRole('button', { name: '查看 @fixture/bundle', exact: true }).waitFor({ timeout: 20_000 })
const toggle = panel.getByRole('switch', { name: '启用 @fixture/bundle' })
expect(await toggle.getAttribute('aria-checked')).toBe('false')
// The profile's own group holds its one bundle; the installation's optional bundles open the Official
// group, followed by the official plugins that registered their configuration, and its other bundles
// stay off the page.
expect(await panel.locator('[data-plugin-group="bundles"] [data-plugin-package]').count()).toBe(1)
// The profile's own group holds its fixture bundle and the scaffold's defaults bundle; the installation's
// optional bundles open the Official group, followed by the official plugins that registered their
// configuration, and its other bundles stay off the page.
expect(await panel.locator('[data-plugin-group="bundles"] [data-plugin-package]').count()).toBe(2)
expect(await panel.locator('[data-plugin-group="official"] [data-plugin-package]').count()).toBe(2)
expect(await panel.locator('[data-plugin-group="official"] [data-plugin-item]').count()).toBe(4)
expect(await panel.getByText('Beta', { exact: true }).count()).toBe(2)
@@ -283,9 +285,7 @@ describe('web e2e: plugin manager', () => {
const manifest = JSON.parse(await homeFile('profiles', 'scaffold', 'package.json')) as {
dsh: { profile: { bundles: string[] } }
}
expect(manifest.dsh.profile.bundles).toEqual([
'@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/dsh-experimental-agent-team-profile',
])
expect(manifest.dsh.profile.bundles).toEqual([...SCAFFOLD_BUNDLES, '@deepseek-ai/dsh-experimental-agent-team-profile'])
await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click()
for (const id of ['agent-team', 'tool-agent-team', 'ui-agent-team']) {
await panel.locator('[data-plugin-row]', { hasText: id }).first().waitFor()
@@ -347,7 +347,7 @@ describe('web e2e: plugin manager', () => {
const bundles = async () => (JSON.parse(await homeFile('profiles', 'scaffold', 'package.json')) as {
dsh: { profile: { bundles: string[] } }
}).dsh.profile.bundles
await expect.poll(bundles, { timeout: 10_000 }).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@fixture/bundle'])
await expect.poll(bundles, { timeout: 10_000 }).toEqual([...SCAFFOLD_BUNDLES, '@fixture/bundle'])
// A live profile: the row mounts once the whole tree recomposed, the switch is on, and nothing waits for a restart.
await expect.poll(() => mounted()?.fiber?.state, { timeout: 20_000 }).toBe(2)
await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: 10_000 }).toBe('true')
@@ -408,7 +408,7 @@ describe('web e2e: startup-applied plugin management', () => {
expect(mounted()?.fiber?.state).toBeUndefined()
await toggle.click()
// The selection is saved and the switch turns on, but nothing mounts before the next start; a toast says so.
await expect.poll(bundles).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@fixture/bundle'])
await expect.poll(bundles).toEqual([...SCAFFOLD_BUNDLES, '@fixture/bundle'])
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true')
await page.getByText('更改将在下次启动生效', { exact: true }).waitFor({ timeout: 10_000 })
expect(mounted()?.fiber?.state).toBeUndefined()
@@ -419,7 +419,7 @@ describe('web e2e: startup-applied plugin management', () => {
await panel.getByRole('button', { name: '返回插件列表' }).click()
await toggle.click()
await expect.poll(bundles).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'])
await expect.poll(bundles).toEqual(SCAFFOLD_BUNDLES)
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
expect(tripwire.pageErrors).toEqual([])
} finally {
+28 -5
View File
@@ -379,16 +379,22 @@ async function bootPreview(origin: string, browser: Browser): Promise<void> {
// Settings and credentials both answer over the Remote carrier, so this
// half of the sweep posts the generated endpoints directly like the
// session read above.
const settings = await remote<{ namespaces: { ns: string; revision: number }[] }>(
interface Setting { ns: string; revision: number; value: Record<string, unknown>; user: Record<string, unknown> }
const settings = await remote<{ writable: boolean; namespaces: Setting[] }>(
'settings/describe', {},
)
const shell = settings.namespaces.find(namespace => namespace.ns === 'shell')
if (shell === undefined) throw new Error('settings/describe omitted the shell namespace')
await remote('settings/update', {
ns: 'shell',
const shell = settings.namespaces.find(namespace => namespace.ns === 'bash-sandbox')
if (shell === undefined) throw new Error('settings/describe omitted the bash-sandbox namespace')
const saved = await remote<Setting>('settings/update', {
ns: 'bash-sandbox',
patch: { timeoutMs: 61_000 },
expectedRevision: shell.revision,
})
const reread = await remote<{ namespaces: Setting[] }>('settings/describe', {})
const reset = await remote<Setting>('settings/mutate', {
ns: 'bash-sandbox', ops: [{ op: 'unset', path: ['timeoutMs'] }], expectedRevision: saved.revision,
})
await remote('settings/update', { ns: 'ui-theme', patch: { fontSize: 17 } })
await remote('credentials/set', { ref: 'PREVIEW_TEST_SECRET', value: 'worker-only' })
const credentials = await remote<Record<string, { configured: boolean }>>(
'credentials/describe',
@@ -397,6 +403,13 @@ async function bootPreview(origin: string, browser: Browser): Promise<void> {
await remote('credentials/unset', { ref: 'PREVIEW_TEST_SECRET' })
await new Promise((resolve) => { setTimeout(resolve, 250) })
return {
settingsWritable: settings.writable,
settingIds: settings.namespaces.map(namespace => namespace.ns),
savedTimeout: saved.value.timeoutMs,
rereadTimeout: reread.namespaces.find(namespace => namespace.ns === 'bash-sandbox')?.value.timeoutMs,
resetTimeout: reset.value.timeoutMs,
initialTimeout: shell.value.timeoutMs,
resetOverrides: reset.user,
renamedTitle: secondRename.title,
renameAdvanced: secondRename.seq > firstRename.seq,
skillCount: skills.skills.length,
@@ -406,6 +419,16 @@ async function bootPreview(origin: string, browser: Browser): Promise<void> {
seededSessionId: VFS_EXAMPLE_SESSION_IDS.main,
seededSessionTitle: SHOWCASE_TITLE,
})
expect(exercised.settingsWritable).toBe(true)
expect(exercised.settingIds).toEqual(expect.arrayContaining([
'bash-sandbox', 'locale', 'ui-theme', 'ui-chat', 'ui-conversation', 'ui-settings', 'ui-settings-general',
]))
expect(exercised.savedTimeout).toBe(61_000)
expect(exercised.rereadTimeout).toBe(61_000)
expect(exercised.resetTimeout).toBe(exercised.initialTimeout)
expect(exercised.resetOverrides).not.toHaveProperty('timeoutMs')
await expect.poll(() => page.evaluate(() => document.body.style.getPropertyValue('--dsh-content-font-size')))
.toBe('17px')
expect(exercised.renamedTitle).toBe(SHOWCASE_TITLE)
expect(exercised.renameAdvanced).toBe(true)
expect(exercised.skillCount).toBeGreaterThan(0)
+33 -27
View File
@@ -33,8 +33,8 @@ import { expect } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import Include, { type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import Group from '@deepseek-ai/cordis-plugin-group'
import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import yaml from 'js-yaml'
import {
captureExpectedWorkspaceSnapshot,
captureWorkspaceSnapshot,
@@ -109,7 +109,9 @@ function appBoot(): AppBoot {
// WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE,
// WELCOME_NOTICE_VERSION, WELCOME_NOTICE_COPY,
// } from '@deepseek-ai/dsh-client-ui-settings-models'
export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-onboarding'
export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-settings-general'
/** The installed bundle carrying the scaffold's deployment defaults; the plugin manager lists it beside fixture bundles. */
export const SCAFFOLD_DEFAULTS_BUNDLE = 'dsh-web-scaffold-defaults'
export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
export const WELCOME_NOTICE_VERSION = '2026-08-13.1'
export const WELCOME_NOTICE_COPY = {
@@ -641,7 +643,6 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
],
},
}],
{ id: 'settings', config: { dshHome: harnessHome } },
{ id: 'credentials', config: { dshHome: harnessHome } },
// The shipped directory-picker row is the -auto chooser, which resolves
// the interaction from the RUNNING host (display, SSH launch, bind). The
@@ -674,7 +675,20 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
}],
{ id: 'llm-deepseek', disabled: mode !== 'record' && !maskDeepSeekCredential },
]
const patches: PatchOptions[] = [...basePatches, ...surfacePatches, ...overlayPatches]
// Live fields use a shared deployment layer; process-specific ports and roots stay in CLI overlays.
const formEntries = new Set(['agent-default-model', 'agent-preset-registry', 'llm-deepseek', 'llm-pi-ai',
'web-search-deepseek', 'agent-loop', 'subagent', 'bash-sandbox', 'pwsh-sandbox',
'ui-theme', 'locale', 'ui-chat', 'ui-conversation', 'ui-settings', 'ui-settings-general', 'permission'])
const formDefaults: PatchOptions[] = []
const processOverlays = overlayPatches.map((patch) => {
if (patch.id === undefined || !formEntries.has(patch.id) || patch.config === undefined) return patch
const config: unknown = patch.config
formDefaults.push({ id: patch.id, config })
const ordinary = { ...patch }
Reflect.deleteProperty(ordinary, 'config')
return ordinary
})
// Sessions inherit the gateway's process.cwd() default; run the boot from
// the temp workspace so tool cwd, session cwd, and fixtures agree.
@@ -730,13 +744,13 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
const rootConfig = join(profileDir, 'cordis.yml')
await writeFile(rootConfig, '[]\n')
ctx.baseUrl = pathToFileURL(profileDir).href + '/'
let profileContext: ProfileContext | undefined
if (options.profile !== undefined) {
let profileContext: ProfileContext
{
// A real profile: the shipped web bundles plus each fixture package,
// installed the way `dsh plugin add` leaves them.
const dependencies: Record<string, string> = {}
const bundles = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', ...options.profile.bundles ?? []]
for (const entry of options.profile.packages) {
const bundles = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', ...options.profile?.bundles ?? []]
for (const entry of options.profile?.packages ?? []) {
const manifest = JSON.parse(await readFile(join(entry.dir, 'package.json'), 'utf8')) as { name: string }
dependencies[manifest.name] = `file:${entry.dir}`
if (entry.enabled === true) bundles.push(manifest.name)
@@ -744,6 +758,13 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
await mkdir(dirname(link), { recursive: true })
await symlink(entry.dir, link, 'junction')
}
// Fixture deployment defaults remain below editable profile values.
const fixtureDir = join(profileDir, 'node_modules', SCAFFOLD_DEFAULTS_BUNDLE)
await mkdir(fixtureDir, { recursive: true })
await writeFile(join(fixtureDir, 'package.json'), JSON.stringify({ name: SCAFFOLD_DEFAULTS_BUNDLE, version: '1.0.0', dsh: { bundle: { patch: 'cordis.patch.yml' } } }))
await writeFile(join(fixtureDir, 'cordis.patch.yml'), yaml.dump(formDefaults, { schema: entryListSchema }))
bundles.push(SCAFFOLD_DEFAULTS_BUNDLE)
dependencies[SCAFFOLD_DEFAULTS_BUNDLE] = `file:${fixtureDir}`
initProfile(profileDir, bundles)
const manifest = readProfileManifest('dsh', profileDir)
manifest.dependencies = dependencies
@@ -752,7 +773,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
name: 'scaffold', dir: profileDir, patchPath: profile.patchPath, installAnchor: INSTALL_ANCHOR,
cwd: workspaceCwd, home: harnessHome,
startedBundles: loadProfileDirectory('dsh', profileDir, INSTALL_ANCHOR).layers.map(layer => layer.packageName),
overlays: overlayPatches, telemetryDisabledEnv: undefined,
overlays: processOverlays, telemetryDisabledEnv: undefined,
}
// HMR gates file-driven reloads on application readiness, which the
// launcher commits after boot; this direct harness is ready at once.
@@ -775,26 +796,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
resolution,
})
await ctx.plugin(Loader)
if (profileContext === undefined) {
ctx.loader.builtins.include = Include
// `cordis:group` beside it, exactly as `boot()` registers it: a group row is
// how a preset gives one `isolate` realm to a provider and its consumers,
// including when the deployment supplies only Cordis builtin resolution.
ctx.loader.builtins.group = Group
await ctx.loader.create({
name: 'cordis:include',
config: { path: pathToFileURL(rootConfig).href, patches },
})
} else {
// The launcher's own mount, so the manager's reloads find the root Include
// and compose the same layers the profile files name; bare names still
// resolve through the runtime resolution above, as in the direct mount.
await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext))
}
await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext))
await ctx.loader.await()
await auditStartupEntries(ctx, 'web e2e scaffold')
if (options.developerTools !== undefined) {
await ctx.settings.update('ui-developer-tools', { enabled: options.developerTools })
await ctx.settings.update('ui-settings', { enabled: options.developerTools })
}
if (options.welcomeNoticePending !== true) {
await ctx.settings.mutate(WELCOME_NOTICE_SETTINGS_NAMESPACE, [{
+23 -22
View File
@@ -250,8 +250,8 @@ describe('web e2e: settings modal and General preferences', () => {
await page.getByRole('menuitem', { name: '仅可查看' }).click()
await dialog.getByRole('button', { name: '仅可查看' }).waitFor({ timeout: 10_000 })
const document = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
expect(document).toContain('permission:')
const document = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(document).toContain('id: permission')
expect(document).toContain('defaultPreset: read-only')
expect(existing.snapshotEvents().find(event => event.type === 'permission/preset')?.data)
.toEqual({ preset: 'workspace-write' })
@@ -271,7 +271,7 @@ describe('web e2e: settings modal and General preferences', () => {
await confirmation.getByRole('checkbox').click()
await enable.click()
await dialog.getByRole('button', { name: '完全权限' }).waitFor({ timeout: 10_000 })
const confirmedDocument = await readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8')
const confirmedDocument = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
expect(confirmedDocument).toContain('defaultPreset: danger-full-access')
const confirmed = scaffold.ctx.sessions.create(SessionId('settings-permission-confirmed'))
expect(confirmed.snapshotEvents().map(event => [event.type, event.data])).toEqual([
@@ -298,7 +298,8 @@ describe('web e2e: settings modal and General preferences', () => {
cube.click(),
])
expect(response.ok()).toBe(true)
expect(await response.json()).toMatchObject({
const outcome: unknown = await response.json()
expect(outcome, JSON.stringify(outcome)).toMatchObject({
result: { ok: true, value: { ns: 'ui-theme', value: { preference } } },
})
}
@@ -311,8 +312,8 @@ describe('web e2e: settings modal and General preferences', () => {
const darkCube = initialDialog.getByRole('button', { name: '深色' })
await selectTheme(darkCube, 'dark')
await expect.poll(() => darkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true')
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/ui-theme:\n\s+preference: dark/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('preference: dark')
await page.keyboard.press('Escape')
// Hold the real application batch so the shell-owned loading page remains observable.
@@ -421,8 +422,8 @@ describe('web e2e: settings modal and General preferences', () => {
expect(dark.legacy).toBeNull()
expect(dark.token).not.toBe(light.token)
expectThemeColorSynchronized(dark)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/ui-theme:\n\s+preference: dark/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('preference: dark')
await page.keyboard.press('Escape')
// Reload: the preference survives the background Host read + presenter update.
@@ -515,8 +516,8 @@ describe('web e2e: settings modal and General preferences', () => {
expect(await response.finished()).toBeNull()
const envelope = await response.json() as { result: { ok: boolean } }
expect(envelope.result.ok).toBe(true)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(new RegExp(`ui-theme:\n(?:\\s+\\w+: .*\n)*?\\s+fontSize: ${px}`))
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain(`fontSize: ${px}`)
await page.getByRole('dialog', { name: '设置' }).getByText(String(px), { exact: true }).waitFor({ timeout: 5_000 })
await expect.poll(readFontSize, { timeout: 5_000 }).toBe(`${px}px`)
}
@@ -570,7 +571,7 @@ describe('web e2e: settings modal and General preferences', () => {
await details.getByRole('button', { name: '简洁', exact: true }).click()
await page.getByRole('menuitem', { name: label, exact: true }).click()
await details.getByRole('button', { name: label, exact: true }).waitFor({ timeout: 10_000 })
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain(`transcriptView: ${mode}`)
await page.keyboard.press('Escape')
@@ -586,8 +587,8 @@ describe('web e2e: settings modal and General preferences', () => {
await restoredDetails.getByRole('button', { name: label, exact: true }).click()
await page.getByRole('menuitem', { name: '简洁', exact: true }).click()
await restoredDetails.getByRole('button', { name: '简洁', exact: true }).waitFor({ timeout: 10_000 })
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/ui-chat:\n\s+transcriptView: compact/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('transcriptView: compact')
await page.keyboard.press('Escape')
expect(tripwire.pageErrors).toEqual([])
}, 90_000)
@@ -601,8 +602,8 @@ describe('web e2e: settings modal and General preferences', () => {
await page.getByRole('menuitem', { name: '插话发送' }).click()
await dialog.getByRole('button', { name: '插话发送' }).waitFor({ timeout: 10_000 })
expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/ui-conversation:\n\s+busyEnter: steer/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('busyEnter: steer')
await page.keyboard.press('Escape')
const warningStart = tripwire.warnings.length
@@ -635,8 +636,8 @@ describe('web e2e: settings modal and General preferences', () => {
await page.getByRole('menuitem', { name: '排队发送' }).click()
await reloaded.getByRole('button', { name: '排队发送' }).waitFor({ timeout: 10_000 })
expect(await page.evaluate(() => localStorage.getItem('dsh.conversation.busyEnter'))).toBeNull()
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/ui-conversation:\n\s+busyEnter: queue/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('busyEnter: queue')
await page.keyboard.press('Escape')
expect(tripwire.pageErrors).toEqual([])
}, 90_000)
@@ -667,8 +668,8 @@ describe('web e2e: settings modal and General preferences', () => {
await enDialog.getByText(`Current version: ${version}`, { exact: true }).waitFor()
await expect.poll(() => enDialog.getByText('Appearance', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/locale:\n\s+preference: en/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('preference: en')
// Reload keeps English; then restore zh so shared page state (and the
// other specs' 设置-anchored selectors + goldens) see the default again.
const warningStart = tripwire.warnings.length
@@ -703,8 +704,8 @@ describe('web e2e: settings modal and General preferences', () => {
await page.getByRole('menuitem', { name: '中文' }).click()
await page.getByRole('dialog', { name: '设置' }).waitFor({ timeout: 10_000 })
expect(await page.evaluate(() => localStorage.getItem('dsh.locale'))).toBeNull()
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
.toMatch(/locale:\n\s+preference: zh/)
await expect.poll(async () => readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain('preference: zh')
await page.keyboard.press('Escape')
expect(tripwire.pageErrors).toEqual([])
}, 90_000)
@@ -737,7 +738,7 @@ describe('web e2e: settings modal and General preferences', () => {
await enPage.keyboard.press('Escape')
await expect.poll(() => enPage.getByRole('dialog', { name: 'Settings' }).count(), { timeout: 5_000 }).toBe(0)
await enPage.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click()
await enPage.getByText('This deployment runs without a manageable profile, so plugins cannot be installed or switched here.', { exact: true })
await enPage.getByRole('button', { name: 'Add plugin', exact: true })
.waitFor({ timeout: 10_000 })
// This page has no closing inventory spec to sweep its console, so the
// scenario clears both tripwire channels itself.
+44
View File
@@ -0,0 +1,44 @@
// Web e2e scenario: a `settings.yaml` left in the harness home by earlier releases is imported into the
// scaffold profile at start, through the shipped entries, and the imported values reach the page.
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { chromium } from 'playwright'
import { expect, it } from 'vitest'
import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
import yaml from 'js-yaml'
import { WELCOME_NOTICE_VERSION, launchWebScaffold, watchConsole } from './scaffold.ts'
import { ZH_BROWSER_LOCALE } from './support.ts'
it('imports settings.yaml into the profile once and applies the imported values', async () => {
const harnessHome = mkdtempSync(join(tmpdir(), 'dsh-settings-import-'))
writeFileSync(join(harnessHome, 'settings.yaml'), [
'ui-theme:', ' fontSize: 16',
'ui-developer-tools:', ' enabled: false',
'ui-onboarding:', ` welcomeNoticeVersion: '${WELCOME_NOTICE_VERSION}'`,
'',
].join('\n'))
const scaffold = await launchWebScaffold({ harnessHome, welcomeNoticePending: true })
const browser = await chromium.launch()
try {
const patchPath = join(harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml')
type Row = { id?: string; config?: Record<string, unknown> }
const config = (id: string): Record<string, unknown> | undefined =>
(yaml.load(readFileSync(patchPath, 'utf8'), { schema: entryListSchema }) as Row[]).find(row => row.id === id)?.config
await expect.poll(() => config('ui-theme')?.['fontSize'], { timeout: 10_000 }).toBe(16)
expect(config('ui-settings')?.['enabled']).toBe(false)
expect(config('ui-settings-general')?.['welcomeNoticeVersion']).toBe(WELCOME_NOTICE_VERSION)
expect(existsSync(join(harnessHome, 'settings.yaml'))).toBe(false)
expect(readFileSync(join(harnessHome, 'settings.yaml.imported'), 'utf8')).toContain('fontSize: 16')
const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
const tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await expect.poll(() => page.evaluate(() => document.body.style.getPropertyValue('--dsh-content-font-size')), { timeout: 10_000 }).toBe('16px')
expect(tripwire.pageErrors).toEqual([])
} finally {
await browser.close()
await scaffold.close()
}
}, 120_000)
+9 -5
View File
@@ -309,7 +309,7 @@ const notReady = UI_PLUGIN_DIRS.filter((dir) => {
if (notReady.length > 0) console.warn(`[smoke-real] skipped — client bundles not ready: ${notReady.join(', ')}`)
describe('dsh web keyless CLI smoke', () => {
it('serves a usable app from two immutable plugin batches', async () => {
it('serves a usable app from three immutable plugin batches', async () => {
requireDist()
const sessionsDir = mkdtempSync(join(tmpdir(), 'dsh-web-keyless-'))
const tsxLoader = pathToFileURL(createRequire(join(REPO_ROOT, 'package.json')).resolve('tsx')).href
@@ -356,10 +356,13 @@ describe('dsh web keyless CLI smoke', () => {
await page.goto(readyUrl)
await page.getByRole('button', { name: 'New session', exact: true }).first().waitFor({ timeout: 30_000 })
const batchPaths = [...new Set(pluginScripts)].sort()
expect(batchPaths).toHaveLength(2)
expect(batchPaths).toContainEqual(expect.stringMatching(
/^\/plugins\/\?\?.+\/client\.js,.+\/client\.js&rev=[a-f\d]{12}$/,
))
// The bootstrap phase is the modules package alone; the application phase
// spans two combos because its map-form URL is over the 3 KiB combo limit
// since the four settings companions joined the composition.
expect(batchPaths).toHaveLength(3)
expect(batchPaths.filter(path => (
/^\/plugins\/\?\?.+\/client\.js,.+\/client\.js&rev=[a-f\d]{12}$/.test(path)
))).toHaveLength(2)
expect(batchPaths).toContainEqual(expect.stringMatching(
/^\/plugins\/\?\?@deepseek-ai\/dsh-client-modules\/client\.js&rev=[a-f\d]{12}$/,
))
@@ -367,6 +370,7 @@ describe('dsh web keyless CLI smoke', () => {
expect([...cacheHeaders.values()]).toEqual([
'public, max-age=31536000, immutable',
'public, max-age=31536000, immutable',
'public, max-age=31536000, immutable',
])
for (const path of batchPaths) {
const [scriptResponse, mapResponse] = await Promise.all([
+1 -1
View File
@@ -255,7 +255,7 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => {
expect(await process.count()).toBe(1)
expect(await process.getAttribute('aria-expanded')).toBe('false')
expect(await tool.isVisible()).toBe(false)
await expect.poll(async () => readFile(join(scaffold!.harnessHome, 'settings.yaml'), 'utf8'), { timeout: 5_000 })
await expect.poll(async () => readFile(join(scaffold!.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8'), { timeout: 5_000 })
.toContain(`transcriptView: ${mode}`)
await page.getByRole('button', { name: 'Settings', exact: true }).click()
+1
View File
@@ -60,6 +60,7 @@
"tests/plugin-install-registry.e2e.ts",
"tests/client-plugin-live.e2e.ts",
"tests/settings-chrome.e2e.ts",
"tests/settings-import.e2e.ts",
"tests/desktop-updates.e2e.ts",
"tests/developer-tools-settings.e2e.ts",
"tests/models-settings.e2e.ts",
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/architecture.md
architecture.md: 514bd52cfa8f50fe8cf73c391094d34942b3cca3
architecture.zh.md: 848fa1b3810403e4a3906ac491c8552052e4ee4e
architecture.md: e09bc38c291dd9a3450cfaef17212514cacdab13
architecture.zh.md: 53125c0d796680a05f190adcb848e2b5d5d00076
+1 -1
View File
@@ -161,4 +161,4 @@ New behavior attaches to a documented extension point. Changing the loop itself
| Store sessions in a new backend | implement `SessionPersistence` (`create`/`open`/`stat`/`list`/`export`) over the shared handle scaffolding |
| Scope a registration to one agent | use that agent's `agent.ctx` |
The [extension cookbook](cookbook/extension-cookbook.md) maps features to capabilities and indexes the step-by-step guides for [packages](cookbook/adding-a-package.md), [tools](cookbook/adding-a-tool.md), [LLM adapters](cookbook/adding-an-llm-adapter.md), and [settings cards](cookbook/adding-a-settings-card.md). The [Conversation subsystem](subsystems/conversation.md) owns Chat-node assembly.
The [extension cookbook](cookbook/extension-cookbook.md) maps features to capabilities and indexes the step-by-step guides for [packages](cookbook/adding-a-package.md), [tools](cookbook/adding-a-tool.md), [LLM adapters](cookbook/adding-an-llm-adapter.md), and [settings pages](cookbook/adding-a-settings-card.md). The [Conversation subsystem](subsystems/conversation.md) owns Chat-node assembly.
+1 -1
View File
@@ -165,4 +165,4 @@ seam 正是替换一个提供方就能改变整个产品的原因。文件系统
| 在新后端存储会话 | 基于共享的句柄脚手架实现 `SessionPersistence`(`create`/`open`/`stat`/`list`/`export`) |
| 将注册项限定到单个 agent | 使用该 agent 的 `agent.ctx` |
[扩展实操手册](cookbook/extension-cookbook.zh.md)将功能映射到能力,并索引[包](cookbook/adding-a-package.zh.md)、[工具](cookbook/adding-a-tool.zh.md)、[LLM(大语言模型)适配器](cookbook/adding-an-llm-adapter.zh.md)和[设置卡片](cookbook/adding-a-settings-card.zh.md)的分步指南。[Conversation 子系统](subsystems/conversation.zh.md)负责 Chat node 组装。
[扩展实操手册](cookbook/extension-cookbook.zh.md)将功能映射到能力,并索引[包](cookbook/adding-a-package.zh.md)、[工具](cookbook/adding-a-tool.zh.md)、[LLM(大语言模型)适配器](cookbook/adding-an-llm-adapter.zh.md)和[设置页](cookbook/adding-a-settings-card.zh.md)的分步指南。[Conversation 子系统](subsystems/conversation.zh.md)负责 Chat node 组装。
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/capability-seams.md
capability-seams.md: 66425afe98bcbefe69912bf130cb72bba9435ec0
capability-seams.zh.md: faa31be64081a80d58a0f302f91c737c34ed3f38
capability-seams.md: 13890605db55379005a0842004bcdbfc64119ee8
capability-seams.zh.md: ff30bb3455d7fefc239109b48adb5f8fa015289e
+15 -9
View File
@@ -3,7 +3,7 @@
# Capability Seams And Core Services
A service can be a core spine service, a swappable capability seam, or a bundle/composition point. The graph shows the package that owns the service declaration, known implementation packages, and packages that consume the service directly.
A service can be a core spine service, a swappable capability seam, a bundle/composition point, or a standalone service. The graph shows the package that owns the service declaration, known implementation packages, and packages that consume the service directly.
```mermaid
flowchart LR
@@ -94,9 +94,11 @@ flowchart LR
pkg_tool_bash["tool-bash"]
pkg_hooks_claude_code["hooks-claude-code"]
pkg_hooks_codex["hooks-codex"]
pkg_config_editor["config-editor"]
svc_configEditor["ctx.configEditor<br/>Profile configuration edits"]
pkg_settings["settings"]
svc_settings["ctx.settings<br/>User-settings seam"]
pkg_settings_file["settings-file"]
pkg_agent_default_model["agent-default-model"]
svc_settings["ctx.settings<br/>Plugin configuration forms"]
pkg_tool_subagent["tool-subagent"]
svc_subagentModelSelection["ctx.subagentModelSelection<br/>Subagent model-selection preference"]
pkg_credentials["credentials"]
@@ -104,6 +106,8 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_host_product_telemetry_otel["host-product-telemetry-otel"]
svc_productTelemetry["ctx.productTelemetry<br/>Product usage event sender"]
pkg_session_telemetry["session-telemetry"]
svc_sessionTelemetry["ctx.sessionTelemetry<br/>Session telemetry seam"]
pkg_session_telemetry_otel["session-telemetry-otel"]
@@ -159,7 +163,6 @@ flowchart LR
pkg_skill_office["skill-office"]
svc_agents["ctx.agents<br/>Agent service"]
pkg_acp["acp"]
pkg_agent_default_model["agent-default-model"]
svc_agentDefaultModel["ctx.agentDefaultModel<br/>Default Agent model selection"]
pkg_headless["headless"]
svc_agentLoop["ctx.agentLoop<br/>Concrete loop driver"]
@@ -292,6 +295,7 @@ flowchart LR
pkg_compaction_basic --> svc_compaction
pkg_compaction_tool_result_pruner --> svc_toolResultPruner
pkg_computer_use --> svc_computerUse
pkg_config_editor --> svc_configEditor
pkg_cordis_host_runner --> svc_cordisInspect
pkg_cordis_host_runner --> svc_dynamicCordisRunner
pkg_credentials --> svc_credentials
@@ -318,6 +322,7 @@ flowchart LR
pkg_host_directory_picker --> svc_directoryPicker
pkg_host_directory_picker_browse --> svc_directoryPicker
pkg_host_directory_picker_native --> svc_directoryPicker
pkg_host_product_telemetry_otel --> svc_productTelemetry
pkg_host_webserver --> svc_webServer
pkg_inspector --> svc_inspector
pkg_invariants --> svc_invariants
@@ -359,7 +364,6 @@ flowchart LR
pkg_session_title_all_prompts_llm --> svc_sessionTitle
pkg_session_title_first_prompt_llm --> svc_sessionTitle
pkg_settings --> svc_settings
pkg_settings_file --> svc_settings
pkg_shell --> svc_shell
pkg_shell_env --> svc_shellEnv
pkg_skill --> svc_skills
@@ -426,6 +430,8 @@ flowchart LR
svc_compaction --> pkg_compaction_basic
svc_computerUse --> pkg_experimental_computer_use_cua_driver_mcp
svc_computerUse --> pkg_experimental_computer_use_cua_driver_native
svc_configEditor --> pkg_agent_default_model
svc_configEditor --> pkg_settings
svc_connection --> pkg_api_gateway
svc_connection --> pkg_host_frontend_static
svc_cordisInspect --> pkg_tool_cordis
@@ -489,8 +495,6 @@ flowchart LR
svc_sessions --> pkg_session_query_sqlite
svc_sessions --> pkg_subagent_in_process_driver
svc_settings --> pkg_api_settings_controller
svc_settings --> pkg_llm_deepseek
svc_settings --> pkg_llm_pi_ai
svc_shell --> pkg_hooks_claude_code
svc_shell --> pkg_hooks_codex
svc_shell --> pkg_tool_bash
@@ -582,10 +586,12 @@ flowchart LR
| `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | Plugins register live zod contributions directly or through dsh-typert-loader; the API gateway consumes invocation descriptors and providers, while other runtime consumers query schemas and reflection metadata at their own edges. |
| `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier. |
| `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session/session-persistence) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/shell/tool-bash), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`message-feedback`](../packages/feedback/message-feedback) | - | The JSONL backend persists the SessionEvent vocabulary as one artifact per Session. |
| `ctx.settings` | `seam` | [`settings`](../packages/settings/settings) | [`settings-file`](../packages/settings/settings-file) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Plugins register namespace schemas and resolve layered values; providers store the raw document. The LLM adapters register their entry config as the composition base under the user section; the settings controller serves redacted layered descriptors and writes the user layer. |
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. |
| `ctx.productTelemetry` | `service` | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | - | - | - | Exports explicitly submitted analytics events through OTLP/HTTP; mounting alone collects nothing. |
| `ctx.sessionTelemetry` | `seam` | [`session-telemetry`](../packages/session/session-telemetry) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | - | The seam captures, redacts, and hands session records to one backend; nothing else consumes the service — its output leaves the process. |
| `ctx.storage` | `seam` | [`storage`](../packages/storage/storage) | [`storage-json`](../packages/storage/storage-json), [`storage-sqlite`](../packages/storage/storage-sqlite) | [`storage-domain`](../packages/storage/storage-domain) | - | Backends register side by side under names; data forms (domain first) mount on the hub and translate typed operations into opaque KV-unit primitives. |
| `ctx.storageDomain` | `core` | [`storage-domain`](../packages/storage/storage-domain) | - | [`workspace`](../packages/workspace/workspace) | - | Waits for every configured backend, then publishes the domain form as one lifecycle-bound service for typed durable state. |
@@ -606,7 +612,7 @@ flowchart LR
| `ctx.sessionProjectionCache` | `core` | [`session-projection-cache`](../packages/session/session-projection-cache) | - | [`api-session-controller`](../packages/api/session-controller), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent) | - | Durably checkpoints projection unit states per session (throttled + turn/end/detach mandatory points) and serves the cold-read ladder: cache row + persistence tail replay, so listings never load full logs. |
| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem), [`skill-office`](../packages/skill/skill-office) | [`tool-skill`](../packages/skill/tool-skill) | - | Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies. |
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Layers the default ModelSelection through settings so direct and Host-backed Agent entry points share one state owner. |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. |
| `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | Owns one authenticated OpenSSH connection, installed helper identity, independent program streams and disconnect cleanup for the paired remote providers. |
+15 -9
View File
@@ -5,7 +5,7 @@
[English](capability-seams.md) | 中文
服务可以是核心主干服务、可替换的能力 seam,也可以是组合包/组合点。下图展示了拥有服务声明的包、已知实现包,以及直接消费该服务的包。
服务可以是核心主干服务、可替换的能力 seam、组合包/组合点或独立服务。下图展示了拥有服务声明的包、已知实现包,以及直接消费该服务的包。
```mermaid
flowchart LR
@@ -96,9 +96,11 @@ flowchart LR
pkg_tool_bash["tool-bash"]
pkg_hooks_claude_code["hooks-claude-code"]
pkg_hooks_codex["hooks-codex"]
pkg_config_editor["config-editor"]
svc_configEditor["ctx.configEditor<br/>Profile configuration edits"]
pkg_settings["settings"]
svc_settings["ctx.settings<br/>User-settings seam"]
pkg_settings_file["settings-file"]
pkg_agent_default_model["agent-default-model"]
svc_settings["ctx.settings<br/>Plugin configuration forms"]
pkg_tool_subagent["tool-subagent"]
svc_subagentModelSelection["ctx.subagentModelSelection<br/>Subagent model-selection preference"]
pkg_credentials["credentials"]
@@ -106,6 +108,8 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_host_product_telemetry_otel["host-product-telemetry-otel"]
svc_productTelemetry["ctx.productTelemetry<br/>Product usage event sender"]
pkg_session_telemetry["session-telemetry"]
svc_sessionTelemetry["ctx.sessionTelemetry<br/>Session telemetry seam"]
pkg_session_telemetry_otel["session-telemetry-otel"]
@@ -161,7 +165,6 @@ flowchart LR
pkg_skill_office["skill-office"]
svc_agents["ctx.agents<br/>Agent service"]
pkg_acp["acp"]
pkg_agent_default_model["agent-default-model"]
svc_agentDefaultModel["ctx.agentDefaultModel<br/>Default Agent model selection"]
pkg_headless["headless"]
svc_agentLoop["ctx.agentLoop<br/>Concrete loop driver"]
@@ -294,6 +297,7 @@ flowchart LR
pkg_compaction_basic --> svc_compaction
pkg_compaction_tool_result_pruner --> svc_toolResultPruner
pkg_computer_use --> svc_computerUse
pkg_config_editor --> svc_configEditor
pkg_cordis_host_runner --> svc_cordisInspect
pkg_cordis_host_runner --> svc_dynamicCordisRunner
pkg_credentials --> svc_credentials
@@ -320,6 +324,7 @@ flowchart LR
pkg_host_directory_picker --> svc_directoryPicker
pkg_host_directory_picker_browse --> svc_directoryPicker
pkg_host_directory_picker_native --> svc_directoryPicker
pkg_host_product_telemetry_otel --> svc_productTelemetry
pkg_host_webserver --> svc_webServer
pkg_inspector --> svc_inspector
pkg_invariants --> svc_invariants
@@ -361,7 +366,6 @@ flowchart LR
pkg_session_title_all_prompts_llm --> svc_sessionTitle
pkg_session_title_first_prompt_llm --> svc_sessionTitle
pkg_settings --> svc_settings
pkg_settings_file --> svc_settings
pkg_shell --> svc_shell
pkg_shell_env --> svc_shellEnv
pkg_skill --> svc_skills
@@ -428,6 +432,8 @@ flowchart LR
svc_compaction --> pkg_compaction_basic
svc_computerUse --> pkg_experimental_computer_use_cua_driver_mcp
svc_computerUse --> pkg_experimental_computer_use_cua_driver_native
svc_configEditor --> pkg_agent_default_model
svc_configEditor --> pkg_settings
svc_connection --> pkg_api_gateway
svc_connection --> pkg_host_frontend_static
svc_cordisInspect --> pkg_tool_cordis
@@ -491,8 +497,6 @@ flowchart LR
svc_sessions --> pkg_session_query_sqlite
svc_sessions --> pkg_subagent_in_process_driver
svc_settings --> pkg_api_settings_controller
svc_settings --> pkg_llm_deepseek
svc_settings --> pkg_llm_pi_ai
svc_shell --> pkg_hooks_claude_code
svc_shell --> pkg_hooks_codex
svc_shell --> pkg_tool_bash
@@ -584,10 +588,12 @@ flowchart LR
| `ctx.typert` | `core` | [`typert-registry`](../packages/typert/registry) | - | [`typert-loader`](../packages/typert/loader), [`api-gateway`](../packages/api/gateway) | - | 插件直接或通过 dsh-typert-loader 注册实时 zod 贡献;API 网关消费调用描述符和提供方,其他运行时消费方则在各自边界查询 schema 与反射元数据。 |
| `ctx.typertGateway` | `core` | [`api-gateway`](../packages/api/gateway) | - | - | - | 将生成的 Remote 描述符与实时 Cordis 服务关联,解析已注册的身份,并通过共享的 Connection RPC 载体提供一元调用。 |
| `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session/session-persistence) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/shell/tool-bash), [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`message-feedback`](../packages/feedback/message-feedback) | - | JSONL backend 把 SessionEvent 词汇持久化为每个 Session 一份产物。 |
| `ctx.settings` | `seam` | [`settings`](../packages/settings/settings) | [`settings-file`](../packages/settings/settings-file) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 插件注册命名空间 schema 并解析分层值;提供方存储原始文档。LLM(大语言模型)适配器在用户分区下将其入口配置注册为组合基础;settings controller 提供经过脱敏的分层描述符,并写入用户层。 |
| `ctx.configEditor` | `core` | [`config-editor`](../packages/boot/config-editor) | - | [`settings`](../packages/settings/settings), [`agent-default-model`](../packages/core/agent-default-model) | - | Persists profile config patches under the application file lock and HMR queue, then reconciles Loader entries. |
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 |
| `ctx.productTelemetry` | `service` | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | - | - | - | 通过 OTLP/HTTP 发送显式提交的分析事件;仅挂载插件不会采集信息。 |
| `ctx.sessionTelemetry` | `seam` | [`session-telemetry`](../packages/session/session-telemetry) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | - | 该 seam 捕获会话记录、进行脱敏并交给一个后端;没有其他组件消费该服务,其输出会离开当前进程。 |
| `ctx.storage` | `seam` | [`storage`](../packages/storage/storage) | [`storage-json`](../packages/storage/storage-json), [`storage-sqlite`](../packages/storage/storage-sqlite) | [`storage-domain`](../packages/storage/storage-domain) | - | 各后端以不同名称并列注册;数据形态(领域优先)挂载到枢纽上,并将类型化操作转换为不透明的 KV 单元原语。 |
| `ctx.storageDomain` | `core` | [`storage-domain`](../packages/storage/storage-domain) | - | [`workspace`](../packages/workspace/workspace) | - | 等待所有已配置后端就绪,然后将领域形态发布为一个受生命周期约束的服务,用于类型化持久状态。 |
@@ -608,7 +614,7 @@ flowchart LR
| `ctx.sessionProjectionCache` | `core` | [`session-projection-cache`](../packages/session/session-projection-cache) | - | [`api-session-controller`](../packages/api/session-controller), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent) | - | 按会话持久保存投影单元状态的检查点(节流检查点,以及轮次/结束/分离时的必选检查点),并提供冷读取阶梯:缓存行加持久化尾部回放,因此列表读取永远不需要加载完整日志。 |
| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem), [`skill-office`](../packages/skill/skill-office) | [`tool-skill`](../packages/skill/tool-skill) | - | 合并提供方的 skill(技能)目录;tool-skill 渲染会话前缀目录,并加载完整的 skill 正文。 |
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | - | 拥有实时 Agent 句柄、创建/恢复工厂 seam,以及进程本地的发起方传播。 |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | 通过 settings 分层默认 `ModelSelection`,让直接入口与 Host 支撑的 Agent 入口共享同一个状态所有者。 |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | 从会话日志折叠带修订版本的目标状态,并将实时延续激活保留在进程本地。 |
| `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | 负责一条经过认证的 OpenSSH 连接、已安装辅助程序身份、独立程序流,以及配套远端提供方的断连清理。 |
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/config-catalog.md
config-catalog.md: 08821db1fb58d0b88639e27ec7687cdbf17b329e
config-catalog.zh.md: 1cd039f3e95934a56e6d83c7f3c5e13dd63f3c35
config-catalog.md: c46008dd88e51dc079d72e6605d06176c26bdea1
config-catalog.zh.md: 7376476771902e1bbcba3ae4d6374b1087e14a72
+145 -86
View File
@@ -38,16 +38,20 @@ Source: [`packages/acp/acp/src/index.ts:75`](../packages/acp/acp/src/index.ts)
## `@deepseek-ai/dsh-agent-default-model`
```ts config-catalog
/** Composition entry for the default model selection. */
/** Default model selection supplied by plugin configuration. */
export interface Config {
/** Registered provider route. */
provider: string
provider: Volatile<string>
/** Provider-owned model id. */
model: string
model: Volatile<string>
/** Adapter-owned reasoning effort; omission follows the provider default. */
reasoningEffort: Volatile<string | undefined>
}
```
Source: [`packages/core/agent-default-model/src/index.ts:41`](../packages/core/agent-default-model/src/index.ts)
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/core/agent-default-model/src/index.ts:24`](../packages/core/agent-default-model/src/index.ts)
<a id="deepseek-aidsh-agent-instructions"></a>
@@ -94,7 +98,7 @@ export interface Config {
* Maximum parallel-safe calls in flight per agent step. `1` is serial;
* omission defaults to {@link DEFAULT_MAX_PARALLEL_TOOL_CALLS}.
*/
maxParallelToolCalls?: number
maxParallelToolCalls: Volatile<number>
/** Agents created or resumed at plugin startup. */
agents: (AgentOptions & {
/** Stable config label used in logs and as the fresh combined-id prefix. */
@@ -109,9 +113,9 @@ export interface Config {
}
```
Depends on: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md)
Depends on: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) · `Volatile` (`@deepseek-ai/cosmokit`)
Source: [`packages/core/agent-loop/src/index.ts:319`](../packages/core/agent-loop/src/index.ts)
Source: [`packages/core/agent-loop/src/index.ts:292`](../packages/core/agent-loop/src/index.ts)
<a id="deepseek-aidsh-agent-preset"></a>
@@ -139,10 +143,16 @@ Requires: `loader` · `sessionProjections`
export interface Config {
/** Deployment default when the caller omits a preset. */
default: string
/** User-selected default while the chooser is shown; edited through Settings. */
selectedDefault: Volatile<string | undefined>
/** Whether new-session surfaces expose preset selection and the saved default applies. */
modeSelectionEnabled: Volatile<boolean>
}
```
Source: [`packages/preset/agent-preset-registry/src/preset.ts:12`](../packages/preset/agent-preset-registry/src/preset.ts)
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/preset/agent-preset-registry/src/preset.ts:13`](../packages/preset/agent-preset-registry/src/preset.ts)
<a id="deepseek-aidsh-agent-tool-presentation"></a>
@@ -367,23 +377,25 @@ Source: [`packages/attachment/attachment-local/src/index.ts:61`](../packages/att
Requires: `subprocess`
```ts config-catalog
/** Plugin config (all optional — `static Config` supplies the defaults). */
/** Validated plugin configuration with live command budgets. */
export interface Config {
/** Default working directory for commands (default: process.cwd()). */
cwd?: string
cwd: Volatile<string | undefined>
/** Default foreground timeout in milliseconds. */
timeoutMs?: number
timeoutMs: Volatile<number>
/** Upper bound for per-call timeout overrides. */
maxTimeoutMs?: number
maxTimeoutMs: Volatile<number>
/** Per-stream in-memory output cap; overflow spills to a temp file. */
maxOutputBytes?: number
maxOutputBytes: Volatile<number>
/** Per-stream spill-file cap; larger streams retain only their in-memory tail. */
maxSpillBytes?: number
maxSpillBytes: Volatile<number>
/** Grace period for kill escalation and inherited pipes; at most `MAX_TIMER_DELAY_MS`. */
graceMs?: number
graceMs: Volatile<number>
}
```
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/shell/bash-local/src/index.ts:41`](../packages/shell/bash-local/src/index.ts)
<a id="deepseek-aidsh-bash-sandbox"></a>
@@ -501,6 +513,27 @@ export interface Config {
Source: [`packages/client/ui-sidebar-documentpreview/src/config.ts:5`](../packages/client/ui-sidebar-documentpreview/src/config.ts)
<a id="deepseek-aidsh-client-ui-theme"></a>
## `@deepseek-ai/dsh-client-ui-theme`
```ts config-catalog
/** Runtime preferences projected to the browser. */
export interface Config {
/** Browser palette preference. */
preference: Volatile<ThemePreference>
/** Browser font size in pixels. */
fontSize: Volatile<number>
}
/** Theme preference persisted by the product Appearance row. */
export type ThemePreference = typeof THEME_PREFERENCES[number]
```
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/client/ui-theme/src/index.ts:22`](../packages/client/ui-theme/src/index.ts)
<a id="deepseek-aidsh-compaction-basic"></a>
## `@deepseek-ai/dsh-compaction-basic`
@@ -882,16 +915,18 @@ Source: [`packages/experimental/ptc-runtime-python/src/index.ts:42`](../packages
## `@deepseek-ai/dsh-experimental-speech-to-text`
```ts config-catalog
/** Composition defaults resolved before a transcription starts. */
/** Live selection read before a transcription starts; `configure()` writes it through the profile. */
export interface Config {
/** Registered provider selected when the caller omits an id. */
defaultProvider: string
defaultProvider: Volatile<string>
/** Provider language hint selected when the caller omits one. */
language: string
language: Volatile<string>
}
```
Source: [`packages/experimental/speech-to-text/src/index.ts:18`](../packages/experimental/speech-to-text/src/index.ts)
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/experimental/speech-to-text/src/index.ts:20`](../packages/experimental/speech-to-text/src/index.ts)
<a id="deepseek-aidsh-experimental-speech-to-text-sensevoice"></a>
@@ -1208,6 +1243,40 @@ export interface Config {
Source: [`packages/host/open-in-app/src/index.ts:50`](../packages/host/open-in-app/src/index.ts)
<a id="deepseek-aidsh-host-product-telemetry-otel"></a>
## `@deepseek-ai/dsh-host-product-telemetry-otel`
```ts config-catalog
/** Collector routing, application identity, and bounded in-memory batch settings. */
export interface Config {
/** Full HTTP(S) logs URL. */
endpoint: string
/** Collector routing header. */
channel: string
/** Resource service.name supplied by the application composition. */
serviceName: string
/** Resource service.version supplied by the application composition. */
serviceVersion: string
/** Omit to honor OTEL_EXPORTER_OTLP_LOGS_COMPRESSION / OTEL_EXPORTER_OTLP_COMPRESSION. */
compression?: 'none' | 'gzip'
/** Maximum records per export; must not exceed maxQueueSize. */
maxExportBatchSize: number
/** Maximum queued records; the SDK drops new records when full. */
maxQueueSize: number
/** Delay before exporting a partial batch. */
scheduledDelayMillis: number
/** Exporter HTTP deadline, including SDK transient-error retries. */
timeoutMillis: number
/** Processor deadline for one batch export. */
exportTimeoutMillis: number
/** Outer shutdown wait; pending exports may be lost after this deadline. */
shutdownTimeoutMillis: number
}
```
Source: [`packages/host/product-telemetry-otel/src/index.ts:37`](../packages/host/product-telemetry-otel/src/index.ts)
<a id="deepseek-aidsh-host-webserver"></a>
## `@deepseek-ai/dsh-host-webserver`
@@ -1292,43 +1361,43 @@ Requires: `llm`
*/
export interface Config {
/** Credential reference (environment-variable name) resolved per request; defaults to `DEEPSEEK_API_KEY`. */
apiKeyEnv?: string
apiKeyEnv: Volatile<string>
/** Endpoint base; falls back to $DEEPSEEK_BASE_URL from a trusted environment layer, then the public API. */
baseURL?: string
baseURL: Volatile<string | undefined>
/** Deployment thinking policy; `disabled` limits every conversation request to `off`. */
thinking?: 'enabled' | 'disabled'
thinking: Volatile<'enabled' | 'disabled' | undefined>
/** Default thinking effort (default `high`); `off` disables thinking per request. */
reasoningEffort?: 'off' | 'low' | 'high' | 'max'
reasoningEffort: Volatile<'off' | 'low' | 'high' | 'max' | undefined>
/** Default per-request output cap (default 256,000); a model's own cap and explicit request values win. */
maxTokens?: number
maxTokens: Volatile<number>
/** Positive context capacity used when the selected model has no exact value (default 1,000,000). */
defaultContextWindow?: number
defaultContextWindow: Volatile<number>
/** Advisory models shown by discovery consumers; defaults to V41 Flash and V4 Pro. */
models?: DeepSeekCatalogModel[]
models: Volatile<DeepSeekCatalogModel[]>
/** Maximum provider idle time while one stream read is outstanding (default five minutes). */
streamIdleTimeoutMs?: number
streamIdleTimeoutMs: Volatile<number>
/** Maximum accumulated file-referenced image bytes per chat request (default 128 MiB). */
maxRequestFilesBytes?: number
maxRequestFilesBytes: Volatile<number>
/** Maximum accumulated base64 image payload after Files API fallback (default 20 MiB). */
maxInlineRequestImageBytes?: number
maxInlineRequestImageBytes: Volatile<number>
/** Maximum number of represented images per chat request (default 600). */
maxImagesPerRequest?: number
maxImagesPerRequest: Volatile<number>
/** Raw-byte removal step after the request exceeds its file bound (default 64 MiB). */
imageOffloadByteQuantum?: number
imageOffloadByteQuantum: Volatile<number>
/** Base64-byte removal step after inline fallback exceeds its bound (default 10 MiB). */
inlineImageOffloadByteQuantum?: number
inlineImageOffloadByteQuantum: Volatile<number>
/** Image-count removal step after the request exceeds its count bound (default 20). */
imageOffloadCountQuantum?: number
imageOffloadCountQuantum: Volatile<number>
/** Maximum duration of one request-image Files API resolution (default one minute). */
filesApiTimeoutMs?: number
filesApiTimeoutMs: Volatile<number>
/** Explicit lifetime assigned to each uploaded image (default seven days). */
fileExpiresAfterSeconds?: number
fileExpiresAfterSeconds: Volatile<number>
/** Remaining lifetime below which an indexed file is replaced (default one hour). */
fileRefreshMarginSeconds?: number
fileRefreshMarginSeconds: Volatile<number>
/** Oldest harness-owned files deleted before one quota-recovery upload retry (default 100). */
fileQuotaCleanupBatch?: number
fileQuotaCleanupBatch: Volatile<number>
/** Provider-owned model-request retry policy; omission uses normal mode with five retries. */
retryPolicy?: RetryPolicyConfig
retryPolicy: Volatile<RetryPolicyConfig | undefined>
}
/** One optional model entry advertised by the direct-fetch adapter. */
@@ -1362,9 +1431,9 @@ export interface DeepSeekCatalogModel {
}
```
Depends on: [`ModelModality`](../packages/llm/llm/src/index.ts) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · [`SystemPromptUpdate`](../packages/llm/llm/src/index.ts)
Depends on: [`ModelModality`](../packages/llm/llm/src/index.ts) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · [`SystemPromptUpdate`](../packages/llm/llm/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/llm/llm-deepseek/src/config.ts:25`](../packages/llm/llm-deepseek/src/config.ts)
Source: [`packages/llm/llm-deepseek/src/config.ts:28`](../packages/llm/llm-deepseek/src/config.ts)
<a id="deepseek-aidsh-llm-pi-ai"></a>
@@ -1380,7 +1449,7 @@ export interface Config {
* the dormant settings-driven posture: the adapter mounts with no routes
* and registers them the moment a settings section supplies profiles.
*/
providers?: Record<string, PiAiProviderProfile>
providers: Volatile<Record<string, PiAiProviderProfile>>
}
/** Configuration for one pi-ai provider route; the `providers` dict key IS the route. */
@@ -1637,9 +1706,9 @@ export type PiAiThinkingFormat = NonNullable<OpenAICompletionsCompat['thinkingFo
export type PiAiThinkingTokenBudgetField = NonNullable<OpenAICompletionsCompat['thinkingTokenBudgetField']>
```
Depends on: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`)
Depends on: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/llm/llm-pi-ai/src/config.ts:221`](../packages/llm/llm-pi-ai/src/config.ts)
Source: [`packages/llm/llm-pi-ai/src/config.ts:222`](../packages/llm/llm-pi-ai/src/config.ts)
<a id="deepseek-aidsh-llm-replay"></a>
@@ -1933,12 +2002,12 @@ export interface Config {
* never). The names `custom` and `auto` are reserved for derived state and
* the Auto review integration respectively.
*/
presets?: Record<string, PresetSpec>
presets: Record<string, PresetSpec>
/**
* Default for new sessions. When omitted, the preset matching the composed
* sandbox and approval defaults is used.
*/
defaultPreset?: string
defaultPreset: Volatile<string | undefined>
}
/** One preset's sandbox/approval bundle and optional client presentation. */
@@ -1954,9 +2023,9 @@ export interface PresetSpec {
}
```
Depends on: [`ApprovalPolicy`](subsystems/approval.md) · [`SandboxMode`](subsystems/sandbox.md)
Depends on: [`ApprovalPolicy`](subsystems/approval.md) · [`SandboxMode`](subsystems/sandbox.md) · `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/interaction/permission-presets/src/index.ts:156`](../packages/interaction/permission-presets/src/index.ts)
Source: [`packages/interaction/permission-presets/src/index.ts:155`](../packages/interaction/permission-presets/src/index.ts)
<a id="deepseek-aidsh-persona"></a>
@@ -2092,30 +2161,32 @@ Source: [`packages/ptc-runtime/ptc-runtime-node/src/index.ts:26`](../packages/pt
Requires: `subprocess`
```ts config-catalog
/** Plugin config (all optional — `static Config` supplies the defaults). */
/** Validated plugin configuration with live command budgets. */
export interface Config {
/** Default working directory for commands (default: process.cwd()). */
cwd?: string
cwd: Volatile<string | undefined>
/** Default foreground timeout in milliseconds. */
timeoutMs?: number
timeoutMs: Volatile<number>
/** Upper bound for per-call timeout overrides. */
maxTimeoutMs?: number
maxTimeoutMs: Volatile<number>
/** Per-stream in-memory output cap; overflow spills to a temp file. */
maxOutputBytes?: number
maxOutputBytes: Volatile<number>
/** Per-stream spill-file cap; larger streams retain only their in-memory tail. */
maxSpillBytes?: number
maxSpillBytes: Volatile<number>
/** Grace period for kill escalation and inherited pipes; at most `MAX_TIMER_DELAY_MS`. */
graceMs?: number
graceMs: Volatile<number>
/**
* Explicit pwsh executable. When omitted, well-known Windows install
* locations and PATH entries are probed in order (PowerShell 7 install,
* PATH entries such as the Microsoft Store install, then Windows
* PowerShell 5.1), falling back to a bare `pwsh` resolved through PATH.
*/
pwshPath?: string
pwshPath: Volatile<string | undefined>
}
```
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/shell/pwsh-local/src/index.ts:58`](../packages/shell/pwsh-local/src/index.ts)
<a id="deepseek-aidsh-pwsh-sandbox"></a>
@@ -2524,26 +2595,6 @@ Depends on: [`SessionTitleLlmConfig`](../packages/session/session-title-llm/src/
Source: [`packages/session/session-title-first-prompt-llm/src/index.ts:15`](../packages/session/session-title-first-prompt-llm/src/index.ts)
<a id="deepseek-aidsh-settings-file"></a>
## `@deepseek-ai/dsh-settings-file`
```ts config-catalog
/** Plugin config: file location and hot-reload behavior. */
export interface Config {
/** Settings document path; defaults to `settings.yaml` under the harness home. */
path?: string
/** Harness home used when `path` is omitted; defaults to `$DSH_HOME` or `~/.dsh`. */
dshHome?: string
/** Watch the document and hot-publish external edits; defaults to true. */
watch?: boolean
/** Watcher write-settle window in milliseconds; defaults to 100. */
debounceMs?: number
}
```
Source: [`packages/settings/settings-file/src/index.ts:22`](../packages/settings/settings-file/src/index.ts)
<a id="deepseek-aidsh-shell-env"></a>
## `@deepseek-ai/dsh-shell-env`
@@ -2801,12 +2852,14 @@ Source: [`packages/storage/storage-sqlite/src/index.ts:24`](../packages/storage/
/** Host configuration for continuable subagent capacity. */
export interface Config {
/** Maximum live children sharing uninterrupted continuable parent links; defaults to 8. */
maxActiveSubagents?: number
maxActiveSubagents: Volatile<number>
/** Default delegation depth for tools without an explicit limit; defaults to 1. */
maxDepth?: number
maxDepth: Volatile<number>
}
```
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/subagent/subagent/src/index.ts:191`](../packages/subagent/subagent/src/index.ts)
<a id="deepseek-aidsh-subagent-acp"></a>
@@ -3818,22 +3871,24 @@ Requires: `web`
/** Plugin config (all optional — `apply` fills env-var and constant defaults). */
export interface Config {
/** Literal DeepSeek API key; prefer {@link apiKeyEnv} so no secret enters configuration files. */
apiKey?: string
apiKey: Volatile<string | undefined>
/** Credential reference resolved for each search; defaults to `DEEPSEEK_API_KEY`. */
apiKeyEnv?: string
apiKeyEnv: Volatile<string>
/** Anthropic-compatible endpoint base; `/messages` is appended. */
baseURL?: string
baseURL: Volatile<string | undefined>
/** Anthropic-format model name. Defaults to `deepseek-v4-flash`. */
model?: string
model: Volatile<string>
/** `anthropic-version` header value. Defaults to `2023-06-01`. */
apiVersion?: string
apiVersion: Volatile<string>
/** Upper bound on generated tokens for the Messages request. Defaults to 4096. */
maxTokens?: number
maxTokens: Volatile<number>
/** Maximum `web_search` server-tool uses per request. Defaults to 5. */
maxUses?: number
maxUses: Volatile<number>
}
```
Depends on: `Volatile` (`@deepseek-ai/cordis`)
Source: [`packages/web/web-search-deepseek/src/index.ts:46`](../packages/web/web-search-deepseek/src/index.ts)
<a id="deepseek-aidsh-web-search-exa"></a>
@@ -3996,10 +4051,14 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-client-ui-schedule` ([`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts))
- `@deepseek-ai/dsh-client-ui-session` ([`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings` ([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-agent-loop` ([`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-general` ([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-models` ([`packages/client/ui-settings-models/src/index.ts`](../packages/client/ui-settings-models/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-plugin-inventory` ([`packages/client/ui-settings-plugin-inventory/src/index.ts`](../packages/client/ui-settings-plugin-inventory/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-plugins` ([`packages/client/ui-settings-plugins/src/index.ts`](../packages/client/ui-settings-plugins/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-shell` ([`packages/client/ui-settings-shell/src/index.ts`](../packages/client/ui-settings-shell/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-subagent` ([`packages/client/ui-settings-subagent/src/index.ts`](../packages/client/ui-settings-subagent/src/index.ts))
- `@deepseek-ai/dsh-client-ui-settings-web-search` ([`packages/client/ui-settings-web-search/src/index.ts`](../packages/client/ui-settings-web-search/src/index.ts))
- `@deepseek-ai/dsh-client-ui-sidebar` ([`packages/client/ui-sidebar/src/index.ts`](../packages/client/ui-sidebar/src/index.ts))
- `@deepseek-ai/dsh-client-ui-sidebar-browser` ([`packages/client/ui-sidebar-browser/src/index.ts`](../packages/client/ui-sidebar-browser/src/index.ts))
- `@deepseek-ai/dsh-client-ui-sidebar-files` ([`packages/client/ui-sidebar-files/src/index.ts`](../packages/client/ui-sidebar-files/src/index.ts))
@@ -4007,7 +4066,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-client-ui-sidebar-terminal` ([`packages/client/ui-sidebar-terminal/src/index.ts`](../packages/client/ui-sidebar-terminal/src/index.ts))
- `@deepseek-ai/dsh-client-ui-skill` ([`packages/client/ui-skill/src/index.ts`](../packages/client/ui-skill/src/index.ts))
- `@deepseek-ai/dsh-client-ui-subagent` ([`packages/client/ui-subagent/src/index.ts`](../packages/client/ui-subagent/src/index.ts))
- `@deepseek-ai/dsh-client-ui-theme` ([`packages/client/ui-theme/src/index.ts`](../packages/client/ui-theme/src/index.ts))
- `@deepseek-ai/dsh-client-ui-tool` ([`packages/client/ui-tool/src/index.ts`](../packages/client/ui-tool/src/index.ts))
- `@deepseek-ai/dsh-client-ui-trajectory` ([`packages/client/ui-trajectory/src/index.ts`](../packages/client/ui-trajectory/src/index.ts))
- `@deepseek-ai/dsh-client-ui-user-questions` ([`packages/client/ui-user-questions/src/index.ts`](../packages/client/ui-user-questions/src/index.ts))
@@ -4019,6 +4077,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-commands` ([`packages/interaction/commands/src/index.ts`](../packages/interaction/commands/src/index.ts))
- `@deepseek-ai/dsh-compaction-image-offload` — requires `agents` · `sessions` ([`packages/compaction/compaction-image-offload/src/index.ts`](../packages/compaction/compaction-image-offload/src/index.ts))
- `@deepseek-ai/dsh-computer-use` ([`packages/computer-use/computer-use/src/index.ts`](../packages/computer-use/computer-use/src/index.ts))
- `@deepseek-ai/dsh-config-editor` — requires `loader` · `profileContext` ([`packages/boot/config-editor/src/index.ts`](../packages/boot/config-editor/src/index.ts))
- `@deepseek-ai/dsh-cordis-client-runner` ([`packages/extensions/cordis-client-runner/src/index.ts`](../packages/extensions/cordis-client-runner/src/index.ts))
- `@deepseek-ai/dsh-deepseek-llm-api-extensions` ([`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts))
- `@deepseek-ai/dsh-experimental-auto-review` — requires `llm` · `permissionPresets` · `sessions` · `tools` ([`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts))
@@ -4041,6 +4100,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-session-projection` ([`packages/session/session-projection/src/index.ts`](../packages/session/session-projection/src/index.ts))
- `@deepseek-ai/dsh-session-stats` — requires `sessionProjections` ([`packages/session/session-stats/src/index.ts`](../packages/session/session-stats/src/index.ts))
- `@deepseek-ai/dsh-session-turn-outline` — requires `sessionProjections` ([`packages/session/session-turn-outline/src/index.ts`](../packages/session/session-turn-outline/src/index.ts))
- `@deepseek-ai/dsh-settings` — requires `configEditor` · `profileContext` ([`packages/settings/settings/src/index.ts`](../packages/settings/settings/src/index.ts))
- `@deepseek-ai/dsh-skill-badge` — requires `skills` ([`packages/skill/skill-badge/src/index.ts`](../packages/skill/skill-badge/src/index.ts))
- `@deepseek-ai/dsh-storage` ([`packages/storage/storage/src/index.ts`](../packages/storage/storage/src/index.ts))
- `@deepseek-ai/dsh-subprocess-local` ([`packages/subprocess/subprocess-local/src/index.ts`](../packages/subprocess/subprocess-local/src/index.ts))
@@ -4069,7 +4129,6 @@ Abstract service classes — a deployment loads a concrete implementation packag
- `@deepseek-ai/dsh-sandbox` — abstract `SandboxProvider` ([`packages/sandbox/sandbox/src/index.ts`](../packages/sandbox/sandbox/src/index.ts))
- `@deepseek-ai/dsh-session-persistence` — abstract `SessionPersistence` ([`packages/session/session-persistence/src/index.ts`](../packages/session/session-persistence/src/index.ts))
- `@deepseek-ai/dsh-session-query` — abstract `SessionQueryEngine` ([`packages/session-query/session-query/src/index.ts`](../packages/session-query/session-query/src/index.ts))
- `@deepseek-ai/dsh-settings` — abstract `SettingsProvider` ([`packages/settings/settings/src/index.ts`](../packages/settings/settings/src/index.ts))
- `@deepseek-ai/dsh-shell` — abstract `ShellExecutor` ([`packages/shell/shell/src/index.ts`](../packages/shell/shell/src/index.ts))
- `@deepseek-ai/dsh-spill` — abstract `SpillStore` ([`packages/spill/spill/src/index.ts`](../packages/spill/spill/src/index.ts))
- `@deepseek-ai/dsh-subprocess` — abstract `SubprocessRuntime` ([`packages/subprocess/subprocess/src/index.ts`](../packages/subprocess/subprocess/src/index.ts))
+364 -306
View File
File diff suppressed because it is too large. Load diff
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/cookbook/adding-a-settings-card.md
adding-a-settings-card.md: d1104299d319203789c9cd153f36b3f5e33edd10
adding-a-settings-card.zh.md: 3ef245d76331015f4d69db52bfbd176dff3e4bcf
adding-a-settings-card.md: 3e473d8bbc52d0bbfddcabc2512dbef1b23a8fb4
adding-a-settings-card.zh.md: fd2c71366112b7f89c1a7f3de000a28778c44ee7
+36 -66
View File
@@ -1,85 +1,63 @@
# Cookbook: adding a settings card
# Cookbook: live configuration forms
English | [中文](adding-a-settings-card.zh.md)
How a plugin puts its own configuration on the web settings page. Nothing in this path needs a change inside this repository: the Host serves every registered settings namespace, and the **Plugins** section keys its cards on the namespace they edit, so a plugin that registers both halves is paired up automatically.
Declare live fields in the plugin Config schema and expose them through a product-owned settings card. The exported `Config` interface describes the values received by the plugin, including each `Volatile<T>` reference.
The two halves live in one package — the Host half under `src/`, the browser half under `src/client/`, exported as `./client` and declared with `dsh.client`. [`packages/client/ui-theme`](../../packages/client/ui-theme) is a worked example of that packaging; the cards this section ships live in [`packages/client/ui-settings-plugins`](../../packages/client/ui-settings-plugins).
## 1. Register the namespace (Host half)
The namespace is the join key, so pick it once and spell it in both halves. A consumer that already has a `cordis.yml` entry should register through `ctx.settings.installSection()`, which layers the entry under the user document and keeps working when no settings provider is mounted:
## 1. Declare live fields
```ts
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-settings'
import type { Context, Volatile } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
declare function assertReachable(endpoint: string | undefined): void
declare function rebuildFromSettings(config: Config): void
export const MY_PLUGIN_NS = 'my-plugin'
export interface Config {
endpoint?: string
retries?: number
endpoint: Volatile<string | undefined>
retries: Volatile<number>
}
export const Config: z<Config> = z.object({
endpoint: z.string(),
retries: z.number().step(1).min(0).default(3),
export const Config = z.object({
endpoint: z.string().volatile(),
retries: z.number().step(1).min(0).default(3).volatile(),
})
export function apply(ctx: Context, config: Config) {
let source = () => config
ctx.inject(['settings'], (settingsCtx) => {
settingsCtx.settings.installSection(ctx, MY_PLUGIN_NS, Config, config, {
// Constraints the schema cannot express refuse the write, not the next use.
validate: value => void assertReachable(value.endpoint),
setSource: (current) => { source = current },
onChange: () => { rebuildFromSettings(source()) },
})
export function apply(ctx: Context, config: Config): void {
ctx.on('loader/volatile-update', () => {
ctx.logger.info('Retry limit: %d', config.retries.get())
})
}
```
`role('secret')` on a field keeps its value off every response; the card writes such a field into an `update`/`mutate` payload, or addresses a credential reference through the `credentials` domain instead. `applies: 'restart'` tells a configuration surface the owner acts on a change only at the next start.
Read `.get()` when starting an operation. A request that needs a consistent snapshot captures its values once. Use `.check()` for cross-field Config validation; these checks run on the Host before persistence and are omitted from serialized form schemas.
## 2. Register the card (browser half)
## 2. Compose the plugin
The card registers into `settings.plugin.item` under its namespace and owns everything inside it — chrome, controls, and copy. It reads and writes through `ctx.settingsScope`, which fences each write with the revision it read:
Give each instance a unique profile entry id. The base bundle mounts settings and config-editor. For custom profiles, see their package READMEs before mounting the same services.
```ts ignore-check
import type { Context as ClientContext } from '@deepseek-ai/cordis'
// Type-only: the keyed slot's declaration. Cross-plugin collaboration goes
// through cordis services; a value import fails the client bundle-purity gate.
import type {} from '@deepseek-ai/dsh-client-ui-settings-plugins/client'
`role('secret')` keeps a value out of form responses. Use credential references for values managed by the credentials domain. Ordinary fields stay out of the settings schema.
export const inject = ['slots', 'locale', 'connection', 'remote', 'settingsScope']
## 3. Verify editing
export function apply(ctx: ClientContext): void {
const card = new MyPluginCardController(ctx.settingsScope.bind({ namespace: 'my-plugin' }))
ctx.slots.inject('settings.plugin.item', () => ctx.slots.register({
name: 'settings.plugin.item',
key: 'my-plugin',
locale: 'settings.myPlugin',
inject: () => card.inject(),
}, MyPluginCard),
)
}
Change a field in Plugins and save. Verify the profile patch, the next consumer operation, unchanged plugin instance identity, and restoration after restart. Reject an invalid value and verify that neither the file nor the live value changed.
Custom plugin pages receive `form.state` and `form.mutate(operations, expectedRevision)` from the Plugins page owner. The Host validates full Config and applies edits through ConfigEditor and volatile HMR. The [plugin settings package](../../packages/client/ui-settings-plugins/README.md) owns the existing card examples.
## 4. Contribute to another plugin's page
A plugin with something to say about a bundle, a row, or an official plugin it does not own registers into `plugins.detail.actions` (a control at the head of the page), `plugins.detail.badge` (a tag beside the title), or `plugins.detail.section` (a section under the page's own content). Every entry is rendered with the page's `subject` — `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }` — and returns null for a subject it has nothing for:
```tsx ignore-check
ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({
name: 'plugins.detail.badge',
id: 'acme-update',
locale: 'acmeUpdate',
}, ({ t, subject }) => subject.kind === 'bundle' && hasUpdate(subject.pkg) ? <Tag tone="info">{t('update')}</Tag> : null))
```
The scope snapshot carries what a form needs: the resolved `value`, the composition `base`, and the raw `user` layer, whose key **presence** — not its value — is what marks a field overridden. `scope.set(field, value)` stores one field and `scope.unset(field)` clears it back to the composition layer.
## 5. Where the browser half rides
## 3. What the tab does with it
The browser half is served to the page by the [client module system](../../packages/client/modules), which scans the enabled Loader entries for packages declaring `dsh.client` and serves each one's built `./client` export — but it attaches a package's half to the Loader row whose specifier is the bare package name. A row mounted from a subpath export never carries a half, so a bundle that splits one package into several rows keeps its half on the root row, and every page it registers goes away when that row is switched off. A sub-plugin whose page must outlive the other rows ships as its own package.
The **Plugin configuration** tab reads which namespaces the Host serves and dispatches one slot key per namespace. A card is rendered when the Host serves its key and skipped when it does not, so a deployment that never composed the Host half shows no trace of the card. A served namespace no card claims renders nothing — that is how the namespaces owned by other pages (`ui-theme`, `permission`, `llm-*`) stay off this tab.
Cards appear in the order they registered into the slot; a keyed entry declares no `order` of its own.
## Packaging
The browser half is served to the page by the [client module system](../../packages/client/modules), which scans the enabled Loader entries for packages declaring `dsh.client` and serves each one's built `./client` export. So the plugin appears on the page as soon as a `cordis.yml` mounts it — no rebuild of the web application.
The built `./client` file must be in the client module system's lazy-CJS factory format: one script that registers the package name and a `factory(require)` with the page's module loader, described in the [client module system's README](../../packages/client/modules/README.md). The `clientBundle` tsdown preset that emits it lives in `packages/client/tsdown.client.ts` rather than in a published package, so a package outside this repository reproduces that build itself.
```jsonc
{
@@ -87,16 +65,8 @@ The browser half is served to the page by the [client module system](../../packa
".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" },
"./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }
},
"dsh": { "client": { "platform": "web", "inject": ["@deepseek-ai/dsh-client-ui-settings-plugins"] } }
"dsh": { "client": { "platform": "web", "inject": ["@deepseek-ai/dsh-client-ui-settings"] } }
}
```
The bundle must be the loader's lazy-CJS factory artifact. Inside this repository `tsdown.config.ts` is three lines over the shared preset:
```ts ignore-check
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle('@deepseek-ai/dsh-client-my-plugin', ['lib/types/index.js', 'lib/types/invariant.js'])
```
No published preset exposes this package, so a package outside this repository has to reproduce the same output format itself. The bundle-purity gate also rejects value imports across plugins, so a card cannot import this section's card chrome or its staged-form model — it renders its own, and owns its own staging and revision fencing. Both limits are recorded under [the section's known limitations](../../packages/client/ui-settings-plugins/README.md#known-limitations-and-deferred-work).
A companion package for a built-in namespace is the same browser half in a client-only package with an empty Host `apply`, listed in the web composition's plugin roster ([`packages/bundle/web-app/cordis.patch.yml`](../../packages/bundle/web-app/cordis.patch.yml)) and registering into `plugins.item` through `ctx.configForms.whileServed`, so the page exists exactly while the Host serves the namespace.
Loaded 100 of 661 files, more files were not shown because too many files have changed in this diff. Show more