Merge pull request #8504 from deepseek-harness/feat/client-config-live-update

feat(client): sync volatile plugin config to the browser
This commit is contained in:
imccyu authored and GitHub committed 2026-11-17 16:08:14 +08:00
1 parent 4c74abdbad
commit bd1d6dcd0c
175 files changed
+3691 -779

No files matched your search

@@ -18,23 +18,23 @@
en: 5f5daec51b20db77
zh: e4d6f78fc1b4b835
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps:
en: 0a4240d88cca240a
zh: 8f5f1527caf571cd
en: 04b9f0138b5d2288
zh: 2a749db57f6e7a10
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/the-loading-flow-end-to-end:
en: 1f7db6ecfc0b0831
zh: f6bf37dc921a7d40
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/live-graph-reconciliation:
en: ab9577214d7b2f2b
zh: fc8f10fd8c90b34b
en: d7777566a2594654
zh: 509cad4a363184ae
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/hot-reload-one-driver-plugin-self-watched-bundles:
en: e6a0bee3d31cd2c6
zh: 7f7384c5d1a74751
en: d31506b6ccca554e
zh: 91f4eb62927ebabe
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/package-ownership:
en: 94ca0d09e6fd1e3a
zh: d5949a2bdec795ba
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/consequences:
en: 624efdd136029771
zh: 7d60207147e631fe
en: cfeb5dc97753e46f
zh: 92da07a598f7cfb0
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/alternatives-considered:
en: b8f036f50cff7cd8
zh: 6d623c4a1f4314b1
@@ -46,7 +46,7 @@ A `require.async("./client.<name>.js")` call requests the exact revisioned `/plu
The shared tsdown preset emits a map for every plugin entry and chunk and rewrites first-party source paths into the browser-resolvable repository form `/packages/<group>/<package>/src/...`. The production Client pass consumes `lib/types`; the preset supplies each tsc map to Rolldown and fills `sourcesContent` from the original files, so the final map reaches TypeScript/TSX instead of stopping at emitted JavaScript. Other workspace sources inlined into a bundle likewise resolve to their `packages/` owner, while dependency paths remain unchanged. Combo generation strips each local debug directive, records its generated-line offset, resolves every authored source against the original per-plugin map URL, and emits an Indexed Source Map v3. An authored map supplies its section; otherwise an identity section embeds the generated bundle and uses the packer's `sourceURL` as its source name when present. The absolute combo map URL mirrors the script resource list by changing every `client.js` suffix to `client.js.map`, so `/plugins/??<package-a>/client.js,<package-b>/client.js&rev=<rev>` points to `/plugins/??<package-a>/client.js.map,<package-b>/client.js.map&rev=<rev>`. A chunk script likewise points to its own map URL. Source-map files are read and combined only when those map URLs receive `GET`; `HEAD` materializes neither script nor map bodies. The Vite shell also emits source maps, letting shell code and externally loaded plugins map stacks and performance profiles back to TypeScript/TSX.
The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting SSE snapshot does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id.
The graph retains each row's revisioned one-resource combo URL for HMR and adds a revisioned descriptor for every startup combo request; several descriptors may carry the same scheduling phase. Initial publication and `rebuilt(id)` use the same hash of entry mtime, ctime, and size; artifact contents never enter the hash. Ctime distinguishes rewrites that preserve mtime and size. A Host restart over unchanged artifacts therefore retains every row revision, so the reconnecting stream baseline does not trigger browser plugin replacement. The shared preset stamps the entry after every package output is written; a chunk-only build therefore advances the owner revision without a Host-side sibling scan. Startup combo revisions derive from the ordered row revisions. Script bodies are assembled on their first `GET`; source-map files are read and combined separately on their first map `GET`. `HEAD` materializes neither body. Versioned scripts and maps use immutable caching, and unrelated graph recomposition retains already-materialized chunk responses at the same revision. The Host serves only exact generated URLs; stale revisions and unadvertised resource lists return 404 instead of aliasing different bytes. An external script's `error` event exposes neither response status nor body, so failure diagnostics name only the URL; the same-origin Host and build-stamped registration id form the identity boundary, while the post-`load` factory-presence check rejects an artifact that did not register the expected id.
### The loading flow, end to end
@@ -76,13 +76,13 @@ Stylesheet metadata and renderer ownership follow the [module metadata decision]
The modules controller owns exactly the Loader entries created from the boot manifest. Full Host snapshots update its module descriptors and reconcile those entries; other Loader contributors retain ownership. New modules arrive through single-resource URLs because replaying a startup batch could register an existing factory twice. Removal uses Loader deletion, then drains the captured fiber before removing unused module records. Declared and observed transitive requests keep shared modules alive. Factory revision tracking is independent of entry activation because a download or materialization can finish without creating an entry. Graph updates invalidate stale factories and failed arrival targets without managed entries, notifying resource consumers before any consumer imports its dependencies; rebuilt frames also reconcile entries missing after import failures.
The Host SSE adapter forwards existing graph-change notifications and sends the current full graph on connection. The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
The Host `pluginEvents/follow` Remote stream forwards existing graph-change notifications and opens every generation with the current full graph; graph rows also carry each plugin's synced configuration ([browser plugin configuration sync](2026-11-15-client-config-sync.md)). The graph describes desired browser entries, not Host cleanup completion: Host lifecycle ordering belongs to its Loader, while each browser waits for its own removed fibers. Graph reconciliation and rebuilt code share one page-owned queue. Local generations prevent stale downloads from mounting; opaque revisions are compared only for equality. The settings inventory reports page-local errors and can retry the same graph without changing Host enablement. This preserves unrelated page state and avoids both an application restart and a second plugin executor. Electron's independent installation flow remains outside this mechanism.
### Hot reload: one driver plugin, self-watched bundles
Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the SSE channel, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row.
Hot reload is a composition decision: the web bundle mounts the `client-hmr` row (a normal plugin package) unconditionally; its node half brings the bundle watch and the authenticated plugin-events Remote stream, and the chain stays idle until a rebuild watcher rewrites client bundles. A composition that must not expose it disables the row.
How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half broadcasts a `rebuilt` frame on `GET /plugins/events` — a system SSE channel that sends the full graph on connect and `rebuilt` frames on change, presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol.
How does a rebuilt bundle become a reload signal? The hmr node half observes it itself — no builder tells it. Before reading each startup snapshot, the module host captures the entry stat baseline and exposes it through `ctx.clientModules.artifactBaseline(id)`. One HMR-owned interval compares every current graph row with that baseline. An unchanged row starts watching without a content read or hash; a write after baseline capture is already a stat delta and only that row enters `rebuilt(id)`. This avoids redundant reads when installing the watcher and avoids `fs.watchFile`, whose asynchronous first baseline can silently absorb a construction-time rebuild. Watch membership follows `onGraphChanged`; vanished rows drop out, and an entry missing at poll time keeps its row dirty so reappearance retries publication even when mtime and size match the baseline. The shared tsdown preset stamps `client.js` after every sibling output has been written; on an entry mtime, ctime, or size delta, or a dirty row, `rebuilt(id)` derives the revision from those three metadata values. It reads the new bundle snapshot only if the revision changes. A chunk-only edit therefore changes the revision, and a partial write followed by the completion stamp supplies a later stat change that self-heals. When the `rev` changes, the node half publishes a `rebuilt` frame on the authenticated `pluginEvents/follow` Remote stream, which opens every generation with the full graph and then sends `graph` and `rebuilt` increments; it is presentation-only wire that never enters the session log. Polling is deliberate because inotify does not fire on the weka network mount, the same reason the build-side watcher needs `--poll`; one entry stat per row and interval is sufficient, the interval is a validated config field (default 500ms), and disposal clears the one timer. Rebuilding artifacts is any process using the shared Client tsdown preset — `scripts/dev-web.ts` remains the watch-build entry point, discovering its package list through `dsh.client` while scanning `packages/*/*/package.json` at startup — and builder and host share no notification protocol.
On the browser side, the transport delegates code replacement to the same modules controller that owns graph reconciliation:
@@ -96,7 +96,7 @@ On the browser side, the transport delegates code replacement to the same module
Bootstrap replacement is rejected before invalidation or teardown: the module system retains its initial exports, so remounting its old code would reset consumers without applying the requested revision. The page reports the required reload and preserves the bootstrap fiber. Every non-bootstrap plugin shares the replacement semantics; an `immediately` row reloads exactly like a lazy one. Dependency cascade costs zero client code: a fiber's activation epoch strings its service providers' uids, so replacing a foundational provider such as connection re-loads every dependent through cordis itself — correct, if heavy.
Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old SSE channel and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival.
Reload creates a fresh fiber and component state; it does not preserve React state inside the replaced plugin. Static assembly libraries and the shell require a rebuilt page; when the Host itself serves another release, the page holds plugin replacement and asks whether to reload ([Host release change prompt](../feature/2026-10-14-host-release-change-refresh-prompt.md)). Failed imports or activation remain diagnosable and retryable without rolling back unrelated plugins. Self-reload closes the old stream and opens a new one; its full snapshot repairs missed graph changes. Boot, graph updates and rebuilt frames share the same queue, so a code replacement cannot overlap initial module arrival.
## Package ownership
@@ -108,7 +108,7 @@ One governance implementation runs on both sides of the wire; the browser-specif
Costs accepted: the vendored Loader carries idle machinery in the browser (EntryTree persistence is a no-op, groups/isolation unused); every plugin edit in dev pays a bundle rebuild plus fiber remount; graph `inject` rows guide factory arrival but service availability remains the activation authority, so a mismatch appears at the boot audit; the static UI libraries keep direct value exports; every bundle gains a source-map artifact; and external-script failures provide only coarse URL diagnostics instead of the HTTP status available to an explicit fetch. The Host retains bundle snapshots and lazy response plans for the current graph and one prior startup generation. Script and map bodies are cached after their first `GET`, so memory grows with bundle snapshots and requested response bodies. Each materialized response stays fixed at its URL; a prior-generation map first requested after a rebuild reads the current map file.
Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus SSE channel belongs to the hmr node half.
Roster: it lives in the web bundle's config tree (`packages/bundle/web-app/cordis.patch.yml`); `mountWebPlugins` and the `CLIENT_PACKAGES` constant are gone, and recomposing a deployment means swapping the yml/overlay. The graph composer lives in the `dsh-client-modules` node half, while the parser-preloaded client face bootstraps the browser module table. The webserver remains a plain route-registration plugin; `/api/*` binding, browser authentication, RPC envelopes, and exact Fetch routes belong to the Connection node half, while Remote dispatch belongs to API Gateway and the dev bundle watch plus the plugin-events Remote stream belongs to the hmr node half.
## Alternatives considered
@@ -46,7 +46,7 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
共享 tsdown 预设为每个插件入口与 chunk 产出 map,并把第一方源码路径重写成浏览器可识别的仓库形式 `/packages/<group>/<package>/src/...`。生产 Client 构建会消费 `lib/types`;预设把每份 tsc map 交给 Rolldown,并从原文件补齐 `sourcesContent`,使最终 map 回到 TypeScript/TSX,而不是停在编译后的 JavaScript。内联进 bundle 的其他 workspace 源码同样回到其 `packages/` 归属,依赖包路径保持原样。Combo 生成会移除每个局部调试指令、记录其生成行偏移、以原插件 map URL 解析每个自带 source,再产出 Indexed Source Map v3。插件有自带 map 时直接用于对应 section;没有时则生成 identity section,内嵌构建后 bundle,并在存在时把 packer 写入的 `sourceURL` 用作 source 名。绝对 combo map URL 会平行改写脚本资源列表中的每个 `client.js` 后缀,因此 `/plugins/??<package-a>/client.js,<package-b>/client.js&rev=<rev>` 指向 `/plugins/??<package-a>/client.js.map,<package-b>/client.js.map&rev=<rev>`。chunk 脚本同样指向自己的 map URL。只有在这些 map URL 收到 `GET` 后,source map 文件才会被读取和组合;`HEAD` 不会物化脚本或 map body。Vite 壳同样产出 sourcemap,使壳代码与经外部加载的插件都能从 stack 和性能 profile 回到 TypeScript/TSX。
图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的 SSE 快照不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。
图为 HMR 保留每个 row 带 revision 的单资源 combo URL,并为每个启动 combo 请求增加带 revision 的描述;多条描述可以使用同一调度阶段。首次发布与 `rebuilt(id)` 使用相同的入口 mtime、ctime 和大小哈希;产物内容不参与求哈希。ctime 用于区分保留 mtime 和大小的重写。Host 重启时若产物未变,每个 row 的 revision 都保持不变,因此重连后的流 baseline不会触发浏览器插件替换。共享预设会在每个包输出写完后标记入口;因此只重建 chunk 也会推进 owner revision,无需 Host 扫描 sibling。启动 combo revision 从有序 row revision 派生。脚本 body 在首次 `GET` 时组合;source map 文件在首次 map `GET` 时单独读取并组合。`HEAD` 不会物化任一 body。版本化脚本与 map 使用 immutable 缓存,无关图重组会保留相同 revision 下已经物化的 chunk 响应。Host 只提供精确生成的 URL;陈旧 revision 与未发布资源列表返回 404,不会别名到其他字节。外部脚本的 `error` 事件不给响应状态与正文,因此失败诊断只报告 URL;同源 Host 与构建期写入的 registration id 是身份边界,`load` 后的 factory 存在性检查负责拒绝未登记预期 id 的产物。
### 装载流程,端到端
@@ -76,13 +76,13 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的
modules 控制器只持有从启动清单创建的 Loader 条目。Host 的完整快照更新模块描述并对账这些条目;其他 Loader 贡献方保留自身所有权。新增模块通过单资源 URL 到达,因为重放启动 batch 可能重复注册现有 factory。移除使用 Loader 删除语义,随后等待已捕获 fiber 清理完毕,再移除未使用的模块记录。已声明及已观察到的传递依赖使共享模块保持存活。Factory revision 的跟踪独立于条目激活,因为下载或物化完成后仍可能没有创建条目。图更新会在任何消费者导入依赖前,使未归属受管条目的陈旧 factory 和失败的到达目标失效,并通知资源消费者;重建帧也会对账因导入失败而缺失的条目。
Host SSE 适配器转发现有图变化通知,并在连接时发送当前完整图。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
Host 的 `pluginEvents/follow` Remote 流转发现有图变化通知,每一代流先发送当前完整图;图行还携带各插件的同步配置([前端插件配置同步](2026-11-15-client-config-sync.zh.md))。图描述浏览器的目标条目,不代表 Host 清理完成:Host 生命周期顺序属于其 Loader,每个浏览器则等待自身被移除 fiber 的清理。图对账与代码重建共用一个页面队列。本地代际阻止过期下载挂载;不透明 revision 只比较相等。失败页面报告本地错误,并可重试同一张图而不改变 Host 启用状态。这保留了无关页面状态,也无需重启应用或引入第二套插件执行器。Electron 的独立安装流程不属于此机制。
### 热重载:一个驱动插件,自行监视的 bundle
热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与 SSE(Server-Sent Events)通道;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。
热重载是一项组合决策:web 组合包无条件挂载 `client-hmr` 行(一个常规的插件包),其 node 半带来 bundle 监视与经过鉴权的插件事件 Remote 流;没有重建 watcher 改写客户端 bundle 时链路保持空闲。不应暴露它的组合可以禁用该行。
重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在 `GET /plugins/events` 上广播 `rebuilt` 帧——这是一条系统级 SSE 通道,连接即发全量图,变更时发 `rebuilt` 帧,仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。
重建好的 bundle 怎么变成重载信号?hmr 的 node 半自己观察——没有构建器来通知它。模块 host 在读取每份启动快照前捕获入口 stat 基线,并通过 `ctx.clientModules.artifactBaseline(id)` 暴露它。HMR 自持的单个定时器把当前图的每个 row 与这份基线比较:未变化的 row 直接开始监视,不读取内容也不求哈希;基线捕获后的写入已经形成 stat 差异,只有该 row 会进入 `rebuilt(id)`。这既避免安装 watcher 时重复读取,也避开 `fs.watchFile` 以异步首次 stat 建立基线、可能静默吸收构造期重建的问题。监视集合的成员随 `onGraphChanged` 更新;消失的 row 撤下监视,轮询时缺失的入口则让对应 row 保持标脏状态,文件重现时即使 mtime 和大小与基线相同也重试发布。共享 tsdown 预设会在每个 sibling 输出写完后标记 `client.js`;入口 mtime、ctime 或大小变化、或 row 处于标脏状态时,`rebuilt(id)` 从这三个元数据值派生 revision。只有 revision 变化时,它才读取新的 bundle 快照。只修改 chunk 因此也会更换 revision;部分写入之后的完成标记还会提供一次更晚的 stat 变化以完成自愈。`rev` 变化时,node 半在经过鉴权的 `pluginEvents/follow` Remote 流上发布 `rebuilt` 帧;该流每一代先发全量图,之后发送 `graph` 与 `rebuilt` 增量,是仅供呈现的 wire,永不进会话日志。轮询是刻意选择:inotify 在 weka 网络挂载上不触发,构建侧监视器需要 `--poll` 也是同一原因;每个 row 每个间隔只需一次入口 stat,轮询间隔是一个经校验的配置字段(默认 500ms),dispose(资源释放)会清掉那一个定时器。重建产物的进程必须使用共享 Client tsdown 预设;`scripts/dev-web.ts` 仍作为 watch 构建入口保留,其包清单在启动时扫描 `packages/*/*/package.json` 按 dsh.client 发现,构建器与 host 之间没有通知协议。
浏览器侧的传输把代码替换交给负责图对账的同一个 modules 控制器:
@@ -96,7 +96,7 @@ Host SSE 适配器转发现有图变化通知,并在连接时发送当前完
Bootstrap 替换会在失效或卸载前被拒绝:模块系统保留其初始导出,重新挂载旧代码会重置消费者,却无法应用请求的 revision。页面会报告需要刷新,并保留 bootstrap fiber。所有非 bootstrap 插件都共享同一套替换语义;`immediately` 行的重载与 lazy 行分毫不差。依赖级联不花一行 client 代码:fiber 的激活纪元串接着它各服务提供方的 uid,因此替换 connection 等基础 provider 的 fiber 时,每个依赖方都会经 cordis 本身重新装载——行为正确,但代价较高。
重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧 SSE 通道并打开新通道;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。
重载会创建新的 fiber 和组件状态,不保留被替换插件内部的 React 状态。静态组装库与应用壳需要重建后的页面;Host 本身换成另一个 release 时,页面会暂停插件替换并询问是否刷新([Host release 变化提示](../feature/2026-10-14-host-release-change-refresh-prompt.zh.md))。导入或激活失败仍可诊断和重试,不会回滚无关插件。自重载关闭旧流并打开新流;其完整快照补齐遗漏的图变更。启动、图更新和重建帧共用同一队列,因此代码替换不会与初始模块到达重叠。
## 包归属
@@ -108,7 +108,7 @@ Wire 两侧运行同一份治理实现;浏览器特有层只包含一套模块
接受的代价:vendored Loader 在浏览器里背着闲置机件(EntryTree 持久化是 no-op,分组/隔离未用);开发期每次修改插件都要付一次 bundle 重建加 fiber 重挂;graph `inject` row 指导 factory 到达,但服务可用性仍是激活权威,因此不匹配会在启动审计时浮出;静态 UI 库保留直接实体导出;每个 bundle 多出一份 sourcemap 产物,外部 script 失败也只能给出粗粒度 URL 诊断,不能像显式 fetch 那样报告 HTTP 状态。Host 为当前图及上一代启动图保留 bundle 快照与惰性响应计划。脚本和 map body 在首次 `GET` 后缓存,因此内存随 bundle 快照和已请求的响应 body 增长。每份已物化响应在其 URL 下保持固定;若上一代 map 在重建后才首次被请求,则会读取当前 map 文件。
名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与 SSE 通道属于 HMR node 半。
名册位于 web 组合包的配置树(`packages/bundle/web-app/cordis.patch.yml`);`mountWebPlugins` 与 `CLIENT_PACKAGES` 常量已消失,重组一次部署等于替换 yml/overlay。Graph 组合器位于 `dsh-client-modules` node 半,由 parser 预载的 Client face 则自举浏览器模块表。Webserver 继续作为朴素路由注册插件;`/api/*` 绑定、浏览器认证、RPC envelope 与精确 Fetch 路由属于 Connection node 半,Remote 分发属于 API Gateway,开发期 bundle 监视与插件事件 Remote 流属于 HMR node 半。
## Alternatives considered
@@ -24,8 +24,8 @@
en: 428699f74f19e998
zh: 2e8fcdbc9616f70b
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery:
en: f3e6ba098433a70a
zh: 345b93f451d2768c
en: 814c344e891f7f91
zh: a024d5e30607968b
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/alternatives-considered:
en: 99ee505e82fa9c7c
zh: 448bc0e160424cbf
@@ -61,7 +61,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
### Watching and Client plugin delivery
- Worker `fs.watch` and `fs.watchFile` listeners run in the async context where the watcher was created, as Node delivers watch events from the watch handle, not in the context of the code whose write produced the event. HMR's configuration watcher therefore runs outside the writer's HMR transaction, and a configuration write made inside a transaction does not make the follow-up reload fail as a nested transaction.
- The browser half of `@deepseek-ai/dsh-client-hmr` reads `/plugins/events` through the page's `__DSH_TRANSPORT__.fetch` when a shell provides one (the Worker preview tunnel), otherwise through `EventSource`. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload.
- The browser half of `@deepseek-ai/dsh-client-hmr` follows the `pluginEvents/follow` Remote stream over the Remote carrier the page's Connection provides, including the Worker preview tunnel. The Client plugins of a bundle enabled in the Preview therefore mount without a page reload.
## Alternatives considered
@@ -61,7 +61,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
### 文件监听与 Client 插件下发
- Worker 的 `fs.watch` 和 `fs.watchFile` 监听器在创建 watcher 时的异步上下文里运行,与 Node 从 watch 句柄派发事件一致,而不是在写入方的上下文里运行。因此 HMR 的配置 watcher 在写入方的 HMR 事务之外运行,事务内的配置写入不会让随后的重载因嵌套事务而失败。
- `@deepseek-ai/dsh-client-hmr` 的浏览器部分在 shell 提供 `__DSH_TRANSPORT__.fetch` 时(Worker preview 隧道)经它读取 `/plugins/events`,否则经 `EventSource` 读取。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。
- `@deepseek-ai/dsh-client-hmr` 的浏览器部分经页面 Connection 提供的 Remote 载体(包括 Worker preview 隧道)跟随 `pluginEvents/follow` Remote 流。因此在 Preview 里启用 bundle 后,其 Client 插件无需刷新页面即可挂载。
## 考虑过的替代方案
@@ -0,0 +1,46 @@
# Bilingual-pair consistency record for 2026-11-15-client-config-sync.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-15-client-config-sync.md
/agent-note-browser-plugin-configuration-sync:
en: 92fb1b35ccd50f2b
zh: 732f665dd12d0feb
/agent-note-browser-plugin-configuration-sync/problem:
en: bad5854f1a21feb2
zh: df9f2c62aa7f1c8c
/agent-note-browser-plugin-configuration-sync/decision:
en: a15c7c13f167e5ac
zh: a15c7c13f167e5ac
/agent-note-browser-plugin-configuration-sync/decision/design-principles:
en: 1678ec9cbc83e49e
zh: 1548e5e08774de78
/agent-note-browser-plugin-configuration-sync/decision/plugin-authoring:
en: 201c029071cc3812
zh: 03a7245772a95b54
/agent-note-browser-plugin-configuration-sync/decision/ownership:
en: cb3e66c7d61b706b
zh: a255f85e9c411db9
/agent-note-browser-plugin-configuration-sync/decision/ordering:
en: 5de9319764101262
zh: 4a5c5c417cf36d8e
/agent-note-browser-plugin-configuration-sync/decision/push-order:
en: 5714f023a439e068
zh: 5d5ec5d5847fb2d4
/agent-note-browser-plugin-configuration-sync/decision/delivery:
en: 9b8e644702108ef6
zh: 0d4f551c6007e989
/agent-note-browser-plugin-configuration-sync/decision/push-channel:
en: 5596a32a26042882
zh: fbeae944656b39ac
/agent-note-browser-plugin-configuration-sync/decision/scope-existing-uses-the-mechanism-can-absorb:
en: 79b8c68583897e07
zh: 15a0f33fa494ec9a
/agent-note-browser-plugin-configuration-sync/verification:
en: b7ab56a86ef63b85
zh: b5fc8aae610659fc
/agent-note-browser-plugin-configuration-sync/alternatives-considered:
en: 15ae5cd610d7208c
zh: 5f25271e318dbfe1
/agent-note-browser-plugin-configuration-sync/consequences:
en: f85e3339246a9f84
zh: 11cbff9deeb78f88
@@ -0,0 +1,215 @@
# Agent Note: Browser plugin configuration sync
Status: implemented
English | [中文](2026-11-15-client-config-sync.zh.md)
## Problem
Host plugin configuration updates live: when only volatile fields change, the Loader commits the references in place and emits `loader/volatile-update` without remounting the plugin. The browser has no matching path:
| Symptom | Cause |
|---|---|
| A browser plugin's `apply(ctx, config)` always receives an empty config | The page Loader creates entries with `name` only ([entries.ts](../../../../packages/client/modules/src/client/entries.ts)), so the row's `config` in cordis.yml never reaches the browser |
| Packages that need Host configuration each work around it | Some write a page global through `webserver/index-inject`, which takes effect only at page load; others read runtime values through the `configForms` settings mirror |
| The plugin-graph push channel does not meet the rules | `/plugins/events` is an `auth: 'anonymous'` route; the browser has two readers, `EventSource` and `__DSH_TRANSPORT__.fetch`, the latter never reconnects; the frame sequence has no one-complete-snapshot-per-generation rule |
## Decision
### Design principles
| Principle | Content |
|---|---|
| One Config | A plugin has one configuration type, in the package's `src/types.ts`, shared by the Host and Client faces; the schema lives only on the Host face. The browser exports no `Config` and validates no configuration |
| Volatile only | The browser receives only the fields the Host schema declares volatile |
| Secrets removed | `role('secret')` positions inside volatile fields, including inside volatile objects, arrays, and dictionaries, are removed on the Host and never sent. The Host face of `client/modules` implements this itself, without depending on `@deepseek-ai/dsh-settings` |
| Plugins support live updates | A synced configuration change never remounts a browser plugin; the plugin reads references at operation time, or hands them to components as observable sources |
| Equal values do nothing | Every layer compares with deep equality; equal values push, write, and notify nothing, and a reconnect snapshot equal to the current values causes no refresh |
| What is not synced | Host-only ordinary fields, secrets, and per-browser preferences stay out of this path; values the page HTML pre-injects to avoid a first-paint flash, such as the theme, stay as they are |
### Plugin authoring
```ts ignore-check
// src/types.ts — shared by both faces; types only
import type { Volatile } from '@deepseek-ai/cordis'
/** Plugin configuration shared by the Host and Client faces. */
export interface Config {
/** Host-only ordinary field; never synced. */
cacheDir: string
/** Synced to the browser. */
interactiveByDefault: Volatile<boolean>
/** Synced as one value. */
office: Volatile<{ maxBytes: number }>
/** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */
apiKey?: Volatile<string>
}
```
```ts ignore-check
// src/index.ts — Host face; the only schema
export const Config: z<Config> = z.object({
cacheDir: z.string().default('.cache'),
interactiveByDefault: z.boolean().default(false).volatile(),
office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(),
apiKey: z.string().role('secret').volatile(),
})
```
```ts ignore-check
// src/client/index.ts — Client face; no Config export
import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types'
import type { Config } from '../types.ts'
export function apply(ctx: Context, config: SyncedConfig<Config>): void {
// Every synced field may read undefined; the plugin decides what an absent value means.
const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY)
ctx.slots.register({
name: 'demo.body',
inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }),
}, DemoBody)
}
```
```tsx ignore-check
// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault
export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace<DemoBodyInjected>) {
const interactive = useInteractiveByDefault(value => value)
// ...
}
```
Types exported by the types-only package `@deepseek-ai/dsh-client-config/types`, which plugins depend on instead of the bootstrap Client Modules package; Client Modules implements them:
```ts ignore-check
/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */
export interface SyncedConfigRef<T> extends Volatile<T>, ObservableSnapshot<VolatileSnapshot<T>> {}
/** The Volatile fields of the shared Config type. */
export type SyncedConfig<C> = {
readonly [K in keyof C as NonNullable<C[K]> extends Volatile<unknown> ? K : never]-?:
NonNullable<C[K]> extends Volatile<infer V> ? SyncedConfigRef<V | undefined> : never
}
```
`get` and `getSnapshot` return the same frozen snapshot: `get` matches how the Host reads a volatile reference, and `getSnapshot` with `subscribe` satisfy `ObservableSnapshot`, so the reference itself goes into `hooks` without renderer adaptation. The interface has no write operation; the implementing class stays private to Client Modules.
Components follow the [client rules](../../../../packages/client/AGENTS.md): the plugin injects field-level sources in a slot inject's `hooks` compartment, and the component reads them only through the renderer-bound `use<Name>`, never touching the source.
### Ownership
Runtime ownership stays in `client/modules`; the only new package is the types-only `@deepseek-ai/dsh-client-config` (empty `apply` on both faces). `client/modules` already follows Loader entries, composes the plugin graph, and creates entries in the browser; synced configuration is an input of an entry, so it owns this too:
| Face | Responsibility |
|---|---|
| Host (inside the `clientModules` service) | Listens to `loader/volatile-update` on each graph row's own plugin `ctx`; recomputes after the plugin fiber becomes ACTIVE (`internal/status`) or after entry reconciliation; reads the schema's top-level volatile field values from `fiber.effectiveConfig`, removes `role('secret')` positions by the schema, and compares the row's values with the last ones by deep equality, writing them into the graph row's `config` and republishing the graph only when they differ. A change of synced values alone rebuilds no combo artifact |
| Client (inside the entry controller) | Keeps the latest synced values of every package that has appeared in the graph; each plugin activation receives a new configuration object (an empty object while the row has no values), as each Host fiber activation resolves new references; on each graph it compares fields as JSON and writes the changes into the current activation's object |
| Client (`ctx.config` service) | Read-only: `resolveConfigByPackage<C>(packageName)` returns the object a package's current activation received, for reading another plugin's configuration; the object changes when the plugin is replaced, and the result is `undefined` while no activation runs |
Client constraints:
| Constraint | Content |
|---|---|
| Lazy creation | A field reference is created on first access and cached |
| Instance identity | One object per activation, living as long as that activation; code replacement and a re-added row each produce a new object holding the latest values |
| No `entry.update` | Synced configuration never takes the Loader update path, so it never triggers a remount, and the browser emits no `loader/volatile-update`; changes notify only through the field references' `subscribe` |
| Atomic publication | One graph update sets every changed field before notifying their subscribers, as the Host commits every reference before emitting its event |
| No value validation | The authoritative Host schema has already validated the values; the browser checks only that a row's `config` is an object when it parses the graph |
| Delivery | The entry controller registers a prepended `internal/config` listener on the page Loader that returns the synced object for managed entries that export no schema; the Loader's interpolation runs inside it and cannot copy the object. A Client face that exports its own `Config` schema keeps Cordis's ordinary configuration, and fails to activate if its row also carries synced values |
### Ordering
Host consistency comes from two facts: the schema and the code belong to one module, and activation resolves the raw configuration with that schema; code reloads and configuration reloads run serially through Host hot reload, and only an ACTIVE instance receives volatile changes in place. The Client aligns with the second:
| Situation | Host | Client |
|---|---|---|
| Configuration changes while the instance runs | Commits every reference in place, then notifies | Writes into the current activation's object in place, notifying after every field is written |
| Configuration changes while a replacement is queued and teardown has not begun | The instance is still ACTIVE and updates in place | Same |
| Configuration changes after teardown begins | A non-ACTIVE instance no longer updates in place; the new instance resolves the latest configuration | Teardown releases the old activation, whose object receives no further writes; the new activation starts with the latest values |
| The row is removed | The instance is destroyed and receives no configuration | Removal releases the activation; nothing is written while the row is absent from the graph |
| The Host-side plugin instance is not ACTIVE | Not applicable | Values follow the Host's configuration as the Host plugin's own effective Config does, including when activation fails; an instance that has not activated yet publishes the values its own schema resolves from its raw configuration |
A plugin instance that has not activated yet (a new install, an upgrade, a code reload) publishes the values its own schema resolves from its raw configuration, so the graph frame that announces new browser code already carries values of the matching Host schema. Only an incompatible schema change during development (a renamed or removed field) can briefly give old browser code values it does not expect, until the rebuilt bundle arrives.
### Push order
When a Host plugin updates its configuration and then pushes other data to the browser, the browser should receive the configuration first. The order is ensured only at the mechanism level, through the steps below; it is not guaranteed in practice. Each stream's source takes its own number of asynchronous steps between a Host event and the item reaching the Gateway write queue, so a stream with fewer steps can be written first even when no plugin adds a wait of its own. Plugins must not rely on this order:
| Step | Approach |
|---|---|
| Host enqueue | `clientModules` registers its `loader/volatile-update` listener on the plugin ctx with prepend, so it puts the new graph into every follower queue synchronously before the plugin's own listeners run |
| pluginEvents stream | `follow` yields increments from its own generator, with no delegated generator adding a step |
| Gateway write | Each connection has one write queue; each stream's items enter it when the source produces them and are written in queue order, without waiting for the previous write to complete; when the queued bytes exceed `streamOutboxBytes`, the whole connection pauses reading every source |
| Browser handling | WebSocket messages are handled in arrival order, and configuration writes complete synchronously while a graph frame is handled |
### Delivery
First-render values travel in the `__DSH_BOOT__` graph rows; later values travel in the plugin-events stream's `baseline` and `graph` frames, with no separate configuration frame. `@deepseek-ai/dsh-client-modules/types` exports the plugin graph's wire types. Only the owner receives configured values; every other Peer, such as a LiveShare viewer, receives in the boot graph and in every plugin-events frame the values each plugin's schema resolves from an empty Config, so the Host schema remains the only source of defaults and the owner's configured values stay on the Host; a row whose schema rejects an empty Config carries no values there. Remote access policies decide only whether a Peer may follow the graph.
### Push channel
`/plugins/events` becomes the authenticated Typert Remote stream `pluginEvents/follow`, which the browser consumes with `RemoteSnapshotStream`:
| Frame | Content | Browser handling |
|---|---|---|
| `baseline` | The complete plugin graph, including each row's synced configuration | Entry reconciliation |
| `graph` | The complete plugin graph after a structural or synced-configuration change | Entry reconciliation |
| `rebuilt` | `{ id, rev }`, one package's code rebuild | Entry code replacement |
| Item | Content |
|---|---|
| Authentication | Ordinary Remote gateway authentication and authorization; the anonymous `/plugins/events` route is removed, and the browser face opens the stream while Remote access allows `pluginEvents/follow` |
| Transport | Both the `EventSource` and the `__DSH_TRANSPORT__.fetch` readers are removed; shells such as liveshare and webworker connect through the Remote carrier Connection already provides |
| Reconnection | `RemoteStream` owns it; every generation starts with `baseline`, and the new snapshot covers anything missed while disconnected |
| Desktop | Shares the same Remote stream with Web |
| Ownership | The `client/hmr` Host face owns the `pluginEvents` Remote service, in the same package as the bundle stat poll, and declares no `ctx` type merge; `client/modules` is a zero-dependency bootstrap package and takes no typert or gateway dependency |
| Browser dependencies | The browser face `$mount`s its own generated `pluginEvents` namespace rather than through the `api-remotes` assembly, so `api-remotes` can be hot-replaced independently; the required dependencies are `modules`, `remote` (the gateway Client face, over Connection), and `remoteAccess` |
### Scope: existing uses the mechanism can absorb
This Note migrates no existing use; the [migration Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.md) owns the inventory and order. The mechanism can absorb page globals that deliver Host configuration through `webserver/index-inject`, plugins that read runtime values through `configForms`, and `Config` schemas declared only on a Client face that nothing can configure.
## Verification
The following hold and are covered by tests:
- A browser plugin's `apply` `config` holds the Host's current volatile values on first render; after a volatile field in `cordis.patch.yml` changes, the browser reference updates and subscribed components re-render, with neither the browser nor the Host plugin fiber remounted.
- `role('secret')` values in the positions the projection removes, the same as the settings redaction, appear neither in the first-render injection nor in any pushed frame; a non-owner Peer receives only schema defaults, never configured values.
- Host-only ordinary fields never appear in the browser.
- A configuration reload with unchanged values, and the reconnect baseline after a Host restart, emit no `loader/volatile-update` and notify no subscriber.
- No anonymous `/plugins/events` route exists; an unauthenticated request cannot obtain the plugin graph or configuration; after reconnection the browser state matches the Host.
- After code hot reload the new activation receives a new `SyncedConfig` object holding the current values, and the old activation receives no new values once its teardown begins.
- On the Host, the new graph frame enters the pluginEvents follower queues before the plugin's own `loader/volatile-update` listeners run; the order on the wire is not required.
- Tests: unit tests for both faces of `client/modules` (removal, comparison, lazy creation, reference stability, listener registration and removal); a real composition test that boots a profile through the Loader, changes a patch, and asserts browser-visible values; the `client-plugin-live` and `client-config-sync` Web end-to-end tests, including reconnection after a transport restart.
## Alternatives considered
| Rejected | Reason |
|---|---|
| A separate browser `ClientConfig` schema | Two schemas drift; the Host schema already carries volatile declarations and validation |
| Sending the whole configuration with secrets removed | Leaks ordinary fields such as Host paths and URLs to the browser |
| Applying changes to browser entries through `entry.update({ config })` | The browser has no schema, so the Loader cannot tell volatile fields and only remounts |
| Changing the vendored Loader to add a global volatile event | Requires a logged vendor modification; listening on each entry's own `ctx` suffices |
| Placing the channel in `client/modules` | The bootstrap package would depend on typert and the gateway |
| Mounting `pluginEvents` through `api-remotes` | A failed `api-remotes` replacement would cut the plugin update channel |
| Declaring "replacement requires a page reload" for Connection and the gateway | Adds a manifest field and a UI branch; a page reload after a failed replacement is accepted |
| A unified `useConfig` framework hook in the renderer | Adds a framework-level hook; manual `hooks` injection already serves components |
| Reusing the projection and removal functions of `@deepseek-ai/dsh-settings` | The settings architecture will be adjusted after this mechanism, so no dependency yet |
| References that are only `ObservableSnapshot` | Inconsistent with the Host's `get()` on volatile references |
| One page-lifetime configuration object per package | An old instance being torn down during replacement would still receive new configuration, unlike the Host |
| Changing the vendored Loader to emit a commit event for Host enqueue order | A prepended listener already suffices, with no vendor change |
| A separate push channel for configuration | Duplicates the plugin-graph channel's authentication, reconnection, and snapshot semantics |
| A separate `client/config` runtime package with a publicly writable configuration service | Any plugin could rewrite another plugin's configuration, and entries would have to wait for that service by package name |
| Plugins importing the types from `@deepseek-ai/dsh-client-modules/types` | Couples every configured plugin to the bootstrap module-system package and exposes the implementing class |
| Emitting `loader/volatile-update` in the browser too | The field references' `subscribe` suffices; the event requires reaching into Cordis's filter mechanism |
## Consequences
| Risk | Description |
|---|---|
| The channel depends on Connection | Plugin-graph sync depends on Connection and the gateway Client face. Hot-replacing them restarts this plugin and reopens the stream, reconciled by the new generation's baseline; if their new code fails to import or activate, the page receives no plugin updates until it reloads (accepted) |
| Listeners registered on other plugins' `ctx` | The Host face registers on tracked entries' `ctx`; `clientModules` must withdraw every listener when it unloads |
| Self-built references | Client references implement `Volatile` structurally without Cosmokit's internal write protocol, so `isVolatile` does not recognize them |
| Empty configuration objects | Browser plugins without synced fields also receive an empty read-only object as `config` |
| Push order not guaranteed | The configuration-first order holds only when every stream takes the same asynchronous steps from a Host event to the Gateway write queue; streams written in other ways, with or without waits of their own, may be written first |
| Every field may be absent | Each `SyncedConfig` field reads `V \| undefined`: secrets, unprojectable values, and Host values not yet matching the browser code are absent, so plugins handle the absent value at each read |
@@ -0,0 +1,215 @@
# Agent Note: 前端插件配置同步
Status: implemented
[English](2026-11-15-client-config-sync.md) | 中文
## Problem
Host 上的插件配置可以实时更新:Loader 在只有 volatile 字段变化时原地提交引用并发出 `loader/volatile-update`,不重新挂载插件。浏览器侧没有对应链路:
| 现象 | 原因 |
|---|---|
| 前端插件的 `apply(ctx, config)` 总是拿到空配置 | 页面 Loader 创建条目时只传 `name`([entries.ts](../../../../packages/client/modules/src/client/entries.ts)),cordis.yml 中该行的 `config` 不会到达浏览器 |
| 需要 Host 配置的包各自绕路 | 有的经 `webserver/index-inject` 写页面全局变量,只在页面加载时生效;有的借 `configForms` 设置镜像读取运行时值 |
| 插件图推送通道不合规 | `/plugins/events` 是 `auth: 'anonymous'` 路由;浏览器有 `EventSource` 和 `__DSH_TRANSPORT__.fetch` 两套读取实现,后者断开后不重连;帧序列没有「每代一份完整快照」约束 |
## Decision
### 设计原则
| 原则 | 内容 |
|---|---|
| 一套 Config | 插件只有一份配置类型,放在包的 `src/types.ts` 并由 Host 与 Client 两面共用;schema 只在 Host 面。浏览器不导出 `Config`,也不做配置校验 |
| 只同步 volatile | 浏览器只接收 Host schema 中声明为 volatile 的字段 |
| 剔除密钥 | volatile 字段内的 `role('secret')` 字段(包括 volatile 对象、数组、字典内部)在 Host 上剔除,不下发。该逻辑在 `client/modules` Host 面独立实现,不依赖 `@deepseek-ai/dsh-settings` |
| 插件自身支持热更新 | 同步配置的变化永远不重新挂载前端插件;插件在操作时读取引用,或把引用作为可订阅数据源交给组件 |
| 相等即无事 | 每层都按 deep equal 比较,值相等时不推送、不写入、不通知;重连收到的完整快照与当前值相等时不产生任何刷新 |
| 不同步的内容 | Host 专用普通字段、密钥、按浏览器区分的偏好不进入此链路;主题等在页面 HTML 预注入以避免首屏闪烁的值保持原状 |
### 插件写法
```ts ignore-check
// src/types.ts — shared by both faces; types only
import type { Volatile } from '@deepseek-ai/cordis'
/** Plugin configuration shared by the Host and Client faces. */
export interface Config {
/** Host-only ordinary field; never synced. */
cacheDir: string
/** Synced to the browser. */
interactiveByDefault: Volatile<boolean>
/** Synced as one value. */
office: Volatile<{ maxBytes: number }>
/** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */
apiKey?: Volatile<string>
}
```
```ts ignore-check
// src/index.ts — Host face; the only schema
export const Config: z<Config> = z.object({
cacheDir: z.string().default('.cache'),
interactiveByDefault: z.boolean().default(false).volatile(),
office: z.object({ maxBytes: z.natural().default(8 << 20) }).volatile(),
apiKey: z.string().role('secret').volatile(),
})
```
```ts ignore-check
// src/client/index.ts — Client face; no Config export
import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types'
import type { Config } from '../types.ts'
export function apply(ctx: Context, config: SyncedConfig<Config>): void {
// Every synced field may read undefined; the plugin decides what an absent value means.
const tooLarge = (bytes: number) => bytes > (config.office.get()?.maxBytes ?? Number.POSITIVE_INFINITY)
ctx.slots.register({
name: 'demo.body',
inject: (): DemoBodyInjected => ({ hooks: { interactiveByDefault: config.interactiveByDefault }, tooLarge }),
}, DemoBody)
}
```
```tsx ignore-check
// src/client/DemoBody.tsx — the renderer binds the injected source as useInteractiveByDefault
export function DemoBody({ useInteractiveByDefault, tooLarge }: InjectFace<DemoBodyInjected>) {
const interactive = useInteractiveByDefault(value => value)
// ...
}
```
只放类型的包 `@deepseek-ai/dsh-client-config/types` 导出的类型;插件依赖它而不依赖启动最早的 Client Modules 包,由 Client Modules 实现:
```ts ignore-check
/** One synced field: Host-aligned `get()`, and directly an observable source for an injected hook. */
export interface SyncedConfigRef<T> extends Volatile<T>, ObservableSnapshot<VolatileSnapshot<T>> {}
/** The Volatile fields of the shared Config type. */
export type SyncedConfig<C> = {
readonly [K in keyof C as NonNullable<C[K]> extends Volatile<unknown> ? K : never]-?:
NonNullable<C[K]> extends Volatile<infer V> ? SyncedConfigRef<V | undefined> : never
}
```
`get` 与 `getSnapshot` 返回同一个冻结快照:`get` 与 Host 的 volatile 引用写法一致,`getSnapshot` 与 `subscribe` 满足 `ObservableSnapshot`,引用本身即可放进 `hooks`,renderer 不需要额外适配。接口没有写操作;实现类只在 Client Modules 内部。
组件取值遵循 [client 规则](../../../../packages/client/AGENTS.md):插件在 slot inject 的 `hooks` 中手动注入 key 级数据源,组件只通过 renderer 绑定的 `use<Name>` 读取,不接触数据源本身。
### 归属
运行时归属仍在 `client/modules`;唯一新增的包是只放类型的 `@deepseek-ai/dsh-client-config`(两个面的 `apply` 都为空)。`client/modules` 本来就跟踪 Loader 条目、组合插件图并在浏览器创建条目,同步配置是条目的输入,由它一并负责:
| 面 | 职责 |
|---|---|
| Host(`clientModules` 服务内部) | 在每个图行插件自身的 `ctx` 上监听 `loader/volatile-update`;插件 fiber 进入 ACTIVE(`internal/status`)或条目对账后重算;从 `fiber.effectiveConfig` 读取 schema 顶层 volatile 字段的值,按 schema 剔除 `role('secret')` 位置,得到该行同步值;与上次值 deep equal 比较,不等才写入图行 `config` 并重新发布图。只变化同步值时不重建 combo 产物 |
| Client(条目控制器内部) | 为图中出现过的每个包保存最新同步值;插件每次激活都得到一个新的配置对象(行暂时没有值时是空对象),与 Host fiber 每次激活重新解析出新引用一致;收到图时按字段 JSON 比较,把变化写入当前激活的对象 |
| Client(`ctx.config` 服务) | 只读:`resolveConfigByPackage<C>(packageName)` 返回某个包当前激活收到的对象,供读取其他插件的配置;插件被替换后对象随之改变,没有运行中的激活时返回 `undefined` |
Client 面的约束:
| 约束 | 内容 |
|---|---|
| 懒生成 | 字段引用在首次访问时创建并缓存 |
| 实例身份 | 每次激活一个对象,与该激活同寿命;代码替换与行重新加入都产生新对象,持有最新值 |
| 不调用 `entry.update` | 同步配置不经过 Loader 的更新路径,不会触发重挂载,浏览器不发 `loader/volatile-update`;变化只经字段引用的 `subscribe` 通知 |
| 原子发布 | 一次图更新先设置所有变化字段,再通知它们的订阅者,与 Host 先提交全部引用再发事件一致 |
| 不校验值 | 值已由 Host 权威 schema 校验;浏览器只在图解析时校验行 `config` 是对象 |
| 交付方式 | 条目控制器在页面 Loader 上以 prepend 方式注册 `internal/config` 监听,为不导出 schema 的托管条目返回同步对象,Loader 插值在其内层运行,不会复制该对象。导出自身 `Config` schema 的前端面保持 Cordis 原有配置解析;这类前端面的行若同时带同步值,激活失败 |
### 时序
Host 的一致性来自两点:schema 与代码同属一个模块,激活时用该 schema 解析原始配置;代码重载与配置重载由 Host 热重载串行执行,只有 ACTIVE 的实例原地接收 volatile 变化。Client 对齐后一点:
| 情形 | Host | Client |
|---|---|---|
| 实例运行中,配置变化 | 原地提交全部引用后通知 | 原地写入当前激活的对象,全部写完后通知 |
| 替换已排队、拆除尚未开始时配置变化 | 实例仍 ACTIVE,原地更新 | 同左 |
| 拆除开始后配置变化 | 非 ACTIVE 实例不再原地更新,新实例解析最新配置 | 拆除开始时释放旧激活,旧对象不再写入;新激活以最新值开始 |
| 行被移除 | 实例被销毁,不再收到配置 | 移除时释放激活;行不在图中期间不写入 |
| Host 侧插件实例非 ACTIVE | 不适用 | 同步值与 Host 插件自身的 effective Config 一样跟随 Host 配置,激活失败时也是如此;尚未激活的实例发布其 schema 从原始配置解析出的值 |
尚未激活的插件实例(新安装、升级、代码热重载)发布用它自己的 schema 从原始配置解析出的值,因此宣布新前端代码的那一帧已带着对应 Host schema 的值。只有开发时不兼容地修改 schema(改名、删字段),才可能在重建的 bundle 到达前,让旧前端代码短暂收到它不认识的值。
### 推送顺序
Host 插件更新配置后再向浏览器推送其他数据时,浏览器应先收到配置。这一顺序只在机制上通过以下几处保证,实际上不保证:各流的源从 Host 事件到把数据项放入 gateway 写出队列所经过的异步步骤数各不相同,即使插件没有自行插入等待,步骤更少的流也可能先被写出。插件不得依赖这一顺序:
| 环节 | 做法 |
|---|---|
| Host 入队 | `clientModules` 在插件 ctx 上以 prepend 注册 `loader/volatile-update` 监听,在插件自己的监听之前同步把新图放入各 follower 队列 |
| pluginEvents 流 | `follow` 在自身生成器内产出增量,不经过额外委托的生成器多走一步 |
| gateway 写出 | 每条连接一个写出队列,各流的项在源产出时立即入队并按入队顺序写出,不再逐项等待上一次写入完成;排队字节超过 `streamOutboxBytes` 时整条连接暂停读取所有源 |
| 浏览器处理 | 每条 WebSocket 消息按到达顺序处理,配置写入在图帧处理时同步完成 |
### 下发
首屏值随 `__DSH_BOOT__` 的图行下发;之后随插件事件流的 `baseline` 与 `graph` 帧下发,不另设配置帧。插件图的线类型由 `@deepseek-ai/dsh-client-modules/types` 导出。只有 owner 收到实际配置的值;其他所有 Peer(例如 LiveShare 查看端)在启动图和每个插件事件帧中收到各插件 schema 对空 Config 解析出的值,因此 Host schema 仍是默认值的唯一来源,owner 实际配置的值留在 Host;schema 拒绝空 Config 的行在这类页面上不带值。Remote access 策略只决定 Peer 能否跟随插件图。
### 推送通道
`/plugins/events` 改为常规鉴权的 Typert Remote 流 `pluginEvents/follow`,浏览器用 `RemoteSnapshotStream` 消费:
| 帧 | 内容 | 浏览器处理 |
|---|---|---|
| `baseline` | 完整插件图(含各行同步配置) | 条目对账 |
| `graph` | 结构或同步配置变化后的完整插件图 | 条目对账 |
| `rebuilt` | `{ id, rev }`,单包代码重建 | 条目代码替换 |
| 项 | 内容 |
|---|---|
| 鉴权 | 走 Remote 网关的常规认证与授权,删除匿名 `/plugins/events` 路由;浏览器面在 Remote access 允许 `pluginEvents/follow` 时开流 |
| 传输 | 删除 `EventSource` 与 `__DSH_TRANSPORT__.fetch` 两套实现;liveshare、webworker 等外壳经 connection 已提供的 Remote 载体接入 |
| 重连 | 由 `RemoteStream` 负责;每代先收 `baseline`,断线期间的遗漏由新快照补齐 |
| 桌面端 | 与 Web 共用同一 Remote 流 |
| 归属 | Remote 服务 `pluginEvents` 由 `client/hmr` Host 面持有,与 bundle stat 轮询同包,不声明 `ctx` 类型合并;`client/modules` 是零依赖的 bootstrap 包,不引入 typert 与 gateway 依赖 |
| 浏览器依赖 | 浏览器面自行 `$mount` 本包生成的 `pluginEvents` 命名空间,不经 `api-remotes` 组装,因此 `api-remotes` 可以独立热替换;必需依赖为 `modules`、`remote`(gateway Client 面,其下为 connection)与 `remoteAccess` |
### 能力边界:可收编的现有用法
本 Note 不迁移现有用法;[迁移 Note](../../proposed/architecture/2026-11-15-client-config-sync-migration.zh.md) 负责盘点与顺序。本机制具备收编以下用法的能力:经 `webserver/index-inject` 下发 Host 配置的页面全局变量、以 `configForms` 读取运行时值的插件、只在前端声明而无法配置的 `Config`。
## Verification
以下行为成立并由测试覆盖:
- 前端插件 `apply` 的 `config` 参数首屏即为 Host 当前 volatile 值;修改 `cordis.patch.yml` 的 volatile 字段后,浏览器中引用值更新、订阅组件重新渲染,前端与 Host 插件 fiber 都不重挂载。
- 投影剔除的 `role('secret')` 位置(与 settings 的剔除范围相同)不出现在首屏注入和任一推送帧中;非 owner 的 Peer 只收到 schema 默认值,收不到实际配置的值。
- Host 专用普通字段不出现在浏览器。
- 值不变的配置重载、Host 重启后的重连 baseline 都不产生 `loader/volatile-update`,也不通知订阅者。
- `/plugins/events` 匿名路由不存在;未认证请求无法获取插件图或配置;断线重连后浏览器状态与 Host 一致。
- 代码热重载后新激活拿到持有当前值的新 `SyncedConfig` 对象,旧激活在拆除开始后不再收到新值。
- Host 上,新图帧在插件自己的 `loader/volatile-update` 监听执行之前进入 pluginEvents 各 follower 队列;不要求线上的先后顺序。
- 测试:`client/modules` 两面单元测试(剔除、比较、懒生成、引用稳定、监听注册与卸载);真实组合测试经 Loader 启动 profile、修改 patch 并断言浏览器可见值;`client-plugin-live` 与 `client-config-sync` 两个 Web 端到端测试,包括传输重启后的重连。
## Alternatives considered
| Rejected | 理由 |
|---|---|
| 另立一份前端 `ClientConfig` schema | 两份 schema 会漂移;volatile 声明与校验已由 Host schema 承担 |
| 整份配置去掉密钥后下发 | 会把 Host 路径、URL 等普通字段泄漏到浏览器 |
| 前端条目经 `entry.update({ config })` 应用变化 | 前端无 schema,Loader 无法判断 volatile,只会重挂载 |
| 修改 vendored Loader 增加全局 volatile 事件 | 需登记 vendor 本地修改;在条目自身 `ctx` 上监听即可满足 |
| 通道放进 `client/modules` | bootstrap 包会因此依赖 typert 与 gateway |
| 经 `api-remotes` 挂载 `pluginEvents` | `api-remotes` 的替换失败会切断插件更新通道 |
| 为 connection 与 gateway 增加「替换需刷新页面」声明 | 新增 manifest 字段与界面分支;接受替换失败时刷新页面 |
| renderer 提供统一的 `useConfig` 框架 hook | 新增框架级 hook;手动注入 `hooks` 已满足组件取值 |
| 复用 `@deepseek-ai/dsh-settings` 的投影与剔除函数 | settings 架构尚待在本机制之后统一调整,先不建立依赖 |
| 引用只保留 `ObservableSnapshot` | 与 Host volatile 引用的 `get()` 写法不一致 |
| 每个包一个页面级配置对象 | 替换期间正在退出的旧实例仍会收到新配置,与 Host 不一致 |
| 修改 vendored Loader 发出提交事件以保证 Host 入队顺序 | prepend 监听已能满足,不需要 vendor 改动 |
| 另开一条配置专用推送通道 | 与插件图通道重复鉴权、重连与快照语义 |
| 独立 `client/config` 运行时包提供公开写入的配置服务 | 任何插件都能改写别的插件的配置;条目还需按包名等待该服务 |
| 插件从 `@deepseek-ai/dsh-client-modules/types` 导入类型 | 让每个使用配置的插件都依赖启动最早的模块系统包,并暴露实现类 |
| 浏览器也发 `loader/volatile-update` | 字段引用的 `subscribe` 已足够,事件需要深入 Cordis 的过滤机制 |
## Consequences
| 风险 | 说明 |
|---|---|
| 通道依赖 connection | 插件图同步依赖 connection 与 gateway Client 面。热替换它们会连带重启本插件并重开流,由新一代 baseline 对账;若其新代码导入或激活失败,页面在刷新前收不到插件更新(已接受) |
| 在他人 `ctx` 上注册监听 | Host 面在被跟踪条目的 `ctx` 上注册,`clientModules` 卸载时必须撤销全部监听 |
| 自建引用 | Client 面引用是自建的 `Volatile` 结构实现,不使用 cosmokit 内部写入协议,`isVolatile` 不识别它们 |
| 空配置对象 | 没有同步字段的前端插件也收到一个空的只读对象作为 `config` |
| 推送顺序不保证 | 配置先到只在各流从 Host 事件到 gateway 写出队列经过相同异步步骤时成立;其他写法的流,无论是否自行等待,都可能先被写出 |
| 每个字段都可能缺值 | `SyncedConfig` 的每个字段读到 `V \| undefined`:密钥、无法投影的值、尚未与浏览器代码对应的 Host 值都会缺失,插件需在每次读取时处理缺值 |
@@ -18,8 +18,8 @@
en: e7cae8876e688f92
zh: 1d326330c34d128d
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/wire:
en: f15c4106f228f5f6
zh: ab80cf4ce62ae84c
en: 387deee727dfc538
zh: 1cae30f007f842d0
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/decision/page-side:
en: c0610c8f5a0882f3
zh: d309cbc53183ec6e
@@ -30,5 +30,5 @@
en: abb9d7ab9ef1df15
zh: 1704732daf5f2886
/agent-note-prompt-to-reload-when-the-host-release-changes-instead-of-hot-replacing-across-releases/consequences:
en: 815b41dc4f9ffcee
zh: b57388264cc459c7
en: a21bf34ac3983fbb
zh: c6278ef441587a48
@@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease }
```
- [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) computes the release once at construction and `compose()` writes it into every graph; `release` stays outside `graph.rev`. There is no new config field and the composition is unchanged.
- `__DSH_BOOT__` and every SSE `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that SSE connection, so it inherits that frame's release.
- `__DSH_BOOT__` and every plugin-events `baseline` and `graph` frame carry the field, so one graph frame carries both the Host release and its complete module graph; the client-hmr Host half is unchanged. A rebuilt frame comes from the same Host process as the graph frame before it on that stream generation, so it inherits that frame's release.
- `parseBootManifest` accepts an absent `release`, rejects a non-string `version` or `commit`, and drops members outside the identity, so equality compares only those two fields. `readRelease` reads only the `release` member of a received graph, so a page compares releases before it validates anything else; a release it cannot read counts as absent. Older pages that do not know the field ignore it.
### Page side
@@ -136,8 +136,7 @@ Order of operations:
- While the Host serves another release, plugin updates, including enabling or disabling a plugin on the Host, reach the page only after a reload.
- When a Host returns to the page's release, only modules whose revisions differ are replaced. Revisions come from artifact metadata, so a rebuild of identical code still replaces the rebuilt modules once, without a prompt.
- A composition without the dialog registered still pauses updates from another release and logs the warning; the user sees no prompt.
- The API connection and SSE are independent channels, so an old page can show a protocol error before the dialog appears.
- If a restarting Host answers `/plugins/events` with a non-200 status before registering the route, the browser closes that SSE stream for good, and the page cannot detect a release change until it reloads.
- After a terminal plugin-events stream failure the page cannot detect a release change until it reloads.
- A source launch without dev-web has no commit, so development detection falls back to version changes.
- Each tab prompts and remembers independently.
- Unit tests pin the gate through `ClientEntries` (same-release replacement, another release applying nothing, the return to the boot release replacing only changed modules, dismissal, absent releases), the manifest parser, the Host-published release, the shared preset's Node-half defines, and the dialog's rendering and callbacks.
@@ -60,7 +60,7 @@ BootManifest { ...; release?: WebBootRelease }
```
- [ClientModuleRegistry](../../../../packages/client/modules/src/index.ts) 在构造时计算一次 release,由 `compose()` 写入每个 graph;`release` 不计入 `graph.rev`。不新增配置项,组合配置不变。
- `__DSH_BOOT__` 和每个 SSE `graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一条 SSE 连接上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。
- `__DSH_BOOT__` 和插件事件流的每个 `baseline`、`graph` 帧都带这个字段,所以一个 graph 帧同时携带 Host 的 release 和完整模块图;client-hmr 的 Host 半侧不变。rebuilt 帧与同一代流上前一个 graph 帧来自同一个 Host 进程,因此沿用那一帧的 release。
- `parseBootManifest` 允许 `release` 缺省,拒绝非字符串的 `version` 或 `commit`,并丢弃身份以外的成员,因此相等判断只看这两个字段。`readRelease` 只读取收到的 graph 的 `release` 成员,所以页面先比较 release,再校验其余内容;读不出的 release 视为缺省。不认识该字段的旧页面会忽略它。
### 页面侧
@@ -136,8 +136,7 @@ class ClientEntries {
- Host 提供其他 release 期间,插件更新(包括在 Host 上启用或停用插件)要等刷新后才会到达页面。
- Host 回到页面的 release 时,只替换 revision 不同的模块。revision 取自产物元数据,所以即使重新构建出的代码完全相同,也会把重建过的模块替换一次,不弹框。
- 组合里没有注册确认框时,仍会暂停来自其他 release 的更新并记录警告,用户看不到提示。
- API 连接和 SSE 是两条独立通道,旧页面可能在确认框出现之前就已显示协议错误。
- 重启中的 Host 若在注册路由前对 `/plugins/events` 返回非 200 状态,浏览器会永久关闭这条 SSE,页面在刷新前检测不到 release 变化。
- 插件事件流以终止性错误结束后,页面在刷新前检测不到 release 变化。
- 不经 dev-web 的源码启动没有 commit,开发期只能检测到版本号变化。
- 每个标签页各自提示、各自记录。
- 单元测试通过 `ClientEntries` 固定 gate 的行为(同一 release 的替换、其他 release 不应用任何内容、回到启动 release 只替换变化了的模块、撤回、缺失 release),并覆盖 manifest 解析、Host 发布的 release、共享预设给 Node 半侧的 define,以及确认框的渲染与回调。
@@ -0,0 +1,34 @@
# Bilingual-pair consistency record for 2026-11-15-client-config-sync-migration.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync:
en: 5f71cf603f0c5013
zh: 3976607b283e68dc
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/problem:
en: 38add9dc3b90ad7e
zh: 867e351401f537bc
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal:
en: 986dd8097aac4d3d
zh: 986dd8097aac4d3d
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/inventory:
en: 08dae763d773f24a
zh: 15b4bd80b4973dff
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/migration-rules:
en: 72202ccc050d7e35
zh: a809ee548e005fcb
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/order:
en: 8b8ded15f43056c0
zh: 3ea6067ed0c3310c
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/proposal/open-questions:
en: 103a6b7dca054eb4
zh: 55b0881eca3e08ac
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/alternatives-considered:
en: a00b894cbcff0c34
zh: 7f2a83f36df109ec
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/acceptance-criteria:
en: 15597a6f656e7268
zh: f17a1cfcbef0fcbd
/agent-note-migrate-existing-browser-configuration-reads-to-configuration-sync/risks:
en: 8f5e523d526b2026
zh: 34a61d7c19df8650
@@ -0,0 +1,66 @@
# Agent Note: Migrate existing browser configuration reads to configuration sync
Status: proposed
English | [中文](2026-11-15-client-config-sync-migration.zh.md)
## Problem
Before [browser plugin configuration sync](../../implemented/architecture/2026-11-15-client-config-sync.md), every package whose browser face needs Host configuration implemented its own read. These reads take effect only at page load, duplicate injection code, or use the settings editing channel as a runtime read channel. This Note inventories them and plans their migration; nothing runs before the architecture lands.
## Proposal
### Inventory
| Category | Use | Packages |
|---|---|---|
| A. Page globals carry Host configuration | `webserver/index-inject` writes `window.__DSH_*__`, read once when the browser loads | `shortcuts`, `ui-sidebar-documentpreview`, `ui-account-notifications`, `ui-settings-models` (onboarding), `ui-settings-account` (contact details), `connection` (recovery parameters) |
| B. Runtime values read through `configForms` | The browser subscribes to accepted values of its own or another entry through the settings mirror | `ui-chat`, `ui-conversation`, `locale`, `ui-theme`, `ui-settings-account`, `ui-settings-general`, `ui-agent-preset`, experimental `timeline`, `client-ui-cot-translation`, `client-ui-forge`, `cua` |
| C. `Config` declared only on the Client face | The browser exports a schema, but the entry never receives configuration | Done in the architecture PR: `ui-context-menu` `resolutionTimeoutMs` and `ui-conversation` `maxConcurrentFileUploads` are top-level volatile fields of their Host schemas, and the Client schemas are removed |
| D. First-paint pre-injection | The page HTML pre-injects values to avoid a first-paint flash | `ui-theme` palette and font sizes |
| E. Settings editing | Settings pages edit inherited values, overrides, revisions, and writability | every `ui-settings-*` card |
### Migration rules
| Category | Handling |
|---|---|
| A | Make the fields volatile and move the `Config` type to `src/types.ts`; the browser reads `SyncedConfig`; remove the matching `index-inject` row and global. Confirm per field that its meaning can become "changes at runtime"; `connection` needs its recovery parameters before Connection itself activates and is assessed separately |
| B | Plugins reading their own entry read `SyncedConfig`; `configForms` keeps only writes and settings presentation. Reads of another entry's values (for example `ui-agent-preset` reading `ui-settings`) can use the read-only `ctx.config.resolveConfigByPackage(packageName)` |
| C | Remove the browser schema and `Config` export, move the type to `src/types.ts`, and declare a volatile schema on the Host face |
| D | Unchanged; the runtime part can be migrated separately |
| E | Outside this migration; adjusting the settings package and `configForms` is discussed separately once the configuration sync architecture is stable |
### Order
1. The architecture Note is implemented and merged.
2. Category C (no behavior dependency; exercises the mechanism).
3. Category A, one package at a time.
4. Category B, own reads first, then cross-plugin reads.
5. A separate Note for the overall adjustment of settings and `configForms`.
### Open questions
- Which fields each package makes volatile.
- Whether cross-plugin reads move to types inferred per package name through declaration merging.
- The first-render timing of `connection` recovery parameters and bootstrap rows.
## Alternatives considered
| Rejected | Reason |
|---|---|
| Migrating in the architecture PR | Widens the review and mixes mechanism questions with per-package semantics |
| Keeping page globals as a long-term parallel channel | Keeps two configuration sources and duplicated injection code |
## Acceptance criteria
- Category A and C packages no longer export a browser `Config` schema or read Host configuration globals.
- Category B plugins that read their own configuration no longer rely on `configForms` for runtime reads.
- After migration, a Host change to the matching volatile field takes effect without a page reload.
## Risks
| Risk | Description |
|---|---|
| Changed meaning | Values that took effect only at load become runtime-changeable, and plugins must support live updates |
| Pinned configuration | Making a field volatile brings it into the settings form's profile row, subject to the pinning rules in [profile-owned live configuration](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.md) |
| First-render timing | `connection` needs its recovery parameters before it activates, earlier than synced configuration can take part |
@@ -0,0 +1,66 @@
# Agent Note: 现有前端配置读取迁移到配置同步
Status: proposed
[English](2026-11-15-client-config-sync-migration.md) | 中文
## Problem
[前端插件配置同步](../../implemented/architecture/2026-11-15-client-config-sync.zh.md)落地前,浏览器需要 Host 配置的包各自实现了读取方式。这些方式只在页面加载时生效、复制注入代码,或把设置编辑通道当成运行时读取通道。本 Note 盘点这些用法并规划收编;架构落地前不执行。
## Proposal
### 盘点
| 类别 | 用法 | 包 |
|---|---|---|
| A. 页面全局变量下发 Host 配置 | `webserver/index-inject` 写 `window.__DSH_*__`,前端加载时读一次 | `shortcuts`、`ui-sidebar-documentpreview`、`ui-account-notifications`、`ui-settings-models`(引导)、`ui-settings-account`(联系方式)、`connection`(恢复参数) |
| B. 以 `configForms` 读取运行时值 | 前端经设置镜像订阅自身或他人条目的已接受值 | `ui-chat`、`ui-conversation`、`locale`、`ui-theme`、`ui-settings-account`、`ui-settings-general`、`ui-agent-preset`、实验包 `timeline`、`client-ui-cot-translation`、`client-ui-forge`、`cua` |
| C. 只在前端声明的 `Config` | 前端导出 schema,但条目从不收到配置 | 已在架构 PR 中完成:`ui-context-menu` 的 `resolutionTimeoutMs` 与 `ui-conversation` 的 `maxConcurrentFileUploads` 已改为 Host 顶层 volatile 字段,前端 schema 已删除 |
| D. 首屏预注入 | 页面 HTML 预注入以避免首屏闪烁 | `ui-theme` 调色板与字号 |
| E. 设置编辑 | 设置页编辑继承值、覆盖值、修订号、可写性 | 各 `ui-settings-*` 卡片 |
### 收编规则
| 类别 | 处理 |
|---|---|
| A | 字段改为 volatile,`Config` 类型移入 `src/types.ts`;前端改读 `SyncedConfig`;删除对应 `index-inject` 与全局变量。需逐字段确认语义可以变为「运行时可变」;`connection` 恢复参数在 connection 自身激活前就需要,须单独评估 |
| B | 读取自身条目的插件改读 `SyncedConfig`;`configForms` 只保留写入与设置页呈现。读取他人条目的值(例如 `ui-agent-preset` 读 `ui-settings`)可改用只读的 `ctx.config.resolveConfigByPackage(packageName)` |
| C | 前端删除 schema 与 `Config` 导出,类型移入 `src/types.ts`,Host 面声明 volatile schema |
| D | 保持不变;运行时变化部分可另行收编 |
| E | 不在本迁移范围;settings 包与 `configForms` 的调整在配置同步架构稳定后另行讨论 |
### 顺序
1. 架构 Note 实现完成并合入。
2. 类别 C(无行为依赖,验证机制)。
3. 类别 A,逐包进行。
4. 类别 B,先自身读取、后跨插件读取。
5. settings 与 `configForms` 的整体调整另起 Note。
### 未决
- 每个包选择哪些字段改为 volatile。
- 跨插件读取是否升级为按包名声明合并推导类型。
- `connection` 恢复参数与 bootstrap 行的首屏时序。
## Alternatives considered
| Rejected | 理由 |
|---|---|
| 与架构同一 PR 迁移 | 扩大评审面,机制问题与逐包语义问题混在一起 |
| 保留页面全局变量作为长期并行通道 | 维持两套配置来源与重复注入代码 |
## Acceptance criteria
- 类别 A、C 的包不再导出前端 `Config` schema 或读取 Host 配置全局变量。
- 类别 B 中读取自身配置的插件不再依赖 `configForms` 做运行时读取。
- 迁移后 Host 修改对应 volatile 字段无需刷新页面即生效。
## Risks
| 风险 | 说明 |
|---|---|
| 语义变化 | 原本只在加载时生效的值变为运行时可变,插件需支持热更新 |
| 配置钉住 | 字段改为 volatile 会使设置表单把它纳入 profile 行,受[实时配置](../../implemented/architecture/2026-09-19-profile-owned-live-configuration.zh.md)中的钉住规则影响 |
| 首屏时序 | `connection` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 |
-6
View File
@@ -191,11 +191,6 @@ class ResizeObserverStub {
unobserve(): void {}
}
class EventSourceStub {
addEventListener(): void {}
close(): void {}
}
const win = window as FixtureWindow
let unmount: (() => Promise<void>) | undefined
let mountedRemote: RemoteMock | undefined
@@ -244,7 +239,6 @@ export function installAssembledBootEnv(): void {
Object.defineProperty(navigator, 'language', { value: 'en-US', configurable: true })
document.title = 'DeepSeek Harness'
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
vi.stubGlobal('EventSource', EventSourceStub)
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
setTimeout(() => { callback(0) }, 0) as unknown as number)
vi.stubGlobal('cancelAnimationFrame', (id: number) => { clearTimeout(id) })
+106
View File
@@ -0,0 +1,106 @@
/** Real profile, Remote, and page Loader: a browser plugin receives its Host face's volatile Config and follows live edits. */
import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { FiberState } from '@deepseek-ai/cordis'
import { chromium } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-synced-config', import.meta.url))
const SCHEMASTERY = fileURLToPath(new URL('../../../vendor/schemastery', import.meta.url))
const PACKAGE = '@fixture/synced-config'
const ROW = 'fixture-synced-config'
/** What the fixture's Client face records from its synced Config object. */
interface Observation {
keys: string[]
greeting: string
account: { label: string }
}
/**
* Parse the fixture's recorded observation.
* @param text - JSON the fixture wrote to `data-synced-config`.
* @returns the observation.
*/
function parseObservation(text: string): Observation {
const value = JSON.parse(text) as Partial<Observation> | null
if (value === null || !Array.isArray(value.keys) || typeof value.greeting !== 'string' || typeof value.account?.label !== 'string') {
throw new Error(`fixture-synced-config recorded an unexpected observation: ${text}`)
}
return value as Observation
}
it('renders volatile Config without secrets or ordinary fields and updates it in place from a profile edit', async () => {
// An installed package carries its own dependencies: the copy links the Schemastery its Host face imports.
const installed = await mkdtemp(join(tmpdir(), 'dsh-client-config-sync-'))
onTestFinished(() => rm(installed, { recursive: true, force: true }))
await cp(FIXTURE, installed, { recursive: true })
await mkdir(join(installed, 'node_modules', '@deepseek-ai'), { recursive: true })
await symlink(SCHEMASTERY, join(installed, 'node_modules', '@deepseek-ai', 'schemastery'), 'junction')
const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: installed, enabled: true }] } })
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const entry = [...scaffold.ctx.loader.entries()].find(candidate => candidate.options.id === ROW)
expect(entry?.fiber?.state).toBe(FiberState.ACTIVE)
const hostFiber = entry!.fiber!
// The first-render HTML carries the projection: volatile values only, the secret subfield removed.
const html = await (await scaffold.hostFetch('/')).text()
expect(html).toContain('hello-r0')
expect(html).not.toContain('secret-token-r0')
expect(html).not.toContain('host-only-cache-r0')
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
const console = watchConsole(page)
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-config-sync'))
let navigations = 0
const dataset = async () => {
const { applies, config } = await page.evaluate(() => ({
applies: document.documentElement.dataset.syncedApplies,
config: document.documentElement.dataset.syncedConfig,
}))
return { applies, config: config === undefined ? undefined : parseObservation(config) }
}
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
page.on('framenavigated', () => { navigations++ })
await expect.poll(async () => (await dataset()).applies, { timeout: 20_000 }).toBe('1')
const bootRow = await page.evaluate((id) => {
const boot = Reflect.get(window, '__DSH_BOOT__') as { entries: { id: string; config?: unknown }[] }
return boot.entries.find(row => row.id === id)
}, PACKAGE)
expect(bootRow?.config).toEqual({ greeting: 'hello-r0', account: { label: 'primary' } })
expect(await dataset()).toEqual({
applies: '1',
config: { keys: ['account', 'greeting'], greeting: 'hello-r0', account: { label: 'primary' } },
})
// A profile edit that changes only volatile values reaches the running activation through its references.
const patchFile = join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml')
const previous = await readFile(patchFile, 'utf8').catch(() => '')
expect(previous.includes(ROW)).toBe(false)
await writeFile(patchFile, [
`- id: ${ROW}`,
' config:',
' cacheDir: host-only-cache-r0',
' greeting: hello-r1',
' account:',
' label: secondary',
' token: secret-token-r1',
'',
].join('\n'))
await expect.poll(async () => (await dataset()).config, { timeout: 30_000 }).toEqual({
keys: ['account', 'greeting'], greeting: 'hello-r1', account: { label: 'secondary' },
})
expect(scaffold.ctx.clientModules.graph().entries.find(row => row.id === PACKAGE)?.config)
.toEqual({ greeting: 'hello-r1', account: { label: 'secondary' } })
expect((await dataset()).applies).toBe('1')
expect(entry!.fiber).toBe(hostFiber)
expect(hostFiber.state).toBe(FiberState.ACTIVE)
expect(navigations).toBe(0)
expect(console.pageErrors).toEqual([])
}, 120_000)
+3 -11
View File
@@ -297,20 +297,12 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
expect(await target.locator('style[data-plugin="@fixture/live-client"]').count()).toBe(1)
}
const disconnected = other.waitForEvent('requestfailed', request => request.url().includes('/plugins/events'))
await otherContext.setOffline(true)
// Chromium offline emulation leaves established SSE sockets open. Cycling this
// fixture's transport plugin closes them without replacing the Host or profile.
// Restarting the Host transport ends every plugin-events stream; each page reopens it and reconciles from the
// new baseline, so a later change still reaches both pages.
const transport = [...scaffold.ctx.loader.entries()].find(entry => entry.options.name === '@deepseek-ai/dsh-client-hmr')!.fiber!
const reconnected = page.waitForResponse(response => response.url().includes('/plugins/events') && response.status() === 200)
await transport.restart()
await disconnected
await reconnected
await toggle()
await expect.poll(() => live(page).count()).toBe(0)
expect(await live(other).count()).toBe(1)
await otherContext.setOffline(false)
await expect.poll(() => live(other).count(), { timeout: 20_000 }).toBe(0)
for (const target of [page, other]) await expect.poll(() => live(target).count(), { timeout: 20_000 }).toBe(0)
expect(await draft.inputValue()).toBe('unfinished-draft')
expect(navigations).toBe(0)
expect(scaffold.ctx.loader.ctx.fiber.uid).toBe(host)
@@ -0,0 +1,29 @@
/** Client face of the synced-configuration fixture: exports no Config and records what its synced Config object shows. */
window.__ModuleLoader__.load({
id: '@fixture/synced-config',
factory() {
return {
apply(ctx, config) {
const data = document.documentElement.dataset
data.syncedApplies = String(Number(data.syncedApplies ?? 0) + 1)
// References are read at operation time; `Object.keys` lists the fields the Host sent.
const publish = () => {
data.syncedConfig = JSON.stringify({
keys: Object.keys(config).sort(),
greeting: config.greeting.get(),
account: config.account.get(),
})
}
publish()
let notifications = 0
const notified = () => {
notifications++
data.syncedNotifications = String(notifications)
publish()
}
ctx.effect(() => config.greeting.subscribe(notified))
ctx.effect(() => config.account.subscribe(notified))
},
}
},
})
@@ -0,0 +1,9 @@
- insert:
- id: fixture-synced-config
name: '@fixture/synced-config'
config:
cacheDir: host-only-cache-r0
greeting: hello-r0
account:
label: primary
token: secret-token-r0
@@ -0,0 +1,15 @@
/** Host face of the synced-configuration fixture: the only Config schema, with an ordinary field and two volatile fields. */
import z from '@deepseek-ai/schemastery'
/** Ordinary `cacheDir` stays on the Host; volatile `greeting` and `account` reach the browser without `account.token`. */
export const Config = z.object({
cacheDir: z.string().required(),
greeting: z.string().required().volatile(),
account: z.object({
label: z.string().required(),
token: z.string().role('secret').required(),
}).volatile(),
})
/** Nothing to mount on the Host. */
export function apply() {}
@@ -0,0 +1,22 @@
{
"name": "@fixture/synced-config",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "index.js",
"exports": {
".": "./index.js",
"./client": "./client.js"
},
"dependencies": {
"@deepseek-ai/schemastery": "*"
},
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
},
"client": {
"platform": "web"
}
}
}
+12 -10
View File
@@ -159,19 +159,21 @@ it.each([false, true])('keeps the same revision, Session and page across a serve
})
socket.on('framereceived', ({ payload }) => {
if (typeof payload !== 'string') return
const message = JSON.parse(payload) as { type?: string; streamId: string; value?: { type?: string }; error?: unknown }
const message = JSON.parse(payload) as {
type?: string
streamId: string
value?: { type?: string; graph?: typeof graphs[number] }
error?: unknown
}
if (message.type === 'error') streamErrors.push(message.error)
if (message.type === 'item' && message.value?.type === 'ready') readyFrames++
if (message.type === 'item' && endpoints.get(message.streamId) === 'session/follow'
&& message.value?.type === 'snapshot') sessionBaselines++
if (message.type !== 'item') return
const endpoint = endpoints.get(message.streamId)
if (message.value?.type === 'ready') readyFrames++
if (endpoint === 'session/follow' && message.value?.type === 'snapshot') sessionBaselines++
// Every plugin-events stream generation opens with a baseline graph; later graph changes arrive as `graph`.
if (endpoint === 'pluginEvents/follow' && message.value?.graph !== undefined) graphs.push(message.value.graph)
})
})
const network = await page.context().newCDPSession(page)
await network.send('Network.enable')
network.on('Network.eventSourceMessageReceived', (event) => {
const message = JSON.parse(event.data) as { type?: string; graph: typeof graphs[number] }
if (message.type === 'graph') graphs.push(message.graph)
})
onTestFailed(async () => {
await saveFailureShot(page, 'web-server-restart-' + scenarioId)
await writeFile(join(REPO_ROOT, '.artifacts', 'server-restart-' + scenarioId + '.json'), JSON.stringify({ errors, streamErrors, graphs, server: server.logs() }, null, 2))
+1
View File
@@ -129,6 +129,7 @@
"tests/plugin-install-github.e2e.ts",
"tests/plugin-install-silent-failure.e2e.ts",
"tests/client-plugin-live.e2e.ts",
"tests/client-config-sync.e2e.ts",
"tests/icon-skin.e2e.ts",
"tests/draft-initialization.e2e.ts",
"tests/settings-chrome.e2e.ts",
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: 15d626593d746219
zh: 332d2135597249b8
en: 4eb44ffc136cee25
zh: a34b8a156fc22955
+5
View File
@@ -312,6 +312,8 @@ flowchart LR
pkg_web_app["web-app"]
svc_webApp["ctx.webApp<br/>Served Web GUI"]
pkg_harness_dev_context["harness-dev-context"]
pkg_client_config["client-config"]
svc_config["ctx.config<br/>Browser synced configuration lookup"]
svc_clientModules["ctx.clientModules<br/>Client plugin graph host"]
pkg_workflow["workflow"]
svc_workflowEngine["ctx.workflowEngine<br/>Workflow script engine"]
@@ -352,10 +354,12 @@ flowchart LR
pkg_bash_local --> svc_shell
pkg_bash_sandbox --> svc_shell
pkg_browser_use --> svc_browserUse
pkg_client_config --> svc_config
pkg_client_connection --> svc_connection
pkg_client_connection --> svc_connection_authentication
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_modules --> svc_config
pkg_client_product_analytics --> svc_productAnalytics
pkg_client_ui_connector_account --> svc_connectorAccounts
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
@@ -784,6 +788,7 @@ flowchart LR
| `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; dual-face backends fill ui-workspace directory-flow slots from their browser halves (no wire advertisement). |
| `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. |
| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | The web-runtime row advertises one URL for its Web GUI: the configured publicUrl, otherwise the listener origin; DSH_WEB_URL, the startup URL, and harness-dev-context read the same value. |
| `ctx.config` | `service` | [`client-config`](../packages/client/config) | [`client-modules`](../packages/client/modules) | - | - | Types-only declaration; the client-modules plugin face provides the read-only lookup of each package's current synced Config. |
| `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | Composes the __DSH_BOOT__ entry graph from an incremental dsh.client scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. |
| `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | One engine per context, as in bash, with no named-provider registry; the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. |
| `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | Provider adapters dispatch authenticated deliveries; trusted plugins register independent process-local rules, and the runtime turns non-null results into ordinary Workspace-backed Sessions without delivery or completion state. |
+5
View File
@@ -314,6 +314,8 @@ flowchart LR
pkg_web_app["web-app"]
svc_webApp["ctx.webApp<br/>Served Web GUI"]
pkg_harness_dev_context["harness-dev-context"]
pkg_client_config["client-config"]
svc_config["ctx.config<br/>Browser synced configuration lookup"]
svc_clientModules["ctx.clientModules<br/>Client plugin graph host"]
pkg_workflow["workflow"]
svc_workflowEngine["ctx.workflowEngine<br/>Workflow script engine"]
@@ -354,10 +356,12 @@ flowchart LR
pkg_bash_local --> svc_shell
pkg_bash_sandbox --> svc_shell
pkg_browser_use --> svc_browserUse
pkg_client_config --> svc_config
pkg_client_connection --> svc_connection
pkg_client_connection --> svc_connection_authentication
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_modules --> svc_config
pkg_client_product_analytics --> svc_productAnalytics
pkg_client_ui_connector_account --> svc_connectorAccounts
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
@@ -786,6 +790,7 @@ flowchart LR
| `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | 带判别标记的交互能力:原生后端在 Host 显示设备上打开一个操作系统选择器,浏览后端为应用内浏览器提供列表与创建原语;双端后端通过其浏览器侧填充 ui-workspace 目录流程的 slot(不通过协议发布)。 |
| `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | 普通的 node:http 载体:具名路由注册表、索引转换 tap,以及静态 dist 回退;Web 传输插件注册自己的路由。 |
| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | web-runtime 行为其 Web GUI 公告一个 URL:配置了 publicUrl 时用它,否则用监听器 origin;DSH_WEB_URL、启动 URL 与 harness-dev-context 读取同一个值。 |
| `ctx.config` | `service` | [`client-config`](../packages/client/config) | [`client-modules`](../packages/client/modules) | - | - | 只有类型的声明;client-modules 插件面提供对各包当前同步 Config 的只读查询。 |
| `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | 通过增量 `dsh.client` 扫描组合 __DSH_BOOT__ 入口图,提供插件组合包,并通知重建/图变更订阅方。 |
| `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | 每个上下文使用一个引擎,与 bash 相同,且没有具名提供方注册表;通用工作流与固定 Ralph 消费方启动运行,其中的 agent() 调用通过 ctx.subagents 扇出。 |
| `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | 提供方适配器分派已认证交付;可信插件注册独立的进程本地规则,runtime 把非 null 结果转换为普通的 Workspace-backed Session,不保留交付或完成状态。 |
+9 -3
View File
@@ -222,7 +222,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-gateway`
- `inject`: `typert` · `remoteAccess`
- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts)
- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts)
```ts config-catalog
/** Gateway transport configuration. */
@@ -231,6 +231,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -539,8 +544,8 @@ export interface ConnectionRecoveryConfig {
## `@deepseek-ai/dsh-client-hmr`
- `inject`: `clientModules` · `webServer`
- `source`: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
- `inject`: `clientModules`
- `source`: [`packages/client/hmr/src/index.ts:26`](../packages/client/hmr/src/index.ts)
```ts config-catalog
/** Plugin config, validated by the same-named schemastery schema. */
@@ -5245,6 +5250,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
| `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) |
| `@deepseek-ai/dsh-client-config` | — | [`packages/client/config/src/index.ts`](../packages/client/config/src/index.ts) |
| `@deepseek-ai/dsh-client-file-upload` | `agents` · `attachments` · `commands` · `connection` | [`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts) |
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
+9 -3
View File
@@ -224,7 +224,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-gateway`
- `inject`: `typert` · `remoteAccess`
- `source`: [`packages/api/gateway/src/index.ts:157`](../packages/api/gateway/src/index.ts)
- `source`: [`packages/api/gateway/src/index.ts:158`](../packages/api/gateway/src/index.ts)
```ts config-catalog
/** Gateway transport configuration. */
@@ -233,6 +233,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -541,8 +546,8 @@ export interface ConnectionRecoveryConfig {
## `@deepseek-ai/dsh-client-hmr`
- `inject`: `clientModules` · `webServer`
- `source`: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
- `inject`: `clientModules`
- `source`: [`packages/client/hmr/src/index.ts:26`](../packages/client/hmr/src/index.ts)
```ts config-catalog
/** Plugin config, validated by the same-named schemastery schema. */
@@ -5247,6 +5252,7 @@ export interface Config {
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
| `@deepseek-ai/dsh-browser-use` | — | [`packages/browser-use/browser-use/src/index.ts`](../packages/browser-use/browser-use/src/index.ts) |
| `@deepseek-ai/dsh-client-config` | — | [`packages/client/config/src/index.ts`](../packages/client/config/src/index.ts) |
| `@deepseek-ai/dsh-client-file-upload` | `agents` · `attachments` · `commands` · `connection` | [`packages/client/file-upload/src/index.ts`](../packages/client/file-upload/src/index.ts) |
| `@deepseek-ai/dsh-client-locale` | — | [`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts) |
| `@deepseek-ai/dsh-client-modules` | `loader` | [`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts) |
+3 -3
View File
@@ -119,12 +119,12 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| --- | --- | --- |
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`timeline`](../packages/experimental/timeline) |
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager) |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
+3 -3
View File
@@ -121,12 +121,12 @@
| --- | --- | --- |
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`timeline`](../packages/experimental/timeline) |
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager) |
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
+2
View File
@@ -155,6 +155,7 @@ flowchart TD
pkg_web_app["web-app"]
end
subgraph group_client["packages/client"]
pkg_client_config["client-config"]
pkg_client_connection["client-connection"]
pkg_client_file_upload["client-file-upload"]
pkg_client_hmr["client-hmr"]
@@ -1627,6 +1628,7 @@ flowchart TD
| [`base`](../packages/bundle/base) | `bundle` | — |
| [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — |
| [`sdk-minimal`](../packages/bundle/sdk-minimal) | `bundle` | — |
| [`client-config`](../packages/client/config) | `client` | — |
| [`client-file-upload`](../packages/client/file-upload) | `client` | — |
| [`client-hmr`](../packages/client/hmr) | `client` | — |
| [`client-locale`](../packages/client/locale) | `client` | — |
+2
View File
@@ -157,6 +157,7 @@ flowchart TD
pkg_web_app["web-app"]
end
subgraph group_client["packages/client"]
pkg_client_config["client-config"]
pkg_client_connection["client-connection"]
pkg_client_file_upload["client-file-upload"]
pkg_client_hmr["client-hmr"]
@@ -1629,6 +1630,7 @@ flowchart TD
| [`base`](../packages/bundle/base) | `bundle` | — |
| [`sdk-app`](../packages/bundle/sdk-app) | `bundle` | — |
| [`sdk-minimal`](../packages/bundle/sdk-minimal) | `bundle` | — |
| [`client-config`](../packages/client/config) | `client` | — |
| [`client-file-upload`](../packages/client/file-upload) | `client` | — |
| [`client-hmr`](../packages/client/hmr) | `client` | — |
| [`client-locale`](../packages/client/locale) | `client` | — |
+37 -4
View File
@@ -35,6 +35,8 @@ interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
```
@@ -139,11 +141,19 @@ The web plugin table service: incremental `dsh.client` scan + wire composition +
```ts cordis-catalog
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -194,13 +204,36 @@ rebuilt(id: string): string | undefined
onRebuilt(listener: (id: string, rev: string) => void): () => void
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
onGraphChanged(listener: () => void): () => void
```
Types: [Principal](typert.md)
Source: [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)
<a id="ctxconfig--syncedconfigservice"></a>
### `ctx.config` — `SyncedConfigService`
Read-only access to other packages' synced Config; a plugin receives its own through `apply`.
```ts cordis-catalog
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it. Each
* activation receives a new object, so the result changes when the plugin is replaced. The caller states the
* package's shared Config type.
* @param packageName - package name of the graph row.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage<C>(packageName: string): SyncedConfig<C> | undefined
```
Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts)
<!-- END GENERATED cordis-surface -->
+37 -4
View File
@@ -35,6 +35,8 @@ interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
```
@@ -139,11 +141,19 @@ The web plugin table service: incremental `dsh.client` scan + wire composition +
```ts cordis-catalog
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -194,13 +204,36 @@ rebuilt(id: string): string | undefined
onRebuilt(listener: (id: string, rev: string) => void): () => void
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
onGraphChanged(listener: () => void): () => void
```
Types: [Principal](typert.zh.md)
Source: [`packages/client/modules/src/index.ts`](../../packages/client/modules/src/index.ts)
<a id="ctxconfig--syncedconfigservice"></a>
### `ctx.config` — `SyncedConfigService`
Read-only access to other packages' synced Config; a plugin receives its own through `apply`.
```ts cordis-catalog
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it. Each
* activation receives a new object, so the result changes when the plugin is replaced. The caller states the
* package's shared Config type.
* @param packageName - package name of the graph row.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage<C>(packageName: string): SyncedConfig<C> | undefined
```
Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts)
<!-- END GENERATED cordis-surface -->
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md
/:
en: fc0f253f60ad41b4
zh: 4b7f02f9260c672a
/plugin-events-stream-and-synced-browser-configuration:
en: 2cd6093e448761ba
zh: 66910abc17effed8
/plugin-events-stream-and-synced-browser-configuration/change:
en: 691f405846b33bbe
zh: b413c6be43ff2ee1
/plugin-events-stream-and-synced-browser-configuration/migration:
en: a8c0674e9b91d83c
zh: 557341db53da1025
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "`@deepseek-ai/dsh-client-hmr` removes `GET /plugins/events` and `EVENTS_ENDPOINT` for the authenticated `pluginEvents/follow` Remote stream, and browser plugins receive synced configuration in `apply`."
---
# Plugin events stream and synced browser configuration
English | [中文](guide.zh.md)
## Change
`@deepseek-ai/dsh-client-hmr` no longer registers the anonymous Server-Sent Events route `GET /plugins/events` and no longer exports `EVENTS_ENDPOINT`. Graph and rebuilt frames travel on the authenticated Typert Remote stream `pluginEvents/follow`: each stream generation opens with a `baseline` frame holding the full graph, followed by `graph` and `rebuilt` frames. Frame types come from `@deepseek-ai/dsh-client-hmr/types`. The browser face opens the stream over Connection and the API Gateway Client face while `remoteAccess` allows `pluginEvents/follow`; it no longer reads `window.__DSH_TRANSPORT__.fetch` or uses `EventSource`. A Peer whose Remote access does not allow `pluginEvents/follow`, such as a live-share viewer, no longer receives live graph or rebuilt updates.
Each graph row carries the plugin's [synced configuration](../../../../packages/client/modules/README.md#synced-plugin-configuration). A browser plugin whose Client face exports no `Config` schema receives a `SyncedConfig` object in `apply`, empty when its Host face declares no volatile fields, where it previously received `undefined`. A Client face that exports its own `Config` schema fails to activate when its graph row also carries synced values.
Affected: custom shells, scripts, and tests that read `/plugins/events` or import `EVENTS_ENDPOINT`; shells that supplied the plugin-events transport through `__DSH_TRANSPORT__.fetch`; deployments relying on viewer Peers following plugin changes; browser plugins that test their `apply` config for `undefined` or export a Client `Config` alongside volatile Host fields.
## Migration
1. Replace reads of `/plugins/events` and imports of `EVENTS_ENDPOINT` with a Remote client that mounts `@deepseek-ai/dsh-client-hmr/remote` and follows `pluginEvents.follow(signal)`; treat each `baseline` frame as a replacement of all earlier state, as [`src/client/index.ts`](../../../../packages/client/hmr/src/client/index.ts) does.
2. In a custom shell, provide the Remote carrier through Connection and the API Gateway Client face instead of a `__DSH_TRANSPORT__.fetch` handler for this endpoint.
3. Grant `pluginEvents/follow` in the Remote access policy of every Peer that must follow plugin changes; Peers without it reload the page to see them.
4. In browser plugins, stop treating an `undefined` `apply` config as "no configuration"; read fields through `SyncedConfig` from `@deepseek-ai/dsh-client-config/types`.
5. For a plugin with volatile Host fields, remove the Client face `Config` schema export and keep the only schema on the Host face, with the shared interface in `src/types.ts`.
6. Confirm: open the Web page, enable or disable a plugin, and check that the page updates without reload and that the browser sends no `/plugins/events` request.
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "`@deepseek-ai/dsh-client-hmr` 删除 `GET /plugins/events` 和 `EVENTS_ENDPOINT`,改用经过鉴权的 `pluginEvents/follow` Remote 流,浏览器插件在 `apply` 中接收同步配置。"
---
# 插件事件流与浏览器同步配置
[English](guide.md) | 中文
## 变更
`@deepseek-ai/dsh-client-hmr` 不再注册匿名 Server-Sent Events 路由 `GET /plugins/events`,也不再导出 `EVENTS_ENDPOINT`。图帧与重建帧改由经过鉴权的 Typert Remote 流 `pluginEvents/follow` 传递:每一代流先发一个包含完整图的 `baseline` 帧,之后发送 `graph` 与 `rebuilt` 帧。帧类型来自 `@deepseek-ai/dsh-client-hmr/types`。浏览器半侧在 `remoteAccess` 允许 `pluginEvents/follow` 时,经 Connection 与 API Gateway Client 半侧打开这条流;它不再读取 `window.__DSH_TRANSPORT__.fetch`,也不再使用 `EventSource`。Remote access 不允许 `pluginEvents/follow` 的 Peer(例如 live share 观看者)不再收到实时的图更新与重建更新。
图的每一行携带该插件的[同步配置](../../../../packages/client/modules/README.zh.md#synced-plugin-configuration)。Client 半侧未导出 `Config` schema 的浏览器插件在 `apply` 中接收一个 `SyncedConfig` 对象,Host 半侧未声明 volatile 字段时该对象为空,此前接收的是 `undefined`。Client 半侧导出自己 `Config` schema 的插件,若其图行同时携带同步值,则激活失败。
受影响者:读取 `/plugins/events` 或导入 `EVENTS_ENDPOINT` 的自定义 shell、脚本和测试;通过 `__DSH_TRANSPORT__.fetch` 提供插件事件传输的 shell;依赖观看者 Peer 跟随插件变更的部署;检查 `apply` 配置是否为 `undefined`,或在 Host volatile 字段之外还导出 Client `Config` 的浏览器插件。
## 迁移
1. 把对 `/plugins/events` 的读取和 `EVENTS_ENDPOINT` 的导入替换为挂载 `@deepseek-ai/dsh-client-hmr/remote` 并跟随 `pluginEvents.follow(signal)` 的 Remote 客户端;与 [`src/client/index.ts`](../../../../packages/client/hmr/src/client/index.ts) 一样,把每个 `baseline` 帧视为对之前全部状态的替换。
2. 在自定义 shell 中,经 Connection 与 API Gateway Client 半侧提供 Remote carrier,而不是为该端点提供 `__DSH_TRANSPORT__.fetch` 处理函数。
3. 在每个需要跟随插件变更的 Peer 的 Remote access 策略中授予 `pluginEvents/follow`;没有该权限的 Peer 需重新加载页面才能看到变更。
4. 在浏览器插件中,不再把 `undefined` 的 `apply` 配置当作“没有配置”;通过 `@deepseek-ai/dsh-client-config/types` 中的 `SyncedConfig` 读取字段。
5. 对带有 Host volatile 字段的插件,删除 Client 半侧的 `Config` schema 导出,只在 Host 半侧保留 schema,共享接口放在 `src/types.ts`。
6. 确认:打开 Web 页面,启用或禁用一个插件,检查页面无需重新加载即更新,且浏览器不再发出 `/plugins/events` 请求。
+2 -2
View File
@@ -15,8 +15,8 @@
en: d9859219cdb0f367
zh: 2a3cfa8cb786e327
/deepseek-ai-dsh-api-gateway/host-service-typertgatewayservice-ctx-key-typertgateway:
en: 6ee072ffebd2eb38
zh: 6a8723d13f443d51
en: 99788727be88f6db
zh: 750fd190bc1b8de0
/deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote:
en: 610e48ec8d772f85
zh: 627da164fc8297ba
+1 -1
View File
@@ -38,7 +38,7 @@ Resources are read from validated arguments: Typert-compiled codecs drop undecla
A cancellation-aware Remote method declares `signal: AbortSignal` as its final Host parameter. The signal is descriptor metadata rather than a wire argument: Connection supplies it to the Gateway, and the Gateway injects it after decoded business parameters. SRC recognizes the reserved final name, while strict generation additionally requires the global `AbortSignal` type.
A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A Pong, any received frame, or a downlink write that does not complete at once counts as peer activity; with the default `'deflate'`, a frame whose JSON text reaches the compression threshold is deflated asynchronously, so its completion always counts. A socket with no activity across two Ping intervals is terminated, so a congested link that delays the Pong behind data stays connected. With `websocketCompression` at its `'deflate'` default, an upgrade that offers `permessage-deflate` negotiates the extension, and the Host compresses its own outbound frames whose JSON text reaches 1,024 characters; shorter frames stay uncompressed, uplink frames are compressed at the peer's discretion, and `'none'` accepts the same upgrades without the extension. Independently cancellable logical streams share that socket; an in-process Connection carrier provides equivalent streams directly without opening it.
A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A Pong, any received frame, or a downlink write that does not complete at once counts as peer activity; with the default `'deflate'`, a frame whose JSON text reaches the compression threshold is deflated asynchronously, so its completion always counts. A socket with no activity across two Ping intervals is terminated, so a congested link that delays the Pong behind data stays connected. With `websocketCompression` at its `'deflate'` default, an upgrade that offers `permessage-deflate` negotiates the extension, and the Host compresses its own outbound frames whose JSON text reaches 1,024 characters; shorter frames stay uncompressed, uplink frames are compressed at the peer's discretion, and `'none'` accepts the same upgrades without the extension. Independently cancellable logical streams share that socket. Each downlink item enters one connection-wide write queue as soon as its stream's source produces it, so items of different streams are written in the order the sources produced them; a stream does not wait for its own previous item to be written. When the queued, unwritten bytes exceed `streamOutboxBytes` (1048576 by default), every stream on the connection pauses reading its source until the queue drains. The order covers only what the sources produce: a source that adds asynchronous steps before it yields an item produces it later. An in-process Connection carrier provides equivalent streams directly without opening the socket.
When the launcher supplies `ctx.appReady`, Gateway registers the WebSocket upgrade route only after successful application startup. Earlier connection attempts remain carrier failures handled by Connection's retry policy, so a restarting Host cannot accept streams while its controllers are still initializing. Unloading cancels a pending readiness subscription and closes any registered carrier. Embedded Hosts without `appReady` register immediately and own their startup ordering; in-process invocation is unchanged.
+1 -1
View File
@@ -38,7 +38,7 @@ Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandle
支持取消的 Remote 方法会把 `signal: AbortSignal` 声明为最后一个 Host 参数。signal 是 descriptor 元数据,而不是 wire 参数:Connection 将它提供给 Gateway,Gateway 则在已解码的业务参数之后注入它。SRC 识别这个保留的末位参数名,严格生成还要求它具有全局 `AbortSignal` 类型。
流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。Pong、收到的任意帧,或未一次性完成的下行写入,都视为对端活动;默认 `'deflate'` 下,JSON 文本达到压缩阈值的帧异步 deflate,因此其完成总是计入。连续两个 Ping 间隔没有活动的 socket 会被终止,因此 Pong 被数据阻塞在拥塞链路上时连接仍会保持。`websocketCompression` 保持默认的 `'deflate'` 时,携带 `permessage-deflate` 的升级会协商该扩展,Host 压缩自己发出的、JSON 文本达到 1024 个字符 的帧;更短的帧不压缩,上行帧是否压缩由对端决定,设为 `'none'` 时接受同样的升级但不带该扩展。可独立取消的逻辑流共享这条连接;进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。
流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。Pong、收到的任意帧,或未一次性完成的下行写入,都视为对端活动;默认 `'deflate'` 下,JSON 文本达到压缩阈值的帧异步 deflate,因此其完成总是计入。连续两个 Ping 间隔没有活动的 socket 会被终止,因此 Pong 被数据阻塞在拥塞链路上时连接仍会保持。`websocketCompression` 保持默认的 `'deflate'` 时,携带 `permessage-deflate` 的升级会协商该扩展,Host 压缩自己发出的、JSON 文本达到 1024 个字符 的帧;更短的帧不压缩,上行帧是否压缩由对端决定,设为 `'none'` 时接受同样的升级但不带该扩展。可独立取消的逻辑流共享这条连接。每个下行项在其流的源产出时立即进入整条连接共用的写出队列,因此不同流的项按各源产出的先后写出;一条流不会等自己的上一项写完。排队且尚未写出的字节超过 `streamOutboxBytes`(默认 1048576)时,这条连接上的所有流暂停读取各自的源,直到队列消化。这一顺序只覆盖源产出的先后:源在产出某项之前多做了异步步骤,这一项就产出得更晚。进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。
启动器提供 `ctx.appReady` 时,Gateway 仅在应用成功启动后注册 WebSocket 升级路由。此前的连接尝试仍属于载体故障,由 Connection 的重试策略处理,因此重启中的 Host 不会在控制器仍在初始化时接受流。卸载会取消尚未触发的就绪订阅,并关闭已注册的载体。不提供 `appReady` 的嵌入式 Host 会立即注册,并自行负责启动顺序;进程内调用不变。
+9
View File
@@ -147,6 +147,7 @@ type ConnectionRpcError = Extract<ConnectionRpcResult, { readonly ok: false }>['
const NEVER_ABORTED_SIGNAL = new AbortController().signal
const DEFAULT_WEBSOCKET_HEARTBEAT_INTERVAL_MS = 2_000
const DEFAULT_STREAM_INBOX_BYTES = 262_144
const DEFAULT_STREAM_OUTBOX_BYTES = 1_048_576
const EMPTY_ASYNC_ITERABLE: AsyncIterable<never> = {
[Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({ value: undefined, done: true }) }),
}
@@ -159,6 +160,11 @@ export interface Config {
readonly websocketHeartbeatIntervalMs?: number
/** Buffered uplink frame bytes one logical stream may hold before it fails with `gateway/uplink-overflow`. @default 262144 */
readonly streamInboxBytes?: number
/**
* Encoded downlink bytes one WebSocket connection may have queued and unwritten before every logical stream on it
* pauses reading its source. Items leave in the order their streams produced them. @default 1048576
*/
readonly streamOutboxBytes?: number
/** Per-message compression for the Remote stream WebSocket; `'none'` disables the extension. @default 'deflate' */
readonly websocketCompression?: 'none' | 'deflate'
}
@@ -166,6 +172,7 @@ export interface Config {
interface ResolvedConfig extends Config {
readonly websocketHeartbeatIntervalMs: number
readonly streamInboxBytes: number
readonly streamOutboxBytes: number
readonly websocketCompression: 'none' | 'deflate'
}
@@ -216,6 +223,7 @@ export class TypertGatewayService extends Service implements TypertGateway {
websocketHeartbeatIntervalMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS)
.default(DEFAULT_WEBSOCKET_HEARTBEAT_INTERVAL_MS),
streamInboxBytes: z.number().step(1).min(1).default(DEFAULT_STREAM_INBOX_BYTES),
streamOutboxBytes: z.number().step(1).min(1).default(DEFAULT_STREAM_OUTBOX_BYTES),
websocketCompression: z.union([z.const('none'), z.const('deflate')]).default('deflate'),
})
@@ -260,6 +268,7 @@ export class TypertGatewayService extends Service implements TypertGateway {
{
heartbeatIntervalMs: resolved.websocketHeartbeatIntervalMs,
streamInboxBytes: resolved.streamInboxBytes,
streamOutboxBytes: resolved.streamOutboxBytes,
compression: resolved.websocketCompression === 'deflate',
},
)
+57 -4
View File
@@ -47,6 +47,8 @@ export interface RemoteStreamMuxServerOptions {
readonly heartbeatIntervalMs: number
/** Buffered uplink frame bytes one logical stream may hold before it fails. */
readonly streamInboxBytes: number
/** Queued, unwritten downlink bytes one connection may hold before its streams pause reading their sources. */
readonly streamOutboxBytes: number
/** Whether accepted connections negotiate the `permessage-deflate` extension. */
readonly compression: boolean
}
@@ -56,6 +58,7 @@ export class RemoteStreamMuxServer {
private readonly server: WebSocketServer
private readonly heartbeatIntervalMs: number
private readonly streamInboxBytes: number
private readonly streamOutboxBytes: number
private readonly compression: boolean
private readonly connections = new Set<Promise<void>>()
private readonly missedHeartbeats = new WeakMap<WebSocket, number>()
@@ -64,7 +67,7 @@ export class RemoteStreamMuxServer {
/**
* @param open - Gateway stream dispatcher.
* @param failure - Gateway error-to-wire mapper.
* @param options - heartbeat interval, uplink inbox bound, and compression setting for accepted connections.
* @param options - heartbeat interval, uplink inbox bound, downlink backlog bound, and compression setting for accepted connections.
*/
constructor(
private readonly open: RemoteStreamOpener,
@@ -73,6 +76,7 @@ export class RemoteStreamMuxServer {
) {
this.heartbeatIntervalMs = options.heartbeatIntervalMs
this.streamInboxBytes = options.streamInboxBytes
this.streamOutboxBytes = options.streamOutboxBytes
this.compression = options.compression
this.server = new WebSocketServer({
noServer: true,
@@ -101,7 +105,7 @@ export class RemoteStreamMuxServer {
const bound: BoundStreamOpener = (endpoint, payload, uplink, control, window) =>
this.open(endpoint, payload, uplink, peer, control, window)
const connection = new RemoteStreamMuxConnection(
websocket, bound, this.failure, this.streamInboxBytes, this.compression, alive,
websocket, bound, this.failure, this.streamInboxBytes, this.streamOutboxBytes, this.compression, alive,
)
const done = connection.run().catch((error: unknown) => {
console.error('[api-gateway] Remote stream connection failed:', error)
@@ -158,15 +162,24 @@ interface ActiveStream {
done: Promise<void>
}
/**
* One WebSocket's logical streams. Every downlink frame enters one connection-wide write queue at the moment its
* stream's source produces it, so frames leave in production order across streams; a stream does not wait for its
* own previous frame to be written. Only the connection backlog pauses sources.
*/
class RemoteStreamMuxConnection {
private readonly streams = new Map<string, ActiveStream>()
private writes = Promise.resolve()
/** Encoded bytes queued and not yet written. */
private queuedBytes = 0
private drained: PromiseWithResolvers<void> | undefined
constructor(
private readonly socket: WebSocket,
private readonly open: BoundStreamOpener,
private readonly failure: RemoteStreamFailureMapper,
private readonly streamInboxBytes: number,
private readonly streamOutboxBytes: number,
private readonly compression: boolean,
private readonly alive: () => void,
) {}
@@ -198,6 +211,9 @@ class RemoteStreamMuxConnection {
})
})
await closed
// Sources paused on the backlog resume and observe their stop.
this.drained?.resolve()
this.drained = undefined
const active = [...this.streams.values()]
for (const stream of active) stream.stop(new Error('Remote stream socket closed'))
await Promise.all(active.map(stream => stream.done))
@@ -272,9 +288,17 @@ class RemoteStreamMuxConnection {
maxBytes: this.streamInboxBytes,
frameOverheadBytes: Buffer.byteLength(JSON.stringify({ type: 'item', streamId, value: null }), 'utf8') - 'null'.length,
})
let written: Promise<void> = Promise.resolve()
let writeFailure: { readonly error: unknown } | undefined
for await (const value of source) {
await this.send({ type: 'item', streamId, value })
if (writeFailure !== undefined) throw writeFailure.error
written = this.send({ type: 'item', streamId, value })
written.catch((error: unknown) => { writeFailure ??= { error } })
await this.backlogDrained(active.abort.signal)
// A cancelled stream stops at once; it does not wait for other streams to drain the connection backlog.
if (active.abort.signal.aborted) break
}
if (!active.abort.signal.aborted) await written
outcome = { failed: false }
} catch (error) {
outcome = { failed: true, error }
@@ -312,15 +336,43 @@ class RemoteStreamMuxConnection {
}
}
/**
* Resolve once the connection backlog is within its bound, the socket has closed, or the stream is cancelled.
* @param signal - the waiting stream's cancellation.
*/
private async backlogDrained(signal: AbortSignal): Promise<void> {
while (this.queuedBytes > this.streamOutboxBytes && this.socket.readyState === WebSocket.OPEN && !signal.aborted) {
this.drained ??= Promise.withResolvers<void>()
const cancelled = Promise.withResolvers<void>()
const onAbort = (): void => { cancelled.resolve() }
signal.addEventListener('abort', onAbort, { once: true })
await Promise.race([this.drained.promise, cancelled.promise])
signal.removeEventListener('abort', onAbort)
}
}
/**
* Queue one frame behind every frame queued before it on this connection.
* @throws Error synchronously when the frame is not JSON serializable; nothing is queued.
*/
private send(message: RemoteStreamServerMessage): Promise<void> {
let text: string
try {
text = JSON.stringify(message)
} catch (cause) {
return Promise.reject(new Error('api gateway: Remote stream item is not JSON serializable', { cause }))
throw new Error('api gateway: Remote stream item is not JSON serializable', { cause })
}
const bytes = Buffer.byteLength(text, 'utf8')
this.queuedBytes += bytes
const settled = (): void => {
this.queuedBytes -= bytes
if (this.queuedBytes > this.streamOutboxBytes) return
this.drained?.resolve()
this.drained = undefined
}
const delivery = this.writes.then(() => new Promise<void>((resolve, reject) => {
if (this.socket.readyState !== WebSocket.OPEN) {
settled()
reject(new Error('api gateway: Remote stream socket is closed'))
return
}
@@ -328,6 +380,7 @@ class RemoteStreamMuxConnection {
this.socket.send(text, {
compress: this.compression && text.length >= 1024,
}, (error) => {
settled()
if (error) {
reject(error)
return
@@ -416,21 +416,27 @@ describe('Typert Remote streams', () => {
expect(() => { startup.commit() }).not.toThrow()
})
it('validates the WebSocket heartbeat timer range, the stream inbox bound, and the compression mode', () => {
it('validates the WebSocket heartbeat timer range, the stream inbox and outbox bounds, and the compression mode', () => {
expect(TypertGatewayService.Config({})).toEqual({
websocketHeartbeatIntervalMs: 2_000,
streamInboxBytes: 262_144,
streamOutboxBytes: 1_048_576,
websocketCompression: 'deflate',
})
expect(TypertGatewayService.Config({
websocketHeartbeatIntervalMs: MAX_TIMER_DELAY_MS,
streamInboxBytes: 1,
streamOutboxBytes: 1,
websocketCompression: 'none',
})).toEqual({
websocketHeartbeatIntervalMs: MAX_TIMER_DELAY_MS,
streamInboxBytes: 1,
streamOutboxBytes: 1,
websocketCompression: 'none',
})
for (const streamOutboxBytes of [0, 1.5]) {
expect(() => TypertGatewayService.Config({ streamOutboxBytes })).toThrow()
}
for (const websocketHeartbeatIntervalMs of [0, 1.5, MAX_TIMER_DELAY_MS + 1]) {
expect(() => TypertGatewayService.Config({ websocketHeartbeatIntervalMs })).toThrow()
}
@@ -226,6 +226,28 @@ describe('Remote stream mux server carrier lifecycle', () => {
expect(String(closeEvent[1])).toBe('Remote stream failure could not be delivered')
})
it('stops a stream at its next item after an earlier item failed to write', async () => {
let release!: () => void
const released = new Promise<void>((resolve) => { release = resolve })
const produced: string[] = []
const entry = await startMux(async () => (async function *() {
await released
for (const value of ['first', 'second', 'third']) {
produced.push(value)
yield value
await new Promise<void>((resolve) => { setImmediate(resolve) })
}
})())
const client = await connect(entry.url)
client.send(openFrame('write-failure-next'))
await vi.waitFor(() => { expect(acceptedSocket(entry.mux)).toBeDefined() })
failWrites(acceptedSocket(entry.mux))
const closed = once(client, 'close')
release()
expect((await closed)[0]).toBe(1011)
expect(produced).toEqual(['first', 'second'])
})
it('closes the carrier when the end frame cannot be written', async () => {
const entry = await startMux(async () => (async function *(): AsyncIterable<never> {})())
const client = await connect(entry.url)
@@ -351,6 +373,170 @@ describe('Remote stream mux server carrier lifecycle', () => {
})
})
describe('Remote stream mux server downlink order', () => {
/** Hold every server write until released, recording the frames in write order. */
function holdWrites(serverSocket: WebSocket): { written: string[]; release: () => void } {
const mutable = serverSocket as {
send(data: string, options: unknown, callback: (error?: Error) => void): void
}
const original = mutable.send.bind(serverSocket)
const written: string[] = []
const held: (() => void)[] = []
let holding = true
mutable.send = (data, options, callback): void => {
written.push(String((JSON.parse(data) as { value?: unknown }).value))
const write = (): void => { original(data, options, callback) }
if (holding) held.push(write)
else write()
}
return { written, release: () => { holding = false; for (const write of held.splice(0)) write() } }
}
/** A source that yields each pushed value until its stream is cancelled; pushes made while it waits wake it in push order. */
function pushSource(): { source: (signal: AbortSignal) => AsyncIterable<string>; push: (value: string) => void } {
const queue: string[] = []
let wake: (() => void) | undefined
return {
push: (value) => { queue.push(value); wake?.() },
source: async function *(signal) {
signal.addEventListener('abort', () => { wake?.() }, { once: true })
while (!signal.aborted) {
const value = queue.shift()
if (value !== undefined) yield value
else await new Promise<void>((resolve) => { wake = resolve })
}
},
}
}
it('writes frames of different streams in production order while an earlier write is still pending', async () => {
const sources = { a: pushSource(), b: pushSource() }
let opened = 0
const allOpen = Promise.withResolvers<undefined>()
const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => {
if (++opened === 2) allOpen.resolve(undefined)
return sources[endpoint === 'fixture/a' ? 'a' : 'b'].source(control.signal)
})
const client = await connect(entry.url)
const frames = collectFrames(client)
client.send(openFrame('a', 'fixture/a'))
client.send(openFrame('b', 'fixture/b'))
await allOpen.promise
await new Promise<void>((resolve) => { setImmediate(resolve) })
const held = holdWrites(acceptedSocket(entry.mux))
sources.a.push('a1')
await vi.waitFor(() => { expect(held.written).toEqual(['a1']) })
// The first write is still pending; stream a's next frame is produced before stream b's.
sources.a.push('a2')
sources.b.push('b1')
await new Promise<void>((resolve) => { setImmediate(resolve) })
held.release()
await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['a1', 'a2', 'b1']) })
client.close()
await once(client, 'close')
})
it('keeps every stream paused until the whole connection backlog drains', async () => {
const sources = { a: pushSource(), b: pushSource() }
let opened = 0
const allOpen = Promise.withResolvers<undefined>()
const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => {
if (++opened === 2) allOpen.resolve(undefined)
return sources[endpoint === 'fixture/a' ? 'a' : 'b'].source(control.signal)
}, 2_000, 262_144, true, undefined, 1)
const client = await connect(entry.url)
const frames = collectFrames(client)
client.send(openFrame('a', 'fixture/a'))
client.send(openFrame('b', 'fixture/b'))
await allOpen.promise
// Both sources reach their first wait before anything is pushed.
await new Promise<void>((resolve) => { setImmediate(resolve) })
const held = holdWrites(acceptedSocket(entry.mux))
sources.a.push('a1')
sources.b.push('b1')
sources.a.push('a2')
await new Promise<void>((resolve) => { setImmediate(resolve) })
held.release()
await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['a1', 'b1', 'a2']) })
client.close()
await once(client, 'close')
})
it('ends a cancelled stream at once while another stream keeps the connection backlog over its bound', async () => {
const sources = { a: pushSource(), b: pushSource() }
const ended = Promise.withResolvers<undefined>()
let opened = 0
const allOpen = Promise.withResolvers<undefined>()
const entry = await startMux(async (endpoint, _payload, _uplink, _peer, control) => {
if (++opened === 2) allOpen.resolve(undefined)
if (endpoint === 'fixture/a') return sources.a.source(control.signal)
return (async function *() {
try {
yield * sources.b.source(control.signal)
} finally {
ended.resolve(undefined)
}
})()
}, 2_000, 262_144, true, undefined, 1)
const client = await connect(entry.url)
client.send(openFrame('a', 'fixture/a'))
client.send(openFrame('b', 'fixture/b'))
await allOpen.promise
await new Promise<void>((resolve) => { setImmediate(resolve) })
const held = holdWrites(acceptedSocket(entry.mux))
sources.a.push('a1')
sources.b.push('b1')
await vi.waitFor(() => { expect(held.written).toEqual(['a1']) })
await new Promise<void>((resolve) => { setImmediate(resolve) })
// a1 is still held and b1 queued behind it, so the backlog stays over its bound while stream b is cancelled.
client.send(JSON.stringify({ type: 'cancel', streamId: 'b' }))
await ended.promise
held.release()
client.close()
await once(client, 'close')
})
it('fails a stream whose item cannot be encoded without queuing a frame for it', async () => {
const entry = await startMux(async () => (async function *() { yield 10n })())
const client = await connect(entry.url)
const frames = collectFrames(client)
client.send(openFrame('bigint'))
await vi.waitFor(() => {
expect(frames).toEqual([{
type: 'error', streamId: 'bigint',
error: { code: 'internal', message: 'api gateway: Remote stream item is not JSON serializable', details: {} },
}])
})
client.close()
await once(client, 'close')
})
it('pauses every stream while the connection backlog exceeds its bound and resumes when it drains', async () => {
const source = pushSource()
const pulled: string[] = []
const entry = await startMux(async (_endpoint, _payload, _uplink, _peer, control) => (async function *() {
for await (const value of source.source(control.signal)) {
pulled.push(value)
yield value
}
})(), 2_000, 262_144, true, undefined, 1)
const client = await connect(entry.url)
const frames = collectFrames(client)
client.send(openFrame('bounded'))
await vi.waitFor(() => { expect(acceptedSocket(entry.mux)).toBeDefined() })
const held = holdWrites(acceptedSocket(entry.mux))
source.push('x1')
source.push('x2')
await vi.waitFor(() => { expect(held.written).toEqual(['x1']) })
await new Promise<void>((resolve) => { setImmediate(resolve) })
expect(pulled).toEqual(['x1'])
held.release()
await vi.waitFor(() => { expect(frames.map(frame => frame.value)).toEqual(['x1', 'x2']) })
client.close()
await once(client, 'close')
})
})
describe('Remote stream mux server Peer binding', () => {
it('closes an upgrade at once when the admitted Peer scope is already disposed', async () => {
const peer = await fixturePeer()
@@ -667,11 +853,13 @@ async function startMux(
streamInboxBytes = 262_144,
compression = true,
peer?: PeerScope,
streamOutboxBytes = 1_048_576,
): Promise<RunningMux> {
const admitted = peer ?? await fixturePeer()
const mux = new RemoteStreamMuxServer(open, mapFailure, {
heartbeatIntervalMs,
streamInboxBytes,
streamOutboxBytes,
compression,
})
const http = createServer()
+5 -4
View File
@@ -214,10 +214,11 @@
- id: harness-dev-context
name: '@deepseek-ai/dsh-harness-dev-context'
# The client-plugin reload chain, always mounted: it is idle until a
# rebuild watcher (pnpm run dev:web) actually rewrites client bundles. It
# is a row rather than a child of web-runtime because its node half is a
# client-side package, which a host-side bundle cannot import.
# The plugin-events stream, always mounted: it delivers graph changes,
# synced configuration, and rebuilt bundles (the last only while a rebuild
# watcher such as pnpm run dev:web rewrites client bundles). It is a row
# rather than a child of web-runtime because its node half is a client-side
# package, which a host-side bundle cannot import.
- id: client-hmr
name: '@deepseek-ai/dsh-client-hmr'
+37
View File
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/config/README.md
/:
en: b1b4983cf77dfb64
zh: f0fa8e1768282924
/deepseek-ai-dsh-client-config:
en: e62a65f2b2584f33
zh: 7321f65efcf87c4f
/deepseek-ai-dsh-client-config/summary:
en: 7de2db28a3a02961
zh: e216c6e28756b37b
/deepseek-ai-dsh-client-config/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-config/use-this-package:
en: f3b26e6717641ce1
zh: bd9db5843968e118
/deepseek-ai-dsh-client-config/understand-the-implementation:
en: 84cb86065c15a770
zh: 675b8559bf14b413
/deepseek-ai-dsh-client-config/further-exploration:
en: f91f84cf3575375f
zh: dfac4f201eaafd82
/deepseek-ai-dsh-client-config/model-experience:
en: 0eb698f5627362b0
zh: 5d73fdb6cf8f246c
/deepseek-ai-dsh-client-config/model-experience/kv-cache-effect:
en: ca75c51c89c2c9b0
zh: 2064958b0754647e
/deepseek-ai-dsh-client-config/known-limitations-and-deferred-work:
en: cd8d4c6d8ae328a0
zh: 62d462921cb015d6
/deepseek-ai-dsh-client-config/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: e88aeb617ffb74ea
+82
View File
@@ -0,0 +1,82 @@
---
description: "Types of browser-synced plugin configuration"
kind: "package-reference"
---
# @deepseek-ai/dsh-client-config
English | [中文](README.zh.md)
## Summary
The types a browser plugin uses to read its live Host configuration. A plugin declares its Config once, with a Host schema; its Client face receives the top-level volatile fields as a `SyncedConfig` through `apply` and reads other packages' synced Config through `ctx.config`. This package holds types only; [Client Modules](../modules/README.md#synced-plugin-configuration) projects, delivers, and updates the values.
## Table of Contents
- [Use this package](#use-this-package)
- [Understand the implementation](#understand-the-implementation)
- [Further Exploration](#further-exploration)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
-----
<a id="use-this-package"></a>
## Use this package
A plugin package lists this package in `devDependencies` and imports from `@deepseek-ai/dsh-client-config/types` with `import type` only:
| Type | Use |
|---|---|
| `SyncedConfig<C>` | The `apply` config of a Client face whose shared Config type is `C`: one `SyncedConfigRef` per top-level `Volatile` field. Every field may read `undefined` (a secret, an unprojectable value, or a Host build not yet matching the browser code), so the plugin handles the absent value at each read |
| `SyncedConfigRef<T>` | One field: `get()` reads the current frozen value as the Host reads a volatile reference, and `getSnapshot` with `subscribe` make it the observable source injected into a slot's `hooks` compartment. It has no write operation |
| `SyncedConfigValues` | The JSON values of one plugin's synced fields, as graph rows carry them |
| `SyncedConfigService` | `ctx.config.resolveConfigByPackage<C>(packageName)`, a read-only lookup of another package's current activation object; importing the types also declares `ctx.config` |
-----
<a id="understand-the-implementation"></a>
## Understand the implementation
<details>
<summary>Implementation internals — click to expand</summary>
The package exports types through `./types` and both faces, and its Host and Client `apply` register nothing. Client Modules implements every type: the Host face projects values into graph rows, and the page entry controller hands each plugin activation its object and provides `ctx.config`. Plugins therefore depend on these types instead of on the bootstrap Client Modules package.
</details>
-----
<a id="further-exploration"></a>
## Further Exploration
- [Agent Note: browser plugin configuration sync](../../../.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md)
- [Client Modules synced plugin configuration](../modules/README.md#synced-plugin-configuration)
-----
<a id="model-experience"></a>
## Model Experience
None, as the package declares browser configuration types and registers nothing model-facing.
#### KV Cache effect
None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
<a id="known-limitations-and-deferred-work"></a>
- `resolveConfigByPackage` trusts the caller's Config type argument; a wrong type is not detected.
<a id="dev-note"></a>
### Dev Note
<details>
<summary>Working context for maintainers — click to expand</summary>
None.
</details>
+82
View File
@@ -0,0 +1,82 @@
---
description: "浏览器同步插件配置的类型"
kind: "package-reference"
---
# @deepseek-ai/dsh-client-config
[English](README.md) | 中文
## 概述
浏览器插件读取自身实时 Host 配置所用的类型。插件只声明一份 Config 并配一个 Host schema;其 Client 面通过 `apply` 以 `SyncedConfig` 收到顶层 volatile 字段,并通过 `ctx.config` 读取其他包的同步配置。本包只包含类型;值的投影、下发与更新由 [Client Modules](../modules/README.zh.md#synced-plugin-configuration) 负责。
## 目录
- [使用本包](#use-this-package)
- [理解实现](#understand-the-implementation)
- [进一步探索](#further-exploration)
- [模型体验](#model-experience)
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
-----
<a id="use-this-package"></a>
## 使用本包
插件包把本包列入 `devDependencies`,只用 `import type` 从 `@deepseek-ai/dsh-client-config/types` 导入:
| 类型 | 用途 |
|---|---|
| `SyncedConfig<C>` | 共享 Config 类型为 `C` 的 Client 面的 `apply` 配置:每个顶层 `Volatile` 字段对应一个 `SyncedConfigRef`。每个字段都可能读到 `undefined`(密钥、无法投影的值,或尚未与浏览器代码对应的 Host 构建),插件在每次读取时处理缺值 |
| `SyncedConfigRef<T>` | 单个字段:`get()` 读取当前冻结值,写法与 Host 读取 volatile 引用一致;`getSnapshot` 与 `subscribe` 使它可以直接作为可观察数据源注入 slot 的 `hooks`。它没有写操作 |
| `SyncedConfigValues` | 图行携带的单个插件同步字段的 JSON 值 |
| `SyncedConfigService` | `ctx.config.resolveConfigByPackage<C>(packageName)`,只读地查询另一个包当前激活的对象;导入这些类型也同时声明了 `ctx.config` |
-----
<a id="understand-the-implementation"></a>
## 理解实现
<details>
<summary>实现细节——点击展开</summary>
本包通过 `./types` 与两个面导出类型,Host 与 Client 的 `apply` 都不注册任何内容。所有类型由 Client Modules 实现:Host 面把值投影进图行,页面条目控制器把对象交给每次插件激活并提供 `ctx.config`。因此插件依赖这些类型,而不是依赖启动最早的 Client Modules 包。
</details>
-----
<a id="further-exploration"></a>
## 进一步探索
- [Agent Note:前端插件配置同步](../../../.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md)
- [Client Modules 同步插件配置](../modules/README.zh.md#synced-plugin-configuration)
-----
<a id="model-experience"></a>
## 模型体验
无,本包声明浏览器配置类型,不注册任何面向模型的内容。
#### KV Cache 影响
无;本包既不组装也不发送 provider 请求。
## 已知限制与延期工作
<a id="known-limitations-and-deferred-work"></a>
- `resolveConfigByPackage` 信任调用方给出的 Config 类型参数,类型写错不会被发现。
<a id="dev-note"></a>
### 开发备注
<details>
<summary>维护者工作上下文——点击展开</summary>
无。
</details>
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Typen für synchronisierte Konfiguration",
"description": "Typen zum Lesen der Live-Host-Konfiguration in Browser-Plugins."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Synced configuration types",
"description": "Types for reading live Host configuration in browser plugins."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Tipos de configuración sincronizada",
"description": "Tipos para leer la configuración en vivo del Host en los plugins del navegador."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Types de configuration synchronisée",
"description": "Types pour lire la configuration en direct de l’Host dans les plugins du navigateur."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "同期設定の型",
"description": "ブラウザープラグインがライブの Host 設定を読み取るための型。"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Tipos de configuração sincronizada",
"description": "Tipos para ler a configuração ao vivo do Host em plugins do navegador."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Типы синхронизированной конфигурации",
"description": "Типы для чтения актуальной конфигурации Host в браузерных плагинах."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"meta": {
"title": "同步配置类型",
"description": "浏览器插件读取实时 Host 配置所用的类型。"
}
}
+60
View File
@@ -0,0 +1,60 @@
{
"name": "@deepseek-ai/dsh-client-config",
"description": "Types of browser-synced plugin configuration",
"version": "0.2.2-rc.3",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/client/config"
},
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./types": {
"types": "./lib/types/types.d.ts"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
},
"./locale/*.json": "./locale/*.json",
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"dsh": {
"client": {
"inject": [],
"platform": "web"
}
},
"scripts": {
"bundle": "tsdown",
"watch": "tsdown --watch"
},
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-client-store": "workspace:*",
"@deepseek-ai/dsh-util-values": "workspace:*"
},
"files": [
"locale/*.json",
"lib/index.js",
"lib/client.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
"src"
]
}
@@ -0,0 +1,5 @@
/** Client face of the synced configuration types package; `@deepseek-ai/dsh-client-modules` provides the runtime. */
export type * from '../types.ts'
/** Register nothing in the browser. */
export function apply(): void {}
+5
View File
@@ -0,0 +1,5 @@
/** Host face of the synced configuration types package; the types live in `./types` and no Host behavior exists. */
export type * from './types.ts'
/** Register nothing on the Host. */
export function apply(): void {}
+49
View File
@@ -0,0 +1,49 @@
/**
* Types of browser-synced plugin configuration. A plugin declares its Config once, with a Host schema; its Client face
* receives the top-level volatile fields as a {@link SyncedConfig} through `apply`. `@deepseek-ai/dsh-client-modules`
* implements these types; plugins import them from here only.
* @module @deepseek-ai/dsh-client-config/types
*/
import type { Volatile, VolatileSnapshot } from '@deepseek-ai/cordis'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
/** JSON values of one plugin's synced Config fields, keyed by field name. */
export type SyncedConfigValues = { readonly [field: string]: JsonValue }
/**
* One synced Config field. `get()` reads it as the Host face reads a volatile reference; the reference is also the
* observable source a plugin injects into a slot's `hooks` compartment. Its snapshot keeps its identity until the value
* changes, and every changed field of one update is set before any subscriber runs. It has no write operation.
*/
export interface SyncedConfigRef<T> extends Volatile<T>, ObservableSnapshot<VolatileSnapshot<T>> {}
/**
* Browser view of a plugin's shared Config type: its top-level `Volatile` fields, each a {@link SyncedConfigRef}.
* Every field may read `undefined`: the Host never sends a `role('secret')` field, keeps a field it cannot project
* unsent, and may send values of a Host build that does not yet match the running browser code. The plugin handles
* the absent value at each read.
*/
export type SyncedConfig<C> = {
readonly [K in keyof C as NonNullable<C[K]> extends Volatile<unknown> ? K : never]-?:
NonNullable<C[K]> extends Volatile<infer V> ? SyncedConfigRef<V | undefined> : never
}
/** Read-only access to other packages' synced Config; a plugin receives its own through `apply`. */
export interface SyncedConfigService {
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it. Each
* activation receives a new object, so the result changes when the plugin is replaced. The caller states the
* package's shared Config type.
* @param packageName - package name of the graph row.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage<C>(packageName: string): SyncedConfig<C> | undefined
}
declare module '@deepseek-ai/cordis' {
interface Context {
/** Read-only lookup of other packages' synced Config, provided by the client-modules plugin face. */
config: SyncedConfigService
}
}
@@ -0,0 +1,9 @@
/** The types package registers nothing: both faces' `apply` return without effects. */
import { expect, it } from 'vitest'
import { apply as clientApply } from '../src/client/index.ts'
import { apply as hostApply } from '../src/index.ts'
it('registers nothing on either face', () => {
expect(hostApply).not.toThrow()
expect(clientApply).not.toThrow()
})
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": ["src"],
"references": [
{ "path": "../../../vendor/cordis" },
{ "path": "../store" },
{ "path": "../../util/values" }
]
}
+3
View File
@@ -0,0 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
+8 -8
View File
@@ -9,8 +9,8 @@
en: 3f8aceed1a3a4221
zh: d48ff0e88eefa046
/deepseek-ai-dsh-client-hmr/summary:
en: 4ea7a901735da086
zh: 77fd5083661ceff5
en: b27f1dc15a6e9f90
zh: 76c4c84a18637def
/deepseek-ai-dsh-client-hmr/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
@@ -33,8 +33,8 @@
en: e5cdd3f10a344b10
zh: 70c8efd12531039d
/deepseek-ai-dsh-client-hmr/understand-the-implementation/design-concept:
en: 90f8d06719b177bd
zh: c5a770ddcacc0f87
en: 3925d19184d37198
zh: 9917f64db546fe03
/deepseek-ai-dsh-client-hmr/understand-the-implementation/the-browser-swap:
en: 269ff43822114dc8
zh: 8604c39c8050858a
@@ -45,8 +45,8 @@
en: cc2114489f83dc70
zh: 6268962333946c82
/deepseek-ai-dsh-client-hmr/understand-the-implementation/source-map:
en: 67728b630b30b9aa
zh: 55861de2169ecafe
en: e8ae5ad4073c5774
zh: ee0c6e11f2e78f45
/deepseek-ai-dsh-client-hmr/further-exploration:
en: 684aff651f59a12d
zh: 671bcfc50918508e
@@ -57,8 +57,8 @@
en: ca75c51c89c2c9b0
zh: de54f3467ef3b9be
/deepseek-ai-dsh-client-hmr/known-limitations-and-deferred-work:
en: 0003a3d701a7f7b1
zh: 9be135531742cf86
en: 98abf5b8b1a9c32a
zh: 579fd09b1946966c
/deepseek-ai-dsh-client-hmr/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
+7 -6
View File
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
`dsh-client-hmr` keeps open Web pages in sync with the Host plugin graph and reloads rebuilt browser bundles. Ordinary plugin enable/disable changes take effect without reloading the page or restarting the Host. Code rebuilds replace the affected plugin with fresh component state. The model sees no new input or output.
`dsh-client-hmr` keeps open Web pages in sync with the Host plugin graph, including synced plugin configuration, and reloads rebuilt browser bundles. Ordinary plugin enable/disable changes and synced configuration changes take effect without reloading the page or restarting the Host. Code rebuilds replace the affected plugin with fresh component state. The model sees no new input or output.
## Table of Contents
@@ -59,7 +59,7 @@ This section explains how the reload chain is built; observable behavior is cove
### Design concept
The Host half watches each package's stamped entry artifact and serves `/plugins/events`. It forwards existing graph-change and rebuilt notifications; every new connection receives the current full graph. A graph describes the browser’s desired entries and carries no Host cleanup-completion guarantee. Host activation and cleanup remain owned by the Host lifecycle. The entry's mtime, ctime, and size identify the revision without hashing its contents; unchanged metadata requires no content read. Host restarts over unchanged artifacts keep the same revisions, so reconnecting the graph stream does not replace browser plugins. The browser half delegates both frame kinds to Client Modules, which serializes entry changes and waits for browser resource cleanup.
The Host half watches each package's stamped entry artifact and serves the authenticated `pluginEvents/follow` Remote stream. Every stream generation opens with a `baseline` frame holding the current full graph, whose rows carry each plugin's [synced configuration](../modules/README.md#synced-plugin-configuration), followed by `graph` and `rebuilt` increments. A graph describes the browser’s desired entries and carries no Host cleanup-completion guarantee. Host activation and cleanup remain owned by the Host lifecycle. The entry's mtime, ctime, and size identify the revision without hashing its contents; unchanged metadata requires no content read. Host restarts over unchanged artifacts keep the same revisions, so reconnecting the graph stream does not replace browser plugins. The browser half mounts its own `pluginEvents` namespace, so the stream does not depend on the api-remotes assembly, and consumes it through `RemoteSnapshotStream` while Remote access allows `pluginEvents/follow`. It delegates graph and rebuilt frames to Client Modules, which applies synced configuration, serializes entry changes, and waits for browser resource cleanup. Carrier loss and a Host-side stream end reconnect, and the new baseline replaces any frames missed meanwhile.
### The browser swap
@@ -77,9 +77,10 @@ Download failures leave the running plugin active. After the old fiber is torn d
| File | Role |
|---|---|
| [`src/index.ts`](src/index.ts) | Node half: bundle stat-poll, `rebuilt` reporting, `/plugins/events` SSE channel |
| [`src/client/index.ts`](src/client/index.ts) | Browser half: SSE subscription through the page's `__DSH_TRANSPORT__.fetch` when a shell provides one (the worker preview's tunnel), otherwise through `EventSource`, and delegation to the shared entry controller |
| [`src/events.ts`](src/events.ts) | Shared frame types (`graph` / `rebuilt`) and the endpoint constant |
| [`src/index.ts`](src/index.ts) | Node half: bundle stat-poll and `rebuilt` reporting; mounts the Remote service |
| [`src/plugin-events.ts`](src/plugin-events.ts) | Host `pluginEvents` Remote service: baseline and ordered increments per stream generation |
| [`src/client/index.ts`](src/client/index.ts) | Browser half: mounts the `pluginEvents` namespace, follows the stream, and forwards frames to the entry controller |
| [`src/types.ts`](src/types.ts) | Shared frame types (`baseline` / `graph` / `rebuilt`) |
</details>
@@ -115,7 +116,7 @@ These limits define what the reload driver does not preserve or restore. They ar
- **Reload is coarse by design** — a fresh fiber and fresh components; React state inside the reloaded plugin is lost while the data layer (connection/runtime fibers, Session objects) is untouched. react-refresh-grade state preservation conflicts with re-executing the bundle and is deliberately out.
- **No failure rollback** — after the old fiber is torn down, a failed replacement does not restore the previous bundle.
- **Web transport only** — Electron installation and backend restart handling do not use this SSE path. Entry reconciliation itself is transport-independent.
- **The stream depends on its carrier** — it runs over Connection and the API Gateway Client face. When replacing either of them fails to import or activate, this plugin cannot activate and the page stops receiving plugin changes until it reloads. Electron installation does not use this stream; entry reconciliation itself is transport-independent.
<a id="dev-note"></a>
### Dev Note
+7 -6
View File
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
`dsh-client-hmr` 让已打开的 Web 页面与 Host 插件图保持同步,并重载重建后的浏览器 bundle。普通插件的启停无需刷新页面或重启 Host 即可生效。代码重建会替换受影响插件并重置其组件状态。模型不会收到新的输入或输出。
`dsh-client-hmr` 让已打开的 Web 页面与 Host 插件图及同步的插件配置保持一致,并重载重建后的浏览器 bundle。普通插件的启停与同步配置的变化无需刷新页面或重启 Host 即可生效。代码重建会替换受影响插件并重置其组件状态。模型不会收到新的输入或输出。
## 目录
@@ -59,7 +59,7 @@ kind: "package-reference"
### 设计理念
Host 半侧监听每个包带完成标记的入口产物,并提供 `/plugins/events`。它转发现有的图变化与重建通知;每个新连接都会收到当前完整图。图描述浏览器的目标条目,不保证 Host 清理已经完成。Host 的激活与清理仍由 Host 生命周期管理。入口的 mtime、ctime 和大小共同标识 revision,无需对其内容求哈希;元数据未变时无需读取内容。Host 重启时若产物未变,revision 保持不变,因此图流重连不会替换浏览器插件。浏览器半侧将两种帧都交给 Client Modules,由它串行处理条目变更并等待浏览器资源清理。
Host 半侧监听每个包带完成标记的入口产物,并提供经过鉴权的 `pluginEvents/follow` Remote 流。每一代流先发一个 `baseline` 帧,包含当前完整图,图的每一行携带该插件的[同步配置](../modules/README.zh.md#synced-plugin-configuration),之后发送 `graph` 与 `rebuilt` 增量。图描述浏览器的目标条目,不保证 Host 清理已经完成。Host 的激活与清理仍由 Host 生命周期管理。入口的 mtime、ctime 和大小共同标识 revision,无需对其内容求哈希;元数据未变时无需读取内容。Host 重启时若产物未变,revision 保持不变,因此图流重连不会替换浏览器插件。浏览器半侧自行挂载 `pluginEvents` 命名空间,因此这条流不依赖 api-remotes 组装;在 Remote access 允许 `pluginEvents/follow` 时通过 `RemoteSnapshotStream` 消费。它把图帧与重建帧交给 Client Modules,由它应用同步配置、串行处理条目变更并等待浏览器资源清理。连接丢失或 Host 侧流结束会重连,新的 baseline 覆盖期间遗漏的帧。
### 浏览器侧替换
@@ -77,9 +77,10 @@ fiber 的激活 epoch 会串联其服务提供方的 uid,因此替换提供方
| 文件 | 职责 |
|---|---|
| [`src/index.ts`](src/index.ts) | node 半侧:bundle stat 轮询、`rebuilt` 上报、`/plugins/events` SSE 通道 |
| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:页面有外壳提供的 `__DSH_TRANSPORT__.fetch`(worker preview 的隧道)时经它订阅 SSE,否则用 `EventSource`;并调用共享条目控制器 |
| [`src/events.ts`](src/events.ts) | 共享帧类型(`graph` / `rebuilt`)与端点常量 |
| [`src/index.ts`](src/index.ts) | node 半侧:bundle stat 轮询与 `rebuilt` 上报;挂载 Remote 服务 |
| [`src/plugin-events.ts`](src/plugin-events.ts) | Host `pluginEvents` Remote 服务:每一代流的 baseline 与有序增量 |
| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:挂载 `pluginEvents` 命名空间、跟随该流,并把帧交给条目控制器 |
| [`src/types.ts`](src/types.ts) | 共享帧类型(`baseline` / `graph` / `rebuilt`) |
</details>
@@ -115,7 +116,7 @@ fiber 的激活 epoch 会串联其服务提供方的 uid,因此替换提供方
- **重载有意保持粗粒度**——全新 fiber 与全新组件;被重载插件内的 React 状态会丢失,而数据层(连接 fiber、运行时 fiber、Session 对象)不受影响。react-refresh 级状态保留与重新执行 bundle 冲突,因此有意排除。
- **失败时不回滚**——旧 fiber 被卸载后,替换失败不会恢复先前的 bundle。
- **仅负责 Web 传输**——Electron 的安装和后端重启流程不使用此 SSE 路径。条目对账本身不依赖传输。
- **流依赖其承载链路**——它运行在 Connection 与 API Gateway Client 面之上。替换二者之一时若导入或激活失败,本插件无法激活,页面在刷新前收不到插件变化。Electron 的安装不使用这条流;条目对账本身不依赖传输。
<a id="dev-note"></a>
### 开发备注
+30 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-hmr",
"description": "Web client graph synchronization and rebuilt-bundle reload transport",
"description": "Web client graph and rebuilt-bundle delivery over an authenticated Remote stream",
"version": "0.2.2-rc.3",
"publishConfig": {
"access": "public"
@@ -18,17 +18,33 @@
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./types": {
"types": "./lib/types/types.d.ts"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
},
"./typert": {
"types": "./lib/typert.host.d.ts",
"default": "./lib/typert.host.js"
},
"./remote": {
"types": "./lib/typert.remote-client.d.ts",
"default": "./lib/typert.remote-client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json",
"./locale/*.json": "./locale/*.json"
},
"dsh": {
"client": {
"external": [
"@deepseek-ai/dsh-api-gateway/client"
],
"inject": [
"@deepseek-ai/dsh-api-gateway",
"@deepseek-ai/dsh-api-remote-access",
"@deepseek-ai/dsh-client-modules"
],
"platform": "web",
@@ -37,17 +53,20 @@
},
"license": "MIT",
"dependencies": {
"@deepseek-ai/schemastery": "workspace:~"
"@deepseek-ai/dsh-deque": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
"@deepseek-ai/schemastery": "workspace:~",
"zod": "4.6.6"
},
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
"@deepseek-ai/dsh-client-modules": "workspace:*",
"@deepseek-ai/dsh-host-webserver": "workspace:*",
"@deepseek-ai/cordis": "workspace:~",
"eventsource-parser": "^3.1.0"
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-client-modules": "workspace:*"
},
"files": [
"locale/*.json",
@@ -56,6 +75,11 @@
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
"lib/typert.host.js",
"lib/typert.host.d.ts",
"lib/typert.remote-client.js",
"lib/typert.remote-client.d.ts",
"lib/typert.remote-client.d.ts.map",
"src"
]
}
+94 -67
View File
@@ -1,87 +1,114 @@
/** Web SSE transport for page-owned client entry reconciliation and rebuilt code replacement. */
/** Remote-stream transport for page-owned client entry reconciliation, rebuilt code replacement, and synced configuration. */
import type { Context } from '@deepseek-ai/cordis'
import { EventSourceParserStream } from 'eventsource-parser/stream'
import type { PluginsEventParseResult } from '../events.ts'
import { EVENTS_ROUTE, parsePluginsEventFrame } from '../events.ts'
import { RemoteSnapshotStream, RemoteStreamCarrierError, type RemoteStreamCarrierFailure } from '@deepseek-ai/dsh-api-gateway/client'
import type {} from '@deepseek-ai/dsh-api-remote-access/client'
import type {} from '@deepseek-ai/dsh-client-modules/client'
// This package mounts its own namespace, so the channel does not depend on the api-remotes assembly being replaceable.
import pluginEventsRemote from '@deepseek-ai/dsh-client-hmr/remote'
import type { PluginsEventBaseline, PluginsEventFrame, PluginsEventIncrement } from '../types.ts'
export type { PluginsEventFrame } from '../events.ts'
export type * from '../types.ts'
/** Cordis plugin name. */
export const name = 'client-hmr'
/** Required service: the client module system whose entry controller handles received frames. */
export const inject = ['modules']
/** Required services: the module system whose entry controller handles frames, the Remote carrier, and Remote access. */
export const inject = ['modules', 'remote', 'remoteAccess']
/** Request carrier a shell installs when it owns the page transport, such as the worker preview's tunnel. */
type PageTransportFetch = (input: string, init: RequestInit) => Promise<Response>
const CARRIER_LOST: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost'
/** Remote failures a Host reload produces while it withdraws `pluginEvents` with the socket still open. */
const RELOADING: ReadonlySet<string> = new Set(['gateway/invocation-unavailable', 'gateway/service-unavailable'])
/** Page global carrying the shell transport; absent in the served web app. */
interface PageTransportGlobal {
__DSH_TRANSPORT__?: { fetch?: PageTransportFetch }
/**
* Open one generation, reporting an endpoint the Host has withdrawn while it reloads as a carrier loss, so the stream
* reconnects instead of ending.
* @param open - opens the generation's frames.
* @yields the generation's frames.
*/
async function *reconnectWhileReloading(open: () => AsyncIterable<PluginsEventFrame>): AsyncIterable<PluginsEventFrame> {
try {
yield * open()
} catch (error) {
if (error instanceof Error && 'code' in error && RELOADING.has(String(error.code))) {
throw new RemoteStreamCarrierError('Plugin events are unavailable while the Host reloads', { cause: error })
}
throw error
}
}
/** The generated `pluginEvents` client method this plugin calls. */
interface PluginEventsNamespace {
follow(signal: AbortSignal): AsyncIterable<PluginsEventFrame>
}
/** Receivers of one followed stream. */
interface PluginEventSinks {
/** A generation's complete graph. */
readonly baseline: (frame: PluginsEventBaseline) => void
/** One increment after the baseline. */
readonly increment: (frame: PluginsEventIncrement) => void
/** A terminal stream failure; graph changes stop until the page reloads. */
readonly failed: (error: unknown) => void
}
/**
* Read the document-relative events route through a shell-owned transport until it closes or `signal` aborts.
* @param fetch - The shell's request carrier.
* @param signal - Aborts the stream when the plugin disposes.
* @param receive - Handles one SSE `data` payload.
* @throws Error when the Host refuses the stream or the stream ends while the plugin is active.
* Follow `pluginEvents/follow` as a reconnecting baseline-and-increment stream.
* @param ctx - context carrying the Remote carrier and the mounted `pluginEvents` namespace.
* @param sinks - frame receivers.
* @returns the disposer that stops the stream and waits until no frame can arrive.
*/
async function readPageTransportEvents(fetch: PageTransportFetch, signal: AbortSignal, receive: (data: string) => void): Promise<void> {
const response = await fetch(EVENTS_ROUTE, { method: 'GET', headers: { accept: 'text/event-stream' }, signal })
if (!response.ok || response.body === null) {
throw new Error(`client-hmr: ${EVENTS_ROUTE} answered ${String(response.status)}`)
}
const reader = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader()
for (;;) {
const { done, value } = await reader.read()
if (done) break
receive(value.data)
}
if (!signal.aborted) throw new Error(`client-hmr: ${EVENTS_ROUTE} closed; client graph changes stop until the page reloads`)
function followPluginEvents(ctx: Context, sinks: PluginEventSinks): () => Promise<void> {
// `$mount` registered the namespace as its own service; only this plugin mounts it, so it is read by name rather
// than through a declared injection.
const namespace = ctx.get('remote.pluginEvents') as PluginEventsNamespace | undefined
if (namespace === undefined) throw new Error('client-hmr: the mounted pluginEvents namespace is not registered')
const stream = ctx.remote.$stream<PluginsEventFrame>({
name: 'Plugin events',
open: signal => reconnectWhileReloading(() => namespace.follow(signal)),
// A Host-side end (the service restarting) reconnects rather than ending the logical stream.
ended: (): RemoteStreamCarrierFailure => Object.assign(new Error('Plugin events stream ended'), { code: CARRIER_LOST }),
})
const control = new RemoteSnapshotStream<PluginsEventBaseline, PluginsEventIncrement>(stream, {
name: 'Plugin events',
isSnapshot: (frame): frame is PluginsEventBaseline => frame.type === 'baseline',
replace: sinks.baseline,
update: sinks.increment,
failed: sinks.failed,
})
control.start()
return () => control.dispose()
}
/**
* Forward graph snapshots and rebuilds to the page's shared serial controller. The event stream arrives through the
* shell transport when the page has one, otherwise through the browser `EventSource`.
* @param ctx - Plugin context with the client module system.
* Forward each stream generation's graph and rebuilds to the page's serial entry controller, which also applies each
* row's synced configuration, while Remote access allows the stream.
* @param ctx - Plugin context with the client module system and Remote carrier.
* @returns the disposer of this plugin's `pluginEvents` namespace.
*/
export function apply(ctx: Context): void {
export async function apply(ctx: Context): Promise<() => Promise<void>> {
const unmount = await ctx.remote.$mount(pluginEventsRemote)
const entries = ctx.modules.entries
const handle = (frame: Extract<PluginsEventParseResult, { kind: 'frame' }>['frame']): void => {
const run = frame.type === 'graph'
? Promise.resolve().then(() => entries.sync(frame.graph))
: entries.reload(frame.id, frame.rev)
void run.catch((error: unknown) => { ctx.logger.error(error) })
// A malformed graph throws synchronously from sync(); both paths report through the same rejection.
const run = (task: () => Promise<void>): void => {
void Promise.resolve().then(task).catch((error: unknown) => { ctx.logger.error(error) })
}
const receive = (data: string): void => {
let value: unknown
try {
value = JSON.parse(data)
} catch {
// Wire boundary: a malformed transport frame is dropped loudly.
ctx.logger.warn(`client-hmr: unparseable event frame: ${data}`)
return
}
const parsed = parsePluginsEventFrame(value)
if (parsed.kind === 'invalid') {
ctx.logger.warn(`client-hmr: invalid event frame: ${data}`)
} else if (parsed.kind === 'frame') {
handle(parsed.frame)
}
const sinks: PluginEventSinks = {
baseline: (frame) => { run(() => entries.sync(frame.graph)) },
increment: (frame) => {
switch (frame.type) {
case 'graph':
run(() => entries.sync(frame.graph))
break
case 'rebuilt':
run(() => entries.reload(frame.id, frame.rev))
break
default:
// Forward compatibility: a newer Host's increment type is ignored.
break
}
},
failed: (error) => { ctx.logger.error('client-hmr: plugin events stopped; client graph changes stop until the page reloads', error) },
}
ctx.effect(() => {
const transport = (globalThis as PageTransportGlobal).__DSH_TRANSPORT__
if (transport?.fetch !== undefined) {
const controller = new AbortController()
void readPageTransportEvents(transport.fetch, controller.signal, receive).catch((error: unknown) => {
if (!controller.signal.aborted) ctx.logger.error(error)
})
return () => { controller.abort() }
}
const source = new EventSource(EVENTS_ROUTE)
source.addEventListener('message', (event: MessageEvent<string>) => { receive(event.data) })
return () => { source.close() }
}, 'client-hmr: event source')
ctx.remoteAccess.whenAccess('pluginEvents/follow', () => followPluginEvents(ctx, sinks))
return unmount
}
-50
View File
@@ -1,50 +0,0 @@
/**
* Wire protocol of the `/plugins/events` SSE channel — single source for
* both halves of this package. Frames still cross a wire boundary: the
* browser half validates them at its JSON parse point; sharing the type keeps
* the two ends from drifting, not from parsing.
*/
import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules'
/** One SSE frame: the settled graph on connection or change, or one rebuilt bundle notice. */
export type PluginsEventFrame =
| { type: 'graph'; graph: WebBootGraph }
| { type: 'rebuilt'; id: string; rev: string }
/** Browser wire-parse result: known frame, forward-compatible unknown type, or malformed payload. */
export type PluginsEventParseResult =
| { kind: 'frame'; frame: { type: 'graph'; graph: unknown } | Extract<PluginsEventFrame, { type: 'rebuilt' }> }
| { kind: 'unknown' }
| { kind: 'invalid' }
/**
* Validate the frame envelope; the module controller parses the complete graph before updating its index.
* @param value - Parsed JSON value from the EventSource message.
* @returns the known frame, an unknown-type marker, or an invalid marker.
*/
export function parsePluginsEventFrame(value: unknown): PluginsEventParseResult {
if (typeof value !== 'object' || value === null) return { kind: 'invalid' }
const record = value as Record<string, unknown>
switch (record.type) {
case 'rebuilt':
return typeof record.id === 'string' && typeof record.rev === 'string'
? { kind: 'frame', frame: { type: 'rebuilt', id: record.id, rev: record.rev } }
: { kind: 'invalid' }
case 'graph':
return typeof record.graph === 'object' && record.graph !== null
? { kind: 'frame', frame: { type: 'graph', graph: record.graph } }
: { kind: 'invalid' }
default:
return typeof record.type === 'string' ? { kind: 'unknown' } : { kind: 'invalid' }
}
}
/** System SSE endpoint pushing graph/rebuilt frames (wire protocol constant). */
export const EVENTS_ENDPOINT = '/plugins/events'
/**
* Document-relative form of {@link EVENTS_ENDPOINT} used by the browser half.
* See .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
*/
export const EVENTS_ROUTE = EVENTS_ENDPOINT.slice(1)
+10 -69
View File
@@ -1,30 +1,26 @@
/**
* Host transport for Web client graph changes and rebuilt bundles. One interval
* stat-polls every graph row's client bundle (polling by design: network mounts
* deliver no inotify events), reports changes through
* `clientModules.rebuilt(id)`, and serves the `/plugins/events` SSE channel
* broadcasting graph/rebuilt frames to the browser half (src/client/).
* deliver no inotify events) and reports changes through
* `clientModules.rebuilt(id)`; the `pluginEvents` Remote stream delivers graph,
* rebuild, and synced configuration changes to the browser half (src/client/).
* The Web composition mounts this transport for live graph updates;
* a development rebuild watcher also supplies bundle changes.
*/
import { statSync } from 'node:fs'
import type { ServerResponse } from 'node:http'
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
// Type imports carry the clientModules/webServer Context merges.
// Type import carries the clientModules Context merge.
import type { ClientArtifactBaseline } from '@deepseek-ai/dsh-client-modules'
import type {} from '@deepseek-ai/dsh-host-webserver'
import type { PluginsEventFrame } from './events.ts'
import { EVENTS_ENDPOINT } from './events.ts'
import { PluginEvents } from './plugin-events.ts'
export type { PluginsEventFrame } from './events.ts'
export { EVENTS_ENDPOINT } from './events.ts'
export type * from './types.ts'
/** Cordis plugin name. */
export const name = 'client-hmr'
/** Required services: the client graph and Web route registry. */
export const inject = ['clientModules', 'webServer']
/** Required service: the client graph. */
export const inject = ['clientModules']
/** Plugin config, validated by the same-named schemastery schema. */
export interface Config {
@@ -36,11 +32,6 @@ export const Config: z<Config> = z.object({
pollIntervalMs: z.number().step(1).min(1).default(500),
})
/** Serialize one frame as an SSE data line. */
function sseData(frame: PluginsEventFrame): string {
return `data: ${JSON.stringify(frame)}\n\n`
}
type WatchedBundleStat = Omit<ClientArtifactBaseline, 'path'>
type WatchedBundle = {
@@ -61,7 +52,7 @@ function sameBundleStat(left: WatchedBundleStat, right: WatchedBundleStat): bool
}
/**
* Mount bundle watches and graph/rebuilt SSE delivery.
* Mount bundle watches and the plugin-events Remote service.
* @param ctx - host plugin context carrying clientModules and webServer.
* @param config - validated {@link Config}.
*/
@@ -155,55 +146,5 @@ export function apply(ctx: Context, config: Config): void {
}
}, 'client-hmr: bundle watches')
// --- /plugins/events SSE channel ----------------------------------------
const connections = new Set<ServerResponse>()
const publishGraph = (): void => {
const line = sseData({ type: 'graph', graph: ctx.clientModules.graph() })
for (const res of connections) res.write(line)
}
const connect = (res: ServerResponse): void => {
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
'connection': 'keep-alive',
})
// Comment line on open so clients/proxies see a live channel even when
// no rebuild ever happens; EventSource frame parsing skips it naturally.
res.write(': connected\n\n')
connections.add(res)
res.write(sseData({ type: 'graph', graph: ctx.clientModules.graph() }))
res.on('close', () => { connections.delete(res) })
}
ctx.effect(() => {
const disposeRoute = ctx.webServer.register({
kind: 'exact',
path: EVENTS_ENDPOINT,
auth: 'anonymous',
handler: (req, res) => {
// Named routes match ahead of the carrier's method gate; keep the old
// global 405 semantics for non-GET hits on this endpoint.
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405)
res.end()
return
}
connect(res)
},
})
const unsubscribeGraph = ctx.clientModules.onGraphChanged(publishGraph)
const unsubscribe = ctx.clientModules.onRebuilt((id, rev) => {
const line = sseData({ type: 'rebuilt', id, rev })
for (const res of connections) res.write(line)
})
return () => {
unsubscribeGraph()
unsubscribe()
disposeRoute()
for (const res of connections) res.destroy()
connections.clear()
}
}, 'client-hmr: /plugins/events channel')
ctx.plugin(PluginEvents)
}
+101
View File
@@ -0,0 +1,101 @@
/** Host `pluginEvents` Remote service: an authenticated baseline-and-increment stream of graph and rebuild changes. */
import type { Context } from '@deepseek-ai/cordis'
import { Deque } from '@deepseek-ai/dsh-deque'
import { principalOf, Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import type {} from '@deepseek-ai/dsh-client-modules'
import type { PluginsEventFrame, PluginsEventIncrement } from './types.ts'
/** Ordered increments of one stream generation; closing wakes the waiting reader. */
class Follower {
private readonly frames = new Deque<PluginsEventIncrement>()
private wake: (() => void) | undefined
closed = false
/** @param principal - the calling Peer's principal; undefined for the owner. */
constructor(readonly principal: Principal | undefined) {}
push(frame: PluginsEventIncrement): void {
this.frames.pushBack(frame)
this.wake?.()
}
close(): void {
this.closed = true
this.wake?.()
}
/** @returns the oldest queued increment, if any. */
take(): PluginsEventIncrement | undefined {
return this.frames.popFront()
}
/** @returns a promise settled by the next push or close. */
wait(): Promise<void> {
return new Promise<void>((resolve) => { this.wake = resolve })
}
}
/**
* Streams start from the current graph; listeners attach before the baseline is read. Every Peer the Remote access
* policies admit may follow; each frame carries the graph as that Peer may see it, so only the owner receives configured
* synced values and every other Peer receives schema defaults.
*/
export class PluginEvents extends TypertRemoteService {
static inject = ['clientModules']
private readonly followers = new Set<Follower>()
/** @param ctx - Host context with the Web client graph. */
constructor(ctx: Context) {
super(ctx, 'pluginEvents', { namespace: 'pluginEvents' })
ctx.effect(() => {
const offGraph = ctx.clientModules.onGraphChanged(() => { this.publishGraph() })
const offRebuilt = ctx.clientModules.onRebuilt((id, rev) => { this.publish({ type: 'rebuilt', id, rev }) })
return () => {
offGraph()
offRebuilt()
for (const follower of this.followers) follower.close()
this.followers.clear()
}
}, 'client-hmr: plugin event followers')
}
/**
* Follow Web client graph and rebuild changes; every generation starts with a complete baseline.
* @param signal - generation cancellation.
* @returns the baseline followed by ordered increments; the stream ends when the service unloads.
*/
@Remote({ mode: 'stream' })
async *follow(signal: AbortSignal): AsyncIterable<PluginsEventFrame> {
signal.throwIfAborted()
const follower = new Follower(principalOf(this.ctx.invocation))
this.followers.add(follower)
const abort = (): void => { follower.close() }
signal.addEventListener('abort', abort, { once: true })
try {
yield { type: 'baseline', graph: this.ctx.clientModules.graphFor(follower.principal) }
// The increments are yielded from this generator itself, with no delegated generator adding a step before each
// reaches the Gateway's write queue.
while (!follower.closed) {
const frame = follower.take()
if (frame !== undefined) yield frame
else await follower.wait()
}
} finally {
signal.removeEventListener('abort', abort)
this.followers.delete(follower)
follower.close()
}
}
private publish(frame: PluginsEventIncrement): void {
for (const follower of this.followers) follower.push(frame)
}
private publishGraph(): void {
for (const follower of this.followers) follower.push({ type: 'graph', graph: this.ctx.clientModules.graphFor(follower.principal) })
}
}
export default PluginEvents
+22
View File
@@ -0,0 +1,22 @@
/**
* Wire protocol of the `pluginEvents/follow` Remote stream, shared by both faces. Each stream generation opens with
* one `baseline` frame holding the complete graph, including each row's synced configuration, followed by increments.
*/
import type { WebBootGraph } from '@deepseek-ai/dsh-client-modules/types'
/** Complete state opening every stream generation. */
export interface PluginsEventBaseline {
type: 'baseline'
/** Current Web client graph. */
graph: WebBootGraph
}
/** One increment after the baseline. */
export type PluginsEventIncrement =
/** The graph after a structural or synced configuration change. */
| { type: 'graph'; graph: WebBootGraph }
/** One rebuilt bundle. */
| { type: 'rebuilt'; id: string; rev: string }
/** Every frame of the stream. */
export type PluginsEventFrame = PluginsEventBaseline | PluginsEventIncrement
@@ -1,23 +0,0 @@
import { describe, expect, it } from 'vitest'
import { parsePluginsEventFrame } from '../src/events.ts'
describe('plugin event wire parser', () => {
it('accepts complete rebuilt and graph frames', () => {
expect(parsePluginsEventFrame({ type: 'rebuilt', id: 'plugin', rev: 'next' })).toEqual({
kind: 'frame',
frame: { type: 'rebuilt', id: 'plugin', rev: 'next' },
})
const graph = { rev: 'graph', entries: [], batches: [] }
expect(parsePluginsEventFrame({ type: 'graph', graph })).toEqual({
kind: 'frame',
frame: { type: 'graph', graph },
})
})
it('separates forward-compatible unknown types from malformed known frames', () => {
expect(parsePluginsEventFrame({ type: 'future', payload: true })).toEqual({ kind: 'unknown' })
for (const value of [null, [], {}, { type: 'rebuilt', id: 'plugin' }, { type: 'graph', graph: null }]) {
expect(parsePluginsEventFrame(value)).toEqual({ kind: 'invalid' })
}
})
})
@@ -0,0 +1,26 @@
/**
* Resolvable stand-in for the generated `./remote` contribution when this package has no built `lib/`.
* It declares the one stream endpoint the Client face mounts, so whole-client specs exercise the real
* `$mount` path; its item schema accepts any JSON value instead of the generated frame validation.
*/
import { createTypertRemoteInfo } from '@deepseek-ai/dsh-typert-protocol/remote-info'
import { z } from 'zod'
export default createTypertRemoteInfo({
package: '@deepseek-ai/dsh-client-hmr',
methods: {
'pluginEvents/follow': {
service: 'pluginEvents',
mode: 'stream',
invocation: { kind: 'direct' },
parameters: [],
cancellation: { parameter: 'signal' },
result: {
mode: 'strict',
typeSymbol: '@deepseek-ai/dsh-client-hmr/types#PluginsEventFrame',
create: () => z.json(),
jsonSchema: {},
},
},
},
}, z)
@@ -1,18 +1,15 @@
/**
* Node half of the HMR plugin: bundle watches follow the graph, stat changes
* report through clientModuleHost.rebuilt, and everything dies with the fiber.
* report through clientModuleHost.rebuilt, and everything dies with the fiber,
* including the plugin-events Remote service.
*/
import { EventEmitter } from 'node:events'
import type { ServerResponse, IncomingMessage } from 'node:http'
import { mkdtempSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import { Context } from '@deepseek-ai/cordis'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ClientArtifactBaseline, ClientModuleRegistry, WebBootGraph } from '@deepseek-ai/dsh-client-modules'
import type { WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver'
import { apply, Config, EVENTS_ENDPOINT, inject } from '../src/index.ts'
import { apply, Config, inject } from '../src/index.ts'
const POLL_MS = 20
@@ -75,24 +72,9 @@ function fakeClientModuleHost(rows: Map<string, string>, options: FakeHostOption
return fake as FakeHost
}
// Structural fake: the plugin only touches register(); the service class
// carries private state a literal cannot (and need not) reproduce.
function fakeHttpServer(routes: WebRoute[]): WebServer {
const fake: Pick<WebServer, 'register' | 'tapIndex' | 'port'> = {
register(route: WebRoute) {
routes.push(route)
return () => { routes.splice(routes.indexOf(route), 1) }
},
tapIndex: () => () => {},
port: 0,
}
return fake as WebServer
}
async function mount(clientModuleHost: FakeHost, webServer: WebServer) {
async function mount(clientModuleHost: FakeHost) {
const ctx = new Context()
ctx.provide('clientModules', clientModuleHost)
ctx.provide('webServer', webServer)
const fiber = ctx.plugin(
{ inject: [...inject], Config, apply },
{ pollIntervalMs: POLL_MS },
@@ -106,11 +88,9 @@ describe('hmr node half', () => {
const bundle = join(dir, 'a.js')
writeFileSync(bundle, 'v1')
const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]))
const routes: WebRoute[] = []
const fiber = await mount(clientModuleHost, fakeHttpServer(routes))
const fiber = await mount(clientModuleHost)
expect(routes).toHaveLength(1)
expect(routes[0]).toMatchObject({ kind: 'exact', path: EVENTS_ENDPOINT })
expect(fiber.ctx.get('pluginEvents')).toBeDefined()
expect(clientModuleHost.rebuiltCalls).toEqual([])
// Nudge mtime past stat granularity so the poller sees a content signal.
@@ -128,7 +108,7 @@ describe('hmr node half', () => {
await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toContain('pkg-a') }, { timeout: 3_000 })
await fiber.dispose()
expect(routes).toHaveLength(0)
expect(fiber.ctx.get('pluginEvents')).toBeUndefined()
// Watcher gone: further file changes report nothing.
clientModuleHost.rebuiltCalls.length = 0
writeFileSync(bundle, 'v4-after-dispose')
@@ -142,7 +122,7 @@ describe('hmr node half', () => {
writeFileSync(early, 'v1')
const rows = new Map([['pkg-early', early]])
const clientModuleHost = fakeClientModuleHost(rows)
const fiber = await mount(clientModuleHost, fakeHttpServer([]))
const fiber = await mount(clientModuleHost)
clientModuleHost.rebuiltCalls.length = 0
writeFileSync(late, 'v1')
@@ -175,7 +155,7 @@ describe('hmr node half', () => {
},
})
const fiber = await mount(clientModuleHost, fakeHttpServer([]))
const fiber = await mount(clientModuleHost)
expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a'])
clientModuleHost.rebuiltCalls.length = 0
@@ -191,7 +171,7 @@ describe('hmr node half', () => {
utimesSync(bundle, fixedTime, fixedTime)
const baseline = statSync(bundle)
const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]))
const fiber = await mount(clientModuleHost, fakeHttpServer([]))
const fiber = await mount(clientModuleHost)
try {
expect(clientModuleHost.rebuiltCalls).toEqual([])
// Filesystem ctime can advance more coarsely than Date.now(); the fixture needs a distinct value.
@@ -214,7 +194,7 @@ describe('hmr node half', () => {
utimesSync(bundle, fixedTime, fixedTime)
const baseline = statSync(bundle)
const clientModuleHost = fakeClientModuleHost(new Map([['pkg-a', bundle]]))
const fiber = await mount(clientModuleHost, fakeHttpServer([]))
const fiber = await mount(clientModuleHost)
clientModuleHost.rebuiltCalls.length = 0
unlinkSync(bundle)
@@ -246,94 +226,9 @@ describe('hmr node half', () => {
},
})
const fiber = await mount(clientModuleHost, fakeHttpServer([]))
const fiber = await mount(clientModuleHost)
await vi.waitFor(() => { expect(clientModuleHost.rebuiltCalls).toEqual(['pkg-a', 'pkg-a']) }, { timeout: 3_000 })
await fiber.dispose()
})
})
it('broadcasts the desired graph without waiting for Host activation or cleanup', async () => {
const ctx = new Context()
await ctx.plugin(Loader)
const bundle = join(dir, 'a.js')
writeFileSync(bundle, 'a')
const rows = new Map([['a', bundle]])
const host = fakeClientModuleHost(rows)
const routes: WebRoute[] = []
ctx.provide('clientModules', host)
ctx.provide('webServer', fakeHttpServer(routes))
let release!: () => void
let cleaned!: () => void
let started!: () => void
const starting = new Promise<void>((resolve) => { started = resolve })
const activation = new Promise<void>((resolve) => { release = resolve })
const cleanup = new Promise<void>((resolve) => { cleaned = resolve })
let disposed = false
ctx.loader.internal = { version: 'client', import: async () => ({
apply: async (pluginCtx: Context) => {
pluginCtx.effect(() => async () => { await cleanup; disposed = true })
started()
await activation
},
}) } as never
const entryId = await ctx.loader.create({ name: 'owned' })
await starting
const fiber = ctx.plugin({ inject, Config, apply }, { pollIntervalMs: POLL_MS })
await fiber.await()
const route = routes[0]!
const connect = async () => {
const lines: string[] = []
const response = Object.assign(new EventEmitter(), {
writeHead: vi.fn(), write: (line: string) => { lines.push(line) },
destroy: vi.fn(), end: vi.fn(),
})
await route.handler({ method: 'GET' } as IncomingMessage, response as unknown as ServerResponse)
return { lines, response }
}
try {
const first = await connect()
expect(first.lines).toHaveLength(2)
const frame = JSON.parse(first.lines[1]!.slice(6)) as { graph: WebBootGraph }
expect(frame.graph.entries.map(row => row.id)).toEqual(['a'])
const second = await connect()
expect(second.lines[1]).toBe(first.lines[1])
expect(first.lines).toHaveLength(2)
release()
const owned = ctx.loader.resolve(entryId).fiber!
await owned.await()
const child = owned.ctx.plugin({ apply() {} })
await child.await()
expect(child.entry).toBe(owned.entry)
await child.dispose()
await child.await()
await ctx.loader.await()
await new Promise<void>(resolve => setImmediate(resolve))
expect(second.lines).toHaveLength(2)
first.response.emit('close')
ctx.loader.remove(entryId)
rows.clear()
host.fireGraphChanged()
expect(second.lines).toHaveLength(3)
expect(disposed).toBe(false)
expect((JSON.parse(second.lines[2]!.slice(6)) as { graph: WebBootGraph }).graph.entries).toEqual([])
const third = await connect()
expect(third.lines[1]).toBe(second.lines[2])
expect(second.lines).toHaveLength(3)
cleaned()
while (owned.inertia !== undefined) await owned.inertia
expect(disposed).toBe(true)
expect(second.lines).toHaveLength(3)
await fiber.dispose()
host.fireGraphChanged()
expect(second.lines).toHaveLength(3)
expect(second.response.destroy).toHaveBeenCalledOnce()
expect(third.response.destroy).toHaveBeenCalledOnce()
} finally {
release()
cleaned()
await fiber.dispose()
await ctx.fiber.dispose()
}
})
@@ -0,0 +1,101 @@
/** The plugin-events Remote stream opens each generation with a complete baseline and then forwards ordered increments. */
import { Context } from '@deepseek-ai/cordis'
import { afterEach, expect, it } from 'vitest'
import type { ClientModuleRegistry, WebBootGraph } from '@deepseek-ai/dsh-client-modules'
import { PluginEvents } from '../src/plugin-events.ts'
import type { PluginsEventFrame } from '../src/types.ts'
const roots: Context[] = []
afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) })
function graph(rev: string, config = 'configured'): WebBootGraph {
return { rev, entries: [{ id: 'a', url: 'a.js', rev, config: { value: config } }], batches: [] }
}
/** Structural fake: the service reads only these members. */
async function harness() {
const ctx = new Context()
roots.push(ctx)
let current = graph('g1')
const graphListeners = new Set<() => void>()
const rebuiltListeners = new Set<(id: string, rev: string) => void>()
const modules: Pick<ClientModuleRegistry, 'graph' | 'graphFor' | 'onGraphChanged' | 'onRebuilt'> = {
graph: () => current,
graphFor: principal => principal === undefined ? current : graph(current.rev, 'default'),
onGraphChanged: (listener) => { graphListeners.add(listener); return () => { graphListeners.delete(listener) } },
onRebuilt: (listener) => { rebuiltListeners.add(listener); return () => { rebuiltListeners.delete(listener) } },
}
ctx.provide('clientModules', modules as ClientModuleRegistry)
const fiber = ctx.plugin(PluginEvents)
await fiber.await()
// No Context merge is declared for the service; its Remote namespace is the public face.
const service = ctx.get('pluginEvents') as PluginEvents
return {
fiber,
follow: (signal: AbortSignal) => service.follow(signal)[Symbol.asyncIterator](),
/** Follow as the Remote call of one non-owner Peer. */
followAs: (kind: string, signal: AbortSignal) => {
const invocation = { peer: { principal: { kind } } }
return (ctx.extend({ invocation }).get('pluginEvents') as PluginEvents).follow(signal)[Symbol.asyncIterator]()
},
setGraph(next: WebBootGraph) { current = next; for (const listener of graphListeners) listener() },
rebuilt(id: string, rev: string) { for (const listener of rebuiltListeners) listener(id, rev) },
listeners: () => graphListeners.size + rebuiltListeners.size,
}
}
async function take(iterator: AsyncIterator<PluginsEventFrame>, count: number): Promise<PluginsEventFrame[]> {
const frames: PluginsEventFrame[] = []
for (let index = 0; index < count; index++) {
const next = await iterator.next()
if (next.done === true) break
frames.push(next.value)
}
return frames
}
it('sends a baseline, then graph and rebuilt increments in order', async () => {
const h = await harness()
const controller = new AbortController()
const iterator = h.follow(controller.signal)
expect(await take(iterator, 1)).toEqual([{ type: 'baseline', graph: graph('g1') }])
h.setGraph(graph('g2'))
h.rebuilt('a', 'r2')
expect(await take(iterator, 2)).toEqual([
{ type: 'graph', graph: graph('g2') },
{ type: 'rebuilt', id: 'a', rev: 'r2' },
])
controller.abort()
expect(await iterator.next()).toEqual({ done: true, value: undefined })
})
it('ends open streams and releases its listeners when unloaded', async () => {
const h = await harness()
const iterator = h.follow(new AbortController().signal)
await take(iterator, 1)
const pending = iterator.next()
await h.fiber.dispose()
expect(await pending).toEqual({ done: true, value: undefined })
expect(h.listeners()).toBe(0)
})
it('rejects a follow whose signal is already aborted', async () => {
const h = await harness()
const controller = new AbortController()
controller.abort()
await expect(h.follow(controller.signal).next()).rejects.toThrow()
})
it('sends a non-owner Peer the graph with schema defaults while the owner receives configured values', async () => {
const h = await harness()
const controller = new AbortController()
const owner = h.follow(controller.signal)
const viewer = h.followAs('viewer', controller.signal)
expect(await take(owner, 1)).toEqual([{ type: 'baseline', graph: graph('g1') }])
expect(await take(viewer, 1)).toEqual([{ type: 'baseline', graph: graph('g1', 'default') }])
h.setGraph(graph('g2'))
h.rebuilt('a', 'r2')
expect(await take(owner, 2)).toEqual([{ type: 'graph', graph: graph('g2') }, { type: 'rebuilt', id: 'a', rev: 'r2' }])
expect(await take(viewer, 2)).toEqual([{ type: 'graph', graph: graph('g2', 'default') }, { type: 'rebuilt', id: 'a', rev: 'r2' }])
controller.abort()
})
+125 -112
View File
@@ -1,127 +1,140 @@
/** Web transport delegates module and entry changes to the page-owned controller. */
/** The Web transport follows the plugin-events Remote stream into the page's entry controller. */
import { Context } from '@deepseek-ai/cordis'
import type { ClientModuleLoader } from '@deepseek-ai/dsh-client-modules/client'
import { afterEach, expect, it, vi } from 'vitest'
import { apply, inject } from '../src/client/index.ts'
import type { PluginsEventFrame } from '../src/types.ts'
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
afterEach(() => { vi.restoreAllMocks() })
/** Provide the module system face this transport drives: its entry controller's sync and reload. */
function provideModules(ctx: Context, sync: (...args: never[]) => unknown, reload: (...args: never[]) => unknown): void {
ctx.provide('modules', { entries: { sync, reload } } as unknown as ClientModuleLoader)
async function collect(items: AsyncIterable<unknown>): Promise<unknown[]> {
const out: unknown[] = []
for await (const item of items) out.push(item)
return out
}
it('forwards full graphs and rebuilt frames, contains wire errors and closes its EventSource', async () => {
const ctx = new Context()
const sync = vi.fn(async () => {})
const reload = vi.fn(async () => {})
provideModules(ctx, sync, reload)
const warnings = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
let receive!: (event: { data: string }) => void
const close = vi.fn()
vi.stubGlobal('EventSource', class {
close = close
addEventListener(_name: string, listener: typeof receive) { receive = listener }
})
const fiber = ctx.plugin({ apply, inject })
try {
await fiber.await()
const graph = { rev: 'r', entries: [], batches: [] }
receive({ data: JSON.stringify({ type: 'graph', graph }) })
receive({ data: JSON.stringify({ type: 'rebuilt', id: 'a', rev: 'r1' }) })
await vi.waitFor(() => { expect(sync).toHaveBeenCalledWith(graph) })
expect(reload).toHaveBeenCalledWith('a', 'r1')
receive({ data: '{' })
receive({ data: JSON.stringify({ type: 'graph', graph: null }) })
receive({ data: JSON.stringify({ type: 'future' }) })
expect(warnings).toHaveBeenCalledTimes(2)
sync.mockRejectedValueOnce(new Error('invalid graph'))
receive({ data: JSON.stringify({ type: 'graph', graph: {} }) })
await vi.waitFor(() => { expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: 'invalid graph' })) })
} finally {
await fiber.dispose()
await ctx.fiber.dispose()
/** A pushable stand-in for one logical Remote stream: items carry a generation number and an accept callback. */
function fakeStream() {
const queue: { generation: number; value: PluginsEventFrame }[] = []
let wake: (() => void) | undefined
let ended = false
const disposed = vi.fn()
const stream = {
async *[Symbol.asyncIterator]() {
while (!ended) {
const item = queue.shift()
if (item === undefined) {
await new Promise<void>((resolve) => { wake = resolve })
continue
}
yield { ...item, signal: new AbortController().signal, accept: () => {} }
}
},
restart: () => {},
dispose: async () => { disposed(); ended = true; wake?.() },
}
expect(close).toHaveBeenCalledOnce()
})
it('reads the event stream through the page transport when the shell provides one', async () => {
const ctx = new Context()
const sync = vi.fn(async () => {})
const reload = vi.fn(async () => {})
provideModules(ctx, sync, reload)
const graph = { rev: 'r', entries: [], batches: [] }
const encoder = new TextEncoder()
let signal: AbortSignal | undefined
const fetch = vi.fn((_input: string, init: RequestInit) => {
signal = init.signal ?? undefined
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode(': connected\n\n'))
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'graph', graph })}\n\n`))
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'rebuilt', id: 'a', rev: 'r1' })}\n\n`))
// The tunnel ends the body when the caller aborts.
init.signal?.addEventListener('abort', () => { controller.close() })
},
})
return Promise.resolve(new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } }))
})
vi.stubGlobal('__DSH_TRANSPORT__', { fetch })
const eventSource = vi.fn()
vi.stubGlobal('EventSource', eventSource)
const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
const fiber = ctx.plugin({ apply, inject })
try {
await fiber.await()
await vi.waitFor(() => { expect(sync).toHaveBeenCalledWith(graph) })
await vi.waitFor(() => { expect(reload).toHaveBeenCalledWith('a', 'r1') })
expect(fetch).toHaveBeenCalledWith('plugins/events', expect.objectContaining({ method: 'GET' }))
expect(eventSource).not.toHaveBeenCalled()
expect(signal?.aborted).toBe(false)
} finally {
await fiber.dispose()
await ctx.fiber.dispose()
return {
stream,
disposed,
push(generation: number, value: PluginsEventFrame) { queue.push({ generation, value }); wake?.() },
}
expect(signal?.aborted).toBe(true)
await Promise.resolve()
expect(errors).not.toHaveBeenCalled()
})
}
it.each([
['a refused stream', () => new Response('missing', { status: 404 }), 'plugins/events answered 404'],
['a stream without a body', () => new Response(null, { status: 200 }), 'plugins/events answered 200'],
['a stream that ends while the plugin runs', () => new Response(': connected\n\n', { status: 200 }), 'plugins/events closed'],
])('reports %s on the page transport', async (_label, respond, message) => {
function harness() {
const ctx = new Context()
provideModules(ctx, vi.fn(), vi.fn())
const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
vi.stubGlobal('__DSH_TRANSPORT__', { fetch: () => Promise.resolve(respond()) })
const fiber = ctx.plugin({ apply, inject })
try {
await fiber.await()
await vi.waitFor(() => {
expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining(message) as string }))
})
} finally {
await fiber.dispose()
await ctx.fiber.dispose()
}
})
const sync = vi.fn(async (_graph: unknown) => {})
const reload = vi.fn(async (_id: string, _rev: string) => {})
ctx.provide('modules', { entries: { sync, reload } } as never)
const stream = fakeStream()
const unmount = vi.fn(async () => {})
const opened: { name: string; open: (signal: AbortSignal) => AsyncIterable<unknown>; ended: () => Error & { code?: string } }[] = []
const follow = vi.fn(async function *(_signal: AbortSignal): AsyncIterable<unknown> { yield 'frame' })
const pluginEvents = { follow }
ctx.provide('remote', {
$mount: vi.fn(async () => unmount),
$stream: (streamOptions: (typeof opened)[number]) => { opened.push(streamOptions); return stream.stream },
pluginEvents,
} as never)
const revoke: (() => unknown)[] = []
ctx.provide('remoteAccess', {
whenAccess: (_action: string, callback: () => () => unknown) => { revoke.push(callback()); return () => {} },
} as never)
// `$mount` provides the generated namespace as its own service under `remote.pluginEvents`.
const provideNamespace = (): void => { ctx.provide('remote.pluginEvents', pluginEvents as never) }
return { ctx, sync, reload, stream, unmount, opened, follow, revoke, provideNamespace }
}
it('stays silent when disposal aborts a page-transport request in flight', async () => {
const ctx = new Context()
provideModules(ctx, vi.fn(), vi.fn())
const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
const fetch = vi.fn((_input: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
init.signal?.addEventListener('abort', () => { reject(new DOMException('aborted', 'AbortError')) })
}))
vi.stubGlobal('__DSH_TRANSPORT__', { fetch })
const fiber = ctx.plugin({ apply, inject })
const baseline: PluginsEventFrame = { type: 'baseline', graph: { rev: 'g1', entries: [], batches: [] } }
it('forwards the baseline and increments to the entry controller while access allows the stream, and unmounts its namespace', async () => {
const h = harness()
h.provideNamespace()
const fiber = h.ctx.plugin({ apply, inject })
await fiber.await()
await vi.waitFor(() => { expect(fetch).toHaveBeenCalledOnce() })
const options = h.opened[0]!
expect(options.name).toBe('Plugin events')
const signal = new AbortController().signal
expect(await collect(options.open(signal))).toEqual(['frame'])
expect(h.follow).toHaveBeenCalledWith(signal)
// An endpoint the Host withdrew while reloading reconnects; any other failure stays as it is.
for (const code of ['gateway/invocation-unavailable', 'gateway/service-unavailable']) {
h.follow.mockImplementationOnce(() => { throw Object.assign(new Error('withdrawn'), { code }) })
await expect(collect(options.open(signal))).rejects.toMatchObject({ code: 'gateway/carrier-lost' })
}
const denied = Object.assign(new Error('denied'), { code: 'gateway/forbidden' })
h.follow.mockImplementationOnce(() => { throw denied })
await expect(collect(options.open(signal))).rejects.toBe(denied)
const plain = new Error('plain')
h.follow.mockImplementationOnce(() => { throw plain })
await expect(collect(options.open(signal))).rejects.toBe(plain)
// A normal generation end reconnects rather than ending the logical stream.
expect(options.ended().code).toBe('gateway/carrier-lost')
h.stream.push(1, baseline)
h.stream.push(1, { type: 'graph', graph: { rev: 'g2', entries: [], batches: [] } })
h.stream.push(1, { type: 'rebuilt', id: 'a', rev: 'r2' })
await vi.waitFor(() => { expect(h.reload).toHaveBeenCalledWith('a', 'r2') })
expect(h.sync.mock.calls.map(([graph]) => (graph as { rev: string }).rev)).toEqual(['g1', 'g2'])
await h.revoke[0]!()
expect(h.stream.disposed).toHaveBeenCalledOnce()
await fiber.dispose()
await ctx.fiber.dispose()
await Promise.resolve()
expect(errors).not.toHaveBeenCalled()
expect(h.unmount).toHaveBeenCalledOnce()
await h.ctx.fiber.dispose()
})
it('reports controller failures, including a synchronous parse failure, and ignores unknown increments', async () => {
const h = harness()
const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {})
h.sync.mockImplementationOnce(() => { throw new Error('bad graph') })
h.reload.mockRejectedValueOnce(new Error('bad reload'))
h.provideNamespace()
const fiber = h.ctx.plugin({ apply, inject })
await fiber.await()
h.stream.push(1, baseline)
h.stream.push(1, { type: 'future' } as never)
h.stream.push(1, { type: 'rebuilt', id: 'a', rev: 'r2' })
await vi.waitFor(() => { expect(errors).toHaveBeenCalledTimes(2) })
expect(errors.mock.calls.map(([error]) => (error as Error).message)).toEqual(['bad graph', 'bad reload'])
await fiber.dispose()
await h.ctx.fiber.dispose()
})
it('fails loudly when the mounted namespace service is missing', async () => {
const h = harness()
const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {})
const fiber = h.ctx.plugin({ apply, inject })
await expect(fiber.await()).rejects.toThrow('the mounted pluginEvents namespace is not registered')
errors.mockRestore()
await h.ctx.fiber.dispose()
})
it('logs a terminal stream failure', async () => {
const h = harness()
h.provideNamespace()
const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {})
const fiber = h.ctx.plugin({ apply, inject })
await fiber.await()
h.stream.push(1, { type: 'graph', graph: { rev: 'g', entries: [], batches: [] } })
await vi.waitFor(() => { expect(errors).toHaveBeenCalledOnce() })
expect(errors.mock.calls[0]![0]).toContain('plugin events stopped')
await fiber.dispose()
await h.ctx.fiber.dispose()
})
+26
View File
@@ -0,0 +1,26 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types",
"tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo"
},
"include": [
"src/client",
"src/types.ts"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../api/gateway/tsconfig.client.json"
},
{
"path": "../../api/remote-access/tsconfig.client.json"
},
{
"path": "../modules"
}
]
}
+30
View File
@@ -0,0 +1,30 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types",
"tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo"
},
"files": [
"src/index.ts",
"src/types.ts",
"src/plugin-events.ts"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../modules"
},
{
"path": "../../typert/protocol"
},
{
"path": "../../util/deque"
}
]
}
+3 -27
View File
@@ -1,35 +1,11 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types",
"lib": [
"ES2024",
"DOM",
"DOM.Iterable"
],
"types": [
"node"
]
},
"include": [
"src"
],
"files": [],
"references": [
{
"path": "../../../vendor/cordis"
"path": "./tsconfig.host.json"
},
{
"path": "../../../vendor/loader"
},
{
"path": "../modules"
},
{
"path": "../../host/webserver"
},
{
"path": "../../../vendor/schemastery"
"path": "./tsconfig.client.json"
}
]
}
+1 -1
View File
@@ -1,3 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true })
+9 -6
View File
@@ -27,8 +27,11 @@
en: 1383d68472b3c057
zh: 94dd7d9abbdbccf3
/deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition:
en: 4487b06ddced3b71
zh: 26d0181fcf0229ca
en: 09ed5277078f44ee
zh: 3643210476149b2a
/deepseek-ai-dsh-client-modules/use-this-package/synced-plugin-configuration:
en: ef9d9ee6fe9b7577
zh: cf09d615cb09df90
/deepseek-ai-dsh-client-modules/use-this-package/host-release-changes:
en: 5c0aa6f1d8df8e1c
zh: 34005131c9bdce3b
@@ -60,8 +63,8 @@
en: a0d8dbb15e079ec0
zh: 7d215cb85fa8b2c7
/deepseek-ai-dsh-client-modules/understand-the-implementation/source-map:
en: ece84808fa9f61f8
zh: 95a65a7adfca9146
en: fcd79e193d5f2857
zh: 1a7a9f67d7998561
/deepseek-ai-dsh-client-modules/further-exploration:
en: 7e5b283efe4f1d16
zh: 79472b64a0d759fe
@@ -72,8 +75,8 @@
en: ca75c51c89c2c9b0
zh: de54f3467ef3b9be
/deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work:
en: 97127ddc35daf6d4
zh: 1417b06046b01067
en: a33318c5e4558b13
zh: 438988c0c6c49e2e
/deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
+12 -2
View File
@@ -46,6 +46,13 @@ The application combo scripts carry only each plugin's `client.js` entry and reg
An open Web page follows the Host's complete module graph through the HMR transport. Enabling an ordinary plugin adds its Loader entry; disabling it removes the entry and waits for its asynchronous effects before evicting unused modules and styles. Re-enabling loads one instance with its styles. Other Loader contributors and shared modules still needed by active entries remain loaded. The Plugins page shows page-local synchronization failures and offers retry without changing Host enablement.
<a id="synced-plugin-configuration"></a>
### Synced plugin configuration
A plugin's top-level `.volatile()` Config fields reach its browser face. The package puts its Config interface in `src/types.ts` for both faces and keeps the only Schemastery schema on its Host face; ordinary fields and every `role('secret')` position, including positions inside a volatile object, dictionary, or array, stay on the Host. Each graph row carries the values in `config`, so they arrive with the boot graph and with every later graph. Only the owner's page receives the configured values; every other Peer, such as a LiveShare viewer, receives in the boot graph and in every plugin-events frame the values each plugin's schema resolves from an empty Config, and a row whose schema rejects an empty Config carries no values there.
The browser face exports no `Config`; its `apply(ctx, config: SyncedConfig<Config>)` receives one `SyncedConfigRef` per field, both from the types-only package [`@deepseek-ai/dsh-client-config/types`](../config/README.md). `config.field.get()` reads the current frozen value at operation time, as on the Host. A component reads it through a hook: the plugin injects the reference in a slot `inject` `hooks` compartment, such as `hooks: { fontSize: config.fontSize }`, and the component calls `useFontSize(value => value)`. Every field may read `undefined`, so the plugin handles the absent value at each read; a secret field is one case, as the Host never sends it. Changes compare each field as JSON; every changed field is set before any subscriber runs, and the plugin is never remounted. As each Host activation resolves its own volatile references, each plugin activation receives its own Config object holding the latest values; once its teardown begins (code replacement, row removal, or an unload after a required service is withdrawn) it receives no further values. A plugin without synced fields receives an empty object. `ctx.config.resolveConfigByPackage(packageName)` returns the read-only object of another package's current activation, or `undefined` while none runs. On the Host the graph frame carrying new values is queued before the plugin's own `loader/volatile-update` listeners run; this orders the mechanism only, and plugins must not rely on the browser receiving configuration before their other data. A Client face that exports its own `Config` schema keeps ordinary Cordis configuration and fails to activate when its row also carries synced values.
<a id="host-release-changes"></a>
### Host release changes
@@ -107,7 +114,10 @@ The host contributes structured index rows that inject, into `<head>`: the `wind
| [`src/assets.ts`](src/assets.ts) | Package-asset media types, export, content revision, revisioned file name, and browser reference shared by the build preset, the asset route, and gates |
| [`src/client/index.ts`](src/client/index.ts) | Browser half: bootstrap export, `ctx.modules` enrollment |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`: load/materialize/invalidate machinery |
| [`src/client/entries.ts`](src/client/entries.ts) | Page entry reconciliation, retries and code replacement |
| [`src/client/entries.ts`](src/client/entries.ts) | Page entry reconciliation, retries, code replacement, and synced Config delivery |
| [`src/client/synced-config.ts`](src/client/synced-config.ts) | The `SyncedConfigRef` implementation and the per-package synced Config object |
| [`src/config-projection.ts`](src/config-projection.ts) | Host projection of volatile Config fields with secrets removed |
| [`src/config-sync.ts`](src/config-sync.ts) | Host publication of each graph row's synced values and their `loader/volatile-update` watches |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | Loader fiber teardown through the registry |
| [`src/client/manifest.ts`](src/client/manifest.ts) | Wire types, boot-manifest parsing, and the `dsh.client` declaration parser |
@@ -146,7 +156,7 @@ These limits define what the module system does not do. They are current package
- **Metadata-based revisions** — revisions identify filesystem generations, not content equality. Metadata-only changes can reload a plugin; changes invisible in mtime, ctime, and size cannot be distinguished.
- **Flat module graph by design** — every bundle is one module node whose edges point only at table leaves; the interface (`loadCache`/`edges`/`invalidate`) already supports a general module graph, so the externalization granularity can change without an interface change.
- **Host release detection rides the graph stream** — a page learns another Host release only from a graph frame. When a restarting Host answers `/plugins/events` with a non-200 status before registering the route, the browser closes that stream for good, and the page neither updates plugins nor detects a release change until it reloads.
- **Host release detection rides the graph stream** — a page learns another Host release only from a graph frame of the [plugin-events stream](../hmr/README.md). While that stream cannot run, for example after a terminal stream failure, the page neither updates plugins nor detects a release change until it reloads.
- **Source launch has no build step for the Host half** — a Host started from TypeScript source reads the commit that `pnpm run dev:web` places in its environment; a source launch without it publishes the version alone.
- **Bootstrap and code replacement limits** — the page retains its modules bootstrap and static platform identities. Removing or replacing the bootstrap requires a page reload; live replacement requests report a page-local error while retaining its fiber and exports; replacing package code and all existing consumers is outside ordinary enable/disable synchronization.
- **Lazy delivery retains requested bodies** — the Host holds each bundle and lazy response plan; a script or map body remains cached after its first `GET`, and HMR additionally retains one prior startup generation. Memory grows only for response bodies that clients request while preserving one-generation race tolerance.
+12 -2
View File
@@ -46,6 +46,13 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启
已打开的 Web 页面通过 HMR 传输跟随 Host 的完整模块图。启用普通插件会添加其 Loader 条目;停用会移除条目,并在其异步 effect 完成清理后回收未使用的模块与样式。再次启用会加载一个带样式的实例。其他 Loader 贡献方的条目及活动条目仍需使用的共享模块会保留。插件页面显示当前页面的同步失败,并提供不改变 Host 启用状态的重试。
<a id="synced-plugin-configuration"></a>
### 同步插件配置
插件 Config 顶层的 `.volatile()` 字段会到达其浏览器面。包把 Config 接口放在 `src/types.ts` 供两个面共用,唯一的 Schemastery schema 只放在 Host 面;普通字段和所有 `role('secret')` 位置(包括 volatile 对象、字典、数组内部的位置)留在 Host。每个图行在 `config` 中携带这些值,因此它们随启动图和之后的每张图一起到达。只有 owner 的页面收到实际配置的值;其他所有 Peer(例如 LiveShare 查看端)在启动图和每个插件事件帧中收到各插件 schema 对空 Config 解析出的值,schema 拒绝空 Config 的行在这类页面上不带值。
浏览器面不导出 `Config`;它的 `apply(ctx, config: SyncedConfig<Config>)` 为每个字段收到一个 `SyncedConfigRef`,二者都来自只放类型的包 [`@deepseek-ai/dsh-client-config/types`](../config/README.zh.md)。`config.field.get()` 在执行操作时读取当前冻结值,写法与 Host 相同。组件通过 hook 读取:插件在 slot `inject` 的 `hooks` 中注入引用,例如 `hooks: { fontSize: config.fontSize }`,组件调用 `useFontSize(value => value)`。每个字段都可能读到 `undefined`,插件需在每次读取时处理缺值;密钥字段是其中一种情况,因为 Host 从不下发它。变化按字段做 JSON 比较,所有变化字段都设置完后才通知订阅者,插件从不重新挂载。与 Host 每次激活重新解析 volatile 引用一样,插件每次激活都得到一个持有最新值的新 Config 对象;该激活开始拆除后(代码替换、行移除,或必需服务撤回后的卸载)不再收到新值。没有同步字段的插件收到一个空对象。`ctx.config.resolveConfigByPackage(packageName)` 返回另一个包当前激活的只读对象,没有运行中的激活时返回 `undefined`。Host 上,携带新值的图帧在插件自己的 `loader/volatile-update` 监听执行之前入队;这只在机制上排序,插件不得依赖浏览器先收到配置、后收到其他数据。导出自身 `Config` schema 的 Client 面保持 Cordis 原有配置解析;其行若同时带同步值,激活失败。
<a id="host-release-changes"></a>
### Host release 变化
@@ -107,7 +114,10 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
| [`src/assets.ts`](src/assets.ts) | 包资源的媒体类型、导出、内容 revision、带 revision 的文件名与浏览器引用,由构建预设、资源路由和门禁共用 |
| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:bootstrap 导出、`ctx.modules` 登记 |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`:加载/物化/失效机制 |
| [`src/client/entries.ts`](src/client/entries.ts) | 页面条目对账、重试与代码替换 |
| [`src/client/entries.ts`](src/client/entries.ts) | 页面条目对账、重试、代码替换与同步 Config 交付 |
| [`src/client/synced-config.ts`](src/client/synced-config.ts) | `SyncedConfigRef` 的实现与每个包的同步 Config 对象 |
| [`src/config-projection.ts`](src/config-projection.ts) | Host 侧投影 volatile Config 字段并剔除密钥 |
| [`src/config-sync.ts`](src/config-sync.ts) | Host 侧发布每个图行的同步值,并监听其 `loader/volatile-update` |
| [`src/client/entry-lifecycle.ts`](src/client/entry-lifecycle.ts) | 通过注册表清理 Loader fiber |
| [`src/client/manifest.ts`](src/client/manifest.ts) | 协议类型、启动清单解析与 `dsh.client` 声明解析器 |
@@ -146,7 +156,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
- **基于元数据的 revision**——revision 标识文件系统代际,而非内容相等性。仅元数据变化也可能重载插件;mtime、ctime 和大小都无法反映的变化无法区分。
- **有意采用扁平模块图**——每个 bundle 是一个模块节点,其边只指向表中的叶节点;接口(`loadCache`/`edges`/`invalidate`)已经支持通用模块图,因此可以改变 externalization 粒度而不更改接口。
- **Host release 检测依赖图事件流**——页面只能从图帧得知 Host 换了 release。重启中的 Host 若在注册路由之前对 `/plugins/events` 返回非 200 状态,浏览器会永久关闭该事件流,页面在刷新前既不更新插件,也检测不到 release 变化。
- **Host release 检测依赖图事件流**——页面只能从[插件事件流](../hmr/README.zh.md)的图帧得知 Host 换了 release。该流无法运行时(例如流以终止性错误结束后),页面在刷新前既不更新插件,也检测不到 release 变化。
- **源码启动时 Host 半侧没有构建步骤**——从 TypeScript 源码启动的 Host 读取 `pnpm run dev:web` 放入其环境的 commit;没有该值的源码启动只发布版本号。
- **Bootstrap 与代码替换限制**——页面保留 modules bootstrap 和静态平台模块的身份。移除或替换 bootstrap 需要刷新页面;动态替换请求会报告页面本地错误,并保留其 fiber 与导出;替换包代码及其所有现有消费者不属于普通启停同步。
- **惰性提供会保留已请求的 body**——Host 在内存中保留每个 bundle 与惰性响应计划;脚本或 map body 在首次 `GET` 后保留缓存,HMR 还会保留上一代启动响应。内存仅随客户端实际请求的响应 body 增长,同时保留一代竞态容忍。
+8 -1
View File
@@ -18,6 +18,9 @@
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./types": {
"types": "./lib/types/types.d.ts"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
@@ -44,7 +47,11 @@
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-package-manifest": "workspace:*",
"@deepseek-ai/dsh-client-store": "workspace:*",
"@deepseek-ai/dsh-client-script-realm": "workspace:*"
"@deepseek-ai/dsh-client-script-realm": "workspace:*",
"@deepseek-ai/schemastery": "workspace:~",
"@deepseek-ai/dsh-util-values": "workspace:*",
"@deepseek-ai/dsh-client-config": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*"
},
"files": [
"locale/*.json",
@@ -7,6 +7,7 @@ import type { BootManifest, ClientModuleLoader } from './manifest.ts'
import { ReleaseChangeGate, type ClientReleaseChange } from './release-change.ts'
import { notifySubscribers } from './notify.ts'
import { tearDownEntryFiber } from './entry-lifecycle.ts'
import { SyncedConfigEntry } from './synced-config.ts'
/** Page-local failures do not change the Host's bundle enablement. */
export interface ClientEntryState {
@@ -51,6 +52,8 @@ export class ClientEntries {
/** Admits only Host graphs of the page's boot release. */
private readonly release: ReleaseChangeGate
private readonly managed = new Map<string, Entry>()
/** Latest synced values per package that has appeared in the graph, and the Config object of its current activation. */
private readonly synced = new Map<string, SyncedConfigEntry>()
private readonly revisions = new Map<string, string>()
private loader: Loader | undefined
private queue: Promise<void> = Promise.resolve()
@@ -90,6 +93,29 @@ export class ClientEntries {
if (this.loader !== undefined) throw new Error('client-modules: entries already started')
this.loader = loader
this.desired = manifest
this.applyConfig(manifest)
// Prepended so the Loader's interpolation runs inside this listener and cannot copy the returned object.
loader.ctx.on('internal/config', (fiber, next) => {
const config: unknown = next()
// As the Loader's own listener does, skip fibers that are not an entry's root plugin (a child plugin inherits
// its parent's entry) and keep their explicit config.
if (fiber.entry === undefined || fiber.parent.fiber.entry === fiber.entry) return config
const id = fiber.entry.options.name
const synced = this.synced.get(id)
if (synced === undefined) return config
// A Client face with its own schema keeps Cordis's ordinary configuration; it must not also receive synced values.
if (fiber.runtime?.Config === undefined) {
// Resolving a candidate for the running instance (as `fiber.update()` does) keeps its object, as the Host keeps
// an active instance's volatile references; only an activation receives a new one.
if (synced.config !== undefined && fiber.effectiveConfig === synced.config) return synced.config
const activation = synced.activate()
// However the instance unloads (replacement, removal, a withdrawn dependency), its object stops receiving values.
fiber.ctx.effect(() => () => { synced.release(activation) }, 'client-modules: synced configuration activation')
return activation
}
if (synced.empty) return config
throw new Error(`client-modules: the Client face of ${id} exports a Config schema; synced configuration requires the Host schema alone`)
}, { prepend: true })
loader.ctx.effect(() => () => {
this.stopped = true
this.generation++
@@ -116,6 +142,8 @@ export class ClientEntries {
const manifest = parseBootManifest(graph)
if (entryTargets(manifest) !== entryTargets(this.desired)) this.generation++
this.desired = manifest
// Configuration is not code: it applies at once, before queued entry work creates or replaces any entry.
if (this.loader !== undefined) this.applyConfig(manifest)
const generation = this.generation
return this.enqueue(() => this.reconcile(generation))
}
@@ -159,6 +187,34 @@ export class ClientEntries {
}, id)
}
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it.
* Each activation receives a new object, so the result changes when the plugin is replaced.
* @param packageName - graph row id.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage(packageName: string): object | undefined {
return this.synced.get(packageName)?.config
}
/** An activation's teardown begins: like a Host fiber that is no longer active, it receives no later values. */
private releaseConfig(id: string): void {
this.synced.get(id)?.release()
}
/**
* Write each row's values into its package's current activation. A row absent from the graph keeps its values: its
* entry is being removed, and removal releases the activation without writing to it.
*/
private applyConfig(manifest: BootManifest): void {
for (const row of manifest.plugins) {
const values = row.config ?? {}
const synced = this.synced.get(row.id)
if (synced === undefined) this.synced.set(row.id, new SyncedConfigEntry(values))
else synced.update(values)
}
}
private publish(snapshot: ClientEntryState): void {
this.snapshot = snapshot
notifySubscribers(this.listeners, 'synchronization')
@@ -195,6 +251,7 @@ export class ClientEntries {
this.index.invalidateForReplacement(id, rev)
await this.modules.prefetch(id)
if (!this.current(generation)) return
this.releaseConfig(id)
await tearDownEntryFiber(entry)
this.index.releaseReplaced(id)
if (!this.current(generation)) return
@@ -218,6 +275,7 @@ export class ClientEntries {
for (const [id, entry] of this.managed) {
if (wanted.has(id)) continue
const fiber = entry.fiber
this.releaseConfig(id)
loader.remove(entry.id)
this.managed.delete(id)
this.revisions.delete(id)
+7 -2
View File
@@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis'
import type { Loader } from '@deepseek-ai/cordis-plugin-loader'
import { ClientModuleSystem } from './system.ts'
import { parseBootManifest } from './manifest.ts'
import type { SyncedConfig, SyncedConfigService } from '@deepseek-ai/dsh-client-config/types'
import type {
ClientBootstrapModule, ClientModuleCreateOptions, ClientModuleLoader, ClientModuleLoaderTarget,
} from './manifest.ts'
@@ -52,11 +53,11 @@ export function createClientModuleSystem(
})
}
/** Required service: the Loader whose internal module system this plugin publishes. */
/** Required service: the Loader whose internal module system and synced configuration this plugin publishes. */
export const inject = ['loader']
/**
* Enroll the kernel-built module system as `ctx.modules`.
* Enroll the kernel-built module system as `ctx.modules` and its synced configuration lookup as `ctx.config`.
* @param ctx - client root context.
*/
export function apply(ctx: Context): void {
@@ -66,4 +67,8 @@ export function apply(ctx: Context): void {
throw new Error('client-modules: the Loader has no client module system')
}
ctx.reflect.provide('modules', modules)
const config: SyncedConfigService = {
resolveConfigByPackage: <C>(packageName: string) => modules.entries.resolveConfigByPackage(packageName) as SyncedConfig<C> | undefined,
}
ctx.reflect.provide('config', config)
}
@@ -28,6 +28,7 @@
* composes the wire.
*/
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import type {} from '@deepseek-ai/cordis'
import type {
DshClientManifest, ClientModuleMetaFactory,
@@ -69,6 +70,8 @@ export interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
/** Initial scheduling phase for one revisioned combo script. */
@@ -134,6 +137,8 @@ export interface BootPluginRow {
inject: string[]
/** Stage-one prefetch tier (false when the wire omits it). */
immediately: boolean
/** Synced Config values; undefined when the row has none. */
config?: SyncedConfigValues
}
/** The parsed boot manifest: one wire, two consumer views. */
@@ -275,10 +280,14 @@ export function parseBootManifest(wire: unknown): BootManifest {
inject: inject === undefined ? [] : [...inject],
external: external === undefined ? [] : [...external],
})
if (row.config !== undefined && (typeof row.config !== 'object' || row.config === null || Array.isArray(row.config))) {
throw new Error(`client-modules: boot manifest entry ${where} config must be an object`)
}
plugins.push({
id: row.id,
inject: inject === undefined ? [] : [...inject],
immediately: row.immediately === true,
...(row.config === undefined ? {} : { config: row.config as SyncedConfigValues }),
})
}
@@ -0,0 +1,160 @@
/**
* Browser-synced plugin configuration. Each plugin activation receives its own Config object of
* `SyncedConfigRef`s, as a Host activation resolves its own volatile references; only the page's entry
* controller writes values, and it stops writing to an activation once that activation's teardown begins.
*/
import type { VolatileSnapshot } from '@deepseek-ai/cordis'
import type { SyncedConfigRef, SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import { notifySubscribers } from './notify.ts'
/** Controller-side access to one reference: set without notifying, then notify once every field is set. */
interface RefPort {
set(value: unknown): void
notify(): void
}
/** The page's implementation of one {@link SyncedConfigRef}; only the activation that created it writes, through its port. */
class SyncedConfigReference<T> implements SyncedConfigRef<T> {
#value: VolatileSnapshot<T>
readonly #listeners = new Set<() => void>()
/**
* @param value - frozen initial value.
* @param attach - receives the controller's port; called once during construction.
*/
constructor(value: VolatileSnapshot<T>, attach: (port: RefPort) => void) {
this.#value = value
attach({
set: (next) => { this.#value = next as VolatileSnapshot<T> },
notify: () => { notifySubscribers(this.#listeners, 'synced configuration') },
})
}
/** @returns the current frozen value; undefined when the Host sends none. */
readonly get: () => VolatileSnapshot<T> = () => this.#value
/** @returns the same value as {@link get}. */
readonly getSnapshot: () => VolatileSnapshot<T> = () => this.#value
/**
* Observe value changes; every changed field of one update is set before any subscriber runs.
* @param listener - called after each change.
* @returns the disposer.
*/
readonly subscribe: (listener: () => void) => () => void = (listener) => {
this.#listeners.add(listener)
return () => { this.#listeners.delete(listener) }
}
}
/** Structural equality of JSON values; object key order does not matter. */
function sameJson(left: unknown, right: unknown): boolean {
if (left === right) return true
if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false
if (Array.isArray(left) !== Array.isArray(right)) return false
const leftKeys = Object.keys(left)
return leftKeys.length === Object.keys(right).length
&& leftKeys.every(key => Object.hasOwn(right, key) && sameJson(Reflect.get(left, key), Reflect.get(right, key)))
}
function freeze(value: unknown): unknown {
if (value !== null && typeof value === 'object') {
for (const child of Object.values(value)) freeze(child)
Object.freeze(value)
}
return value
}
/** The Config object of one plugin activation. */
class SyncedConfigActivation {
private values: SyncedConfigValues
private readonly ports = new Map<string, RefPort>()
private readonly refs = new Map<string, SyncedConfigReference<unknown>>()
/** Read-only object whose properties create field references on first access. */
readonly config: object
constructor(values: SyncedConfigValues) {
this.values = values
// An extensible empty target keeps the Proxy invariants satisfied for fields that appear later.
this.config = new Proxy({}, {
set: () => false,
defineProperty: () => false,
deleteProperty: () => false,
get: (_target, property) => typeof property === 'string' ? this.ref(property) : undefined,
has: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property),
ownKeys: () => Object.keys(this.values),
getOwnPropertyDescriptor: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property)
? { configurable: true, enumerable: true, value: this.ref(property) }
: undefined,
})
}
/** Set every changed field, then notify the changed fields' subscribers. */
write(values: SyncedConfigValues): void {
const previous = this.values
const changed = [...new Set([...Object.keys(previous), ...Object.keys(values)])]
.filter(field => !sameJson(previous[field], values[field]))
if (changed.length === 0) return
this.values = values
const ports = changed.flatMap((field) => {
const port = this.ports.get(field)
return port === undefined ? [] : [{ port, value: values[field] }]
})
for (const { port, value } of ports) port.set(value)
for (const { port } of ports) port.notify()
}
private ref(field: string): SyncedConfigReference<unknown> {
let ref = this.refs.get(field)
if (ref === undefined) {
ref = new SyncedConfigReference<unknown>(this.values[field], (port) => { this.ports.set(field, port) })
this.refs.set(field, ref)
}
return ref
}
}
/** Latest synced values of one package and the Config object of its current plugin activation. */
export class SyncedConfigEntry {
private values: SyncedConfigValues
private current: SyncedConfigActivation | undefined
/** @param values - Host-validated values; they are frozen and not checked against any schema. */
constructor(values: SyncedConfigValues) {
this.values = freeze(structuredClone(values)) as SyncedConfigValues
}
/** Whether no field currently has a value. */
get empty(): boolean {
return Object.keys(this.values).length === 0
}
/** The current activation's Config object; undefined between a teardown and the next activation. */
get config(): object | undefined {
return this.current?.config
}
/**
* Start an activation: a new Config object holding the latest values; the previous activation stops receiving writes.
* @returns the object to hand to the activation's `apply`.
*/
activate(): object {
this.current = new SyncedConfigActivation(this.values)
return this.current.config
}
/**
* An activation's teardown has begun; later values wait for the next activation.
* @param config - the ending activation's object; omitted, the current activation ends.
*/
release(config?: object): void {
if (config === undefined || this.current?.config === config) this.current = undefined
}
/**
* Replace the values; the current activation receives the changed fields, if one is running.
* @param values - the package's complete values; absent fields read undefined.
*/
update(values: SyncedConfigValues): void {
this.values = freeze(structuredClone(values)) as SyncedConfigValues
this.current?.write(this.values)
}
}
@@ -0,0 +1,120 @@
/**
* Projection of one running plugin's Config onto the values the browser may receive: top-level volatile fields only,
* with every `role('secret')` position removed, including positions inside volatile objects, dictionaries, and arrays.
*/
import { isDeepStrictEqual } from 'node:util'
import type { Volatile } from '@deepseek-ai/cordis'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
/** Schemastery node fields the projection reads; a Schemastery schema satisfies it structurally. */
export interface SchemaNode {
type: string
meta: { role?: unknown; volatile?: unknown }
dict?: Record<string, SchemaNode>
inner?: SchemaNode
list?: SchemaNode[]
}
/** A volatile field of a parsed Config is a reference; detected structurally so this package needs no Cosmokit copy. */
function isReference(value: unknown): value is Volatile<unknown> {
return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'get') === 'function'
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Read a child field Schemastery always sets for the node types that use it.
* @param node - schema node.
* @param key - `dict` for objects, `inner` for dictionaries, arrays, and transforms, `list` for unions and intersections.
* @returns the field.
*/
function part<K extends 'dict' | 'inner' | 'list'>(node: SchemaNode, key: K): NonNullable<SchemaNode[K]> {
const value = node[key]
/* v8 ignore next -- Schemastery constructs every object, dict, array, transform, union, and intersect node with this field. */
if (value === undefined) throw new TypeError(`client-modules: ${node.type} schema has no ${key}`)
return value
}
/** Every union branch is applied, so a field any branch declares secret is removed. */
function stripSecrets(node: SchemaNode, value: unknown): unknown {
if (value === undefined || node.meta.role === 'secret') return undefined
switch (node.type) {
case 'object': {
if (!isRecord(value)) return value
// As the settings redaction does, keys this branch does not declare stay, so union and intersection members do not
// drop each other's fields.
const dict = part(node, 'dict')
const undeclared = Object.entries(value).filter(([key]) => !(key in dict))
return { ...Object.fromEntries(undeclared), ...collect(Object.entries(dict).map(([key, child]) => [key, child, value[key]])) }
}
case 'dict': {
const inner = part(node, 'inner')
return isRecord(value) ? collect(Object.entries(value).map(([key, entry]) => [key, inner, entry])) : value
}
case 'array':
// A secret array item is dropped from the list rather than replaced by a placeholder.
return Array.isArray(value) ? value.map(entry => stripSecrets(part(node, 'inner'), entry)).filter(entry => entry !== undefined) : value
case 'union':
case 'intersect':
return part(node, 'list').reduce<unknown>((current, child) => stripSecrets(child, current), value)
case 'transform':
return stripSecrets(part(node, 'inner'), value)
default:
return value
}
}
/** Rebuild an object from stripped properties, omitting those that strip to undefined. */
function collect(properties: [string, SchemaNode, unknown][]): Record<string, unknown> {
const rebuilt: Record<string, unknown> = {}
for (const [key, child, entry] of properties) {
const stripped = stripSecrets(child, entry)
if (stripped !== undefined) rebuilt[key] = stripped
}
return rebuilt
}
/** Top-level object fields of a Config schema; intersections contribute the fields of each object member. */
function topFields(node: SchemaNode): [string, SchemaNode][] {
if (node.type === 'object') return Object.entries(part(node, 'dict'))
if (node.type === 'intersect') return part(node, 'list').flatMap(topFields)
return []
}
/**
* Whether a Config schema declares a top-level volatile field, the only fields synced to the browser.
* @param schema - the plugin's Host Config schema.
* @returns true when at least one top-level field is volatile.
*/
export function hasSyncedFields(schema: SchemaNode): boolean {
return topFields(schema).some(([, node]) => node.meta.volatile === true)
}
/**
* Project a running plugin's effective Config onto its browser-synced values.
* @param schema - the plugin's Host Config schema.
* @param effective - the fiber's effective Config, whose volatile fields are references.
* @param id - package name, used in diagnostics.
* @returns the synced values, or undefined when the schema declares no top-level volatile field.
* @throws TypeError when a synced value is not lossless JSON.
*/
export function syncedValues(schema: SchemaNode, effective: unknown, id: string): SyncedConfigValues | undefined {
const fields = topFields(schema).filter(([, node]) => node.meta.volatile === true)
if (fields.length === 0) return undefined
const source = isRecord(effective) ? effective : {}
const values: Record<string, JsonValue> = {}
for (const [key, node] of fields) {
const raw = source[key]
const stripped = stripSecrets(node, isReference(raw) ? raw.get() : raw)
if (stripped === undefined) continue
const json = JSON.parse(JSON.stringify(stripped)) as JsonValue
if (!isDeepStrictEqual(json, stripped)) {
throw new TypeError(`client-modules: ${id} Config field ${key} is not lossless JSON and cannot be synced to the browser`)
}
values[key] = json
}
return values
}
+160
View File
@@ -0,0 +1,160 @@
/**
* Host-side publication of browser-synced plugin configuration: each graph row carries the projected volatile values
* of its Loader entry's plugin, and a change of those values republishes the graph.
*/
import { isDeepStrictEqual } from 'node:util'
import { FiberState } from '@deepseek-ai/cordis'
import type { Context, Fiber } from '@deepseek-ai/cordis'
import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import type z from '@deepseek-ai/schemastery'
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import type { WebBootEntry, WebBootGraph } from './client/manifest.ts'
import { hasSyncedFields, syncedValues } from './config-projection.ts'
/** Synced values per graph row, owned by the client module registry. */
export class SyncedConfigPublisher {
/** Last published values per row; undefined for a plugin without top-level volatile fields. */
private readonly values = new Map<string, SyncedConfigValues | undefined>()
/**
* Values the row's schema resolves from an empty Config, served to every non-owner Peer; undefined when the schema
* declares no top-level volatile field or cannot resolve an empty Config.
*/
private readonly defaults = new Map<string, SyncedConfigValues | undefined>()
/** Loader entry name per row of the last composed graph. */
private rows = new Map<string, string>()
/** Current root plugin fiber per Loader entry name; of entries sharing a name, the one seen last. */
private readonly fibers = new Map<string, Fiber>()
/** `loader/volatile-update` listener disposer per Loader entry name. */
private readonly watches = new Map<string, () => void>()
/**
* @param ctx - the registry's context; the publisher's listeners leave with it.
* @param entries - the Loader entries present when the registry starts.
* @param changed - recomposes and republishes the graph after a row's values change.
*/
constructor(private readonly ctx: Context, entries: Iterable<Entry>, private readonly changed: () => void) {
for (const entry of entries) if (entry.fiber !== undefined) this.track(entry.options.name, entry.fiber.ctx.fiber)
// A new plugin instance (install, upgrade, code reload) is seen at creation, so the graph that announces its code
// already carries values its schema resolves; a status change re-reads values after a (re)start.
const seen = (fiber: Fiber): void => {
const entry = fiber.entry
// Only an entry's live root plugin, by the Loader's own test: a child plugin inherits its parent's entry, and a
// replaced instance (its uid cleared at disposal) may report its teardown after its successor exists. The
// successor is not yet `entry.fiber` here, because the Loader assigns that after construction returns.
if (entry === undefined || fiber.parent.fiber.entry === entry) return
const name = entry.options.name
if (fiber.uid === null) {
if (this.fibers.get(name) !== fiber) return
// The selected instance is gone; a live entry of the same name, sharing its source, supplies the values.
const live = [...ctx.loader.entries()]
.map(candidate => candidate.options.name === name ? candidate.fiber?.ctx.fiber : undefined)
.find(candidate => candidate !== undefined && candidate.uid !== null)
if (live === undefined) return
fiber = live
}
this.track(name, fiber)
this.republish(name)
}
ctx.on('internal/plugin', seen)
ctx.on('internal/status', seen)
ctx.effect(() => () => {
for (const dispose of this.watches.values()) dispose()
this.watches.clear()
}, 'client-modules: synced configuration watches')
}
/**
* Attach current synced values to composed rows, and drop the values of rows that left the graph.
* @param entries - composed rows.
* @param records - the registry table, keyed by row id, naming the Loader entry that supplies each row.
* @returns the rows, each with its values when it has any.
*/
apply(entries: WebBootEntry[], records: ReadonlyMap<string, { readonly loaderName: string }>): WebBootEntry[] {
this.rows = new Map([...records].map(([id, record]) => [id, record.loaderName]))
for (const id of this.values.keys()) if (!this.rows.has(id)) this.values.delete(id)
for (const id of this.defaults.keys()) if (!this.rows.has(id)) this.defaults.delete(id)
for (const [id, loaderName] of this.rows) this.refresh(id, loaderName)
return entries.map(({ config: _published, ...row }) => {
const config = this.values.get(row.id)
return config === undefined ? row : { ...row, config }
})
}
/**
* The graph one Peer receives, at first render and in every plugin-events frame. The owner receives the configured
* values; every other Peer receives each row's schema defaults instead, so the owner's values stay on the Host.
* @param graph - the composed graph.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph itself for the owner, otherwise a copy whose row values are the schema defaults.
*/
graphFor(graph: WebBootGraph, principal: Principal | undefined): WebBootGraph {
/* oxlint-disable typescript/no-unnecessary-condition -- other packages merge non-owner principal kinds into the map
this program sees with only the owner kind. */
if (principal === undefined || principal.kind === 'owner') return graph
/* oxlint-enable typescript/no-unnecessary-condition */
return {
...graph,
entries: graph.entries.map(({ config: _config, ...row }) => {
const config = this.defaults.get(row.id)
return config === undefined ? row : { ...row, config }
}),
}
}
private track(name: string, fiber: Fiber): void {
this.fibers.set(name, fiber)
// `loader/volatile-update` reaches only listeners on the updated fiber's own context, and a listener there lasts one
// activation, so each activation registers it again. Prepended: the graph frame carrying the new values is queued
// before the plugin's own listeners can push data that depends on them.
if (fiber.state !== FiberState.ACTIVE) return
this.watches.get(name)?.()
this.watches.set(name, fiber.ctx.on('loader/volatile-update', () => { this.republish(name) }, { prepend: true }))
}
private republish(name: string): void {
let changed = false
for (const [id, loaderName] of this.rows) if (loaderName === name && this.refresh(id, loaderName)) changed = true
if (changed) this.changed()
}
/**
* Recompute one row's values; equal values (deep equality) change nothing.
* @returns whether the row's values changed.
*/
private refresh(id: string, loaderName: string): boolean {
const fiber = this.fibers.get(loaderName)
/* v8 ignore next -- a table row comes from a Loader entry whose root fiber was tracked at startup or creation. */
if (fiber === undefined) return false
const runtimeSchema = fiber.runtime?.Config
// A plugin without synced fields is never resolved here.
const schema = runtimeSchema !== undefined && 'toJSON' in runtimeSchema && hasSyncedFields(runtimeSchema as z)
? runtimeSchema as z
: undefined
this.defaults.set(id, schema === undefined ? undefined : this.defaultValues(schema, fiber, id))
let values: SyncedConfigValues | undefined
try {
// Before activation there is no effective Config; resolving the raw config with the instance's own schema gives
// the object activation will receive.
values = schema === undefined ? undefined : syncedValues(schema, fiber.effectiveConfig ?? fiber.resolveConfig(fiber.rawConfig), id)
} catch (error) {
// Containment: one plugin's unsyncable value keeps its last published values and leaves the other rows intact.
this.ctx.logger.error(error)
return false
}
if (isDeepStrictEqual(this.values.get(id), values)) return false
this.values.set(id, values)
return true
}
private defaultValues(schema: z, fiber: Fiber, id: string): SyncedConfigValues | undefined {
try {
return syncedValues(schema, fiber.resolveConfig({}), id)
} catch (error) {
// A schema with a required field that has no default rejects an empty Config; such a row then carries no values
// for a non-owner Peer, and its plugin reads every field as absent there.
this.ctx.logger.debug(error)
return undefined
}
}
}
+33 -10
View File
@@ -39,8 +39,10 @@ import { Service } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import { PACKAGE_ASSET_SEGMENT, packageAssetMediaType } from './assets.ts'
import { exactPackageSpecifier, parseDshClient, stripClientSuffix } from './client/manifest.ts'
import { SyncedConfigPublisher } from './config-sync.ts'
import type { WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph, WebBootRelease } from './client/manifest.ts'
export { stripClientSuffix } from './client/manifest.ts'
@@ -662,6 +664,7 @@ export class ClientModuleRegistry extends Service {
private previousBatchResponses = new Map<string, LazyResponse>()
private flushQueued = false
private composed: WebBootGraph
private readonly syncedConfig: SyncedConfigPublisher
/**
* Build the service: subscribe, seed, and run the activation flush.
@@ -692,7 +695,14 @@ export class ClientModuleRegistry extends Service {
// Activation pass: the initial scan IS the incremental path over the
// current entries, flushed synchronously (nothing async between subscribe,
// seed, and flush).
for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name)
const entries = [...ctx.loader.entries()]
for (const entry of entries) this.dirty.add(entry.options.name)
this.syncedConfig = new SyncedConfigPublisher(ctx, entries, () => {
// Only rows and rev change: the batch artifacts and the prior batch generation stay.
const rows = this.syncedConfig.apply(this.composed.entries, this.table)
this.composed = { ...this.composed, entries: rows, rev: shortHash(JSON.stringify({ entries: rows, batches: this.composed.batches })) }
this.notifyGraphChanged()
})
this.composed = this.compose()
const failures: Error[] = []
this.flush(err => failures.push(err))
@@ -707,19 +717,29 @@ export class ClientModuleRegistry extends Service {
)
}
ctx.inject(['webServer'], registerWebCarrier)
ctx.on('webserver/index-inject', (table) => {
table.push(...bootInjections(this.composed))
ctx.on('webserver/index-inject', (table, peer) => {
table.push(...bootInjections(this.graphFor(peer.principal)))
})
}
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph {
return this.composed
}
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph {
return this.syncedConfig.graphFor(this.composed, principal)
}
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -808,8 +828,10 @@ export class ClientModuleRegistry extends Service {
}
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
@@ -868,10 +890,11 @@ export class ClientModuleRegistry extends Service {
this.batchResponses = batchResponses
this.responses = responses
const batches = artifacts.map(artifact => artifact.descriptor)
const rows = this.syncedConfig.apply(entries, this.table)
return {
rev: shortHash(JSON.stringify({ entries, batches })),
rev: shortHash(JSON.stringify({ entries: rows, batches })),
release: this.release,
entries,
entries: rows,
batches,
}
}
@@ -1289,7 +1312,7 @@ export class ClientModuleRegistry extends Service {
}
}
// Anything else under /plugins (including unadvertised combinations and
// /plugins/events when the HMR row is absent) is an unknown resource.
// an unknown path) is an unknown resource.
return { status: 404 }
}
+5
View File
@@ -0,0 +1,5 @@
/** Web client graph types shared by the Host and Client faces and by Remote wire declarations. */
export type {
BootManifest, BootModuleRow, BootPluginRow, WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph,
WebBootRelease,
} from './client/manifest.ts'
@@ -2,7 +2,9 @@
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import { afterEach, describe, expect, it, vi } from 'vitest'
import z from '@deepseek-ai/schemastery'
import { createClientModuleSystem } from '../src/client/index.ts'
import type { SyncedConfigRef } from '@deepseek-ai/dsh-client-config/types'
import type { ClientBundleRegistration, ClientModuleLoaderTarget, WebBootRelease, WebBootEntry, WebBootGraph } from '../src/client/index.ts'
type Factory = ClientBundleRegistration['factory']
@@ -86,6 +88,149 @@ function visible(id: string, effects: { mounted: number; disposed: number; hits:
}
describe('client manifest entries', () => {
it('hands each activation its own synced Config object and updates changed fields without remounting', async () => {
interface Synced { size: SyncedConfigRef<number>; office: SyncedConfigRef<{ maxBytes: number }> }
const received: Synced[] = []
const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1, office: { maxBytes: 8 } } })), {
a: () => ({ apply(_ctx: Context, config: Synced) { received.push(config) } }),
})
const config = received[0]!
expect(b.modules.entries.resolveConfigByPackage('a')).toBe(config)
expect(b.modules.entries.resolveConfigByPackage('missing')).toBeUndefined()
expect(Object.keys(config)).toEqual(['size', 'office'])
expect('size' in config).toBe(true)
expect('missing' in config).toBe(false)
expect('toString' in config).toBe(false)
expect(Object.getOwnPropertyDescriptor(config, 'hasOwnProperty')).toBeUndefined()
expect(Object.getOwnPropertyDescriptor(config, 'missing')).toBeUndefined()
expect(Reflect.get(config, Symbol.iterator)).toBeUndefined()
expect(Reflect.set(config, 'size', 1)).toBe(false)
expect(Reflect.defineProperty(config, 'size', { value: 1 })).toBe(false)
expect(Reflect.deleteProperty(config, 'size')).toBe(false)
const size = config.size
expect(config.size).toBe(size)
expect(Object.getOwnPropertyDescriptor(config, 'size')?.value).toBe(size)
expect(size.get()).toBe(1)
const office = config.office.getSnapshot()
expect(Object.isFrozen(office)).toBe(true)
const sizeListener = vi.fn()
const officeListener = vi.fn()
const unsubscribe = size.subscribe(sizeListener)
config.office.subscribe(officeListener)
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { office: { maxBytes: 8 }, size: 1 } })))
expect(sizeListener).not.toHaveBeenCalled()
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2, office: { maxBytes: 8 } } })))
expect(size.get()).toBe(2)
expect(size.getSnapshot()).toBe(2)
expect(sizeListener).toHaveBeenCalledOnce()
expect(officeListener).not.toHaveBeenCalled()
expect(config.office.getSnapshot()).toBe(office)
// Every changed field is set before any subscriber runs.
const seen: unknown[] = []
size.subscribe(() => { seen.push([size.get(), config.office.get()]) })
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 4, office: { maxBytes: 9 } } })))
expect(seen).toEqual([[4, { maxBytes: 9 }]])
unsubscribe()
// Removal releases the activation: like a Host fiber that is no longer active, it receives no later values.
await b.modules.entries.sync(graph(row('bootstrap')))
expect(b.modules.entries.resolveConfigByPackage('a')).toBeUndefined()
expect(size.get()).toBe(4)
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 5 } })))
expect(size.get()).toBe(4)
// A re-added row's new activation receives a new object with the latest values.
expect(received).toHaveLength(2)
expect(received[1]).not.toBe(config)
expect(received[1]!.size.get()).toBe(5)
expect(b.modules.entries.resolveConfigByPackage('a')).toBe(received[1])
// Code replacement: a value arriving before teardown begins updates the still-active activation, as on the Host;
// the replacement then starts with the latest values, and the released activation receives nothing later.
const second = received[1]!
const replacing = b.modules.entries.reload('a', 'r1')
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r1', { config: { size: 6 } })))
await replacing
expect(received).toHaveLength(3)
expect(second.size.get()).toBe(6)
expect(received[2]!.size.get()).toBe(6)
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r1', { config: { size: 7 } })))
expect(received[2]!.size.get()).toBe(7)
expect(second.size.get()).toBe(6)
})
it('stops writing to an activation that unloads because a required service was withdrawn', async () => {
interface Synced { size: SyncedConfigRef<number> }
const received: Synced[] = []
const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), {
a: () => ({ inject: ['dependency'], apply(_ctx: Context, config: Synced) { received.push(config) } }),
})
const dispose = b.ctx.provide('dependency', {})
await vi.waitFor(() => { expect(received).toHaveLength(1) })
const first = received[0]!
expect(b.modules.entries.resolveConfigByPackage('a')).toBe(first)
dispose()
await b.ctx.loader.await()
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2 } })))
expect(first.size.get()).toBe(1)
expect(b.modules.entries.resolveConfigByPackage('a')).toBeUndefined()
})
it('keeps the running activation\'s object when a candidate config is resolved for it', async () => {
interface Synced { size: SyncedConfigRef<number> }
const received: Synced[] = []
const b = await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), {
a: () => ({ apply(_ctx: Context, config: Synced) { received.push(config) } }),
})
const fiber = [...b.ctx.loader.entries()].find(entry => entry.options.name === 'a')!.fiber!.ctx.fiber
expect(fiber.resolveConfig(fiber.rawConfig)).toBe(received[0])
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 2 } })))
expect(received[0]!.size.get()).toBe(2)
})
it('gives a row without values an empty object that later values fill without another apply', async () => {
const configs: unknown[] = []
const b = await bench(graph(row('bootstrap'), row('a')), {
a: () => ({ apply(_ctx: Context, config: unknown) { configs.push(config) } }),
})
const config = configs[0] as { size: SyncedConfigRef<number> }
expect(Object.keys(config)).toEqual([])
expect(config.size.get()).toBeUndefined()
await b.modules.entries.sync(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })))
expect(configs).toEqual([config])
expect(config.size.get()).toBe(1)
})
it('keeps ordinary configuration for a Client Config schema and rejects one that also receives synced values', async () => {
const own: unknown[] = []
const b = await bench(graph(row('bootstrap'), row('own'), row('schema', 'r0', { config: { size: 1 } })), {
own: () => ({ Config: z.object({ limit: z.natural().default(3) }), apply(_ctx: Context, config: unknown) { own.push(config) } }),
schema: () => ({ Config: z.object({}), apply() {} }),
})
expect(own).toEqual([{ limit: 3 }])
const schemaFiber = [...b.ctx.loader.entries()].find(entry => entry.options.name === 'schema')!.fiber!
await expect(schemaFiber.await()).rejects.toThrow('exports a Config schema')
// A fiber outside the managed entries resolves its own config.
const plain = await b.ctx.plugin({ apply(_ctx: Context, config: unknown) { own.push(config) } }, { plain: true })
expect(plain.state).toBe(2)
expect(own.at(-1)).toEqual({ plain: true })
})
it('keeps a child plugin\'s explicit config inside a managed entry', async () => {
const child: unknown[] = []
await bench(graph(row('bootstrap'), row('a', 'r0', { config: { size: 1 } })), {
a: () => ({ apply(ctx: Context) { ctx.plugin({ apply(_ctx: Context, config: unknown) { child.push(config) } }, { input: 1 }) } }),
})
expect(child).toEqual([{ input: 1 }])
})
it('rejects a graph row whose config is not an object', async () => {
const b = await bench(graph(row('bootstrap')), {})
expect(() => b.modules.entries.sync(graph(row('bootstrap', 'r0', { config: [] as never })))).toThrow('config must be an object')
})
it('adds, drains removal and re-enables one module record; unrelated entries survive', async () => {
const effects = { mounted: 0, disposed: 0, hits: 0 }
const cleanup = deferred()
@@ -7,7 +7,7 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { runInNewContext } from 'node:vm'
import { Context, FiberState, type Fiber } from '@deepseek-ai/cordis'
import { Context, FiberState } from '@deepseek-ai/cordis'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { renderIndexInjections, type WebServer, type WebResourceRoute, type WebRoute } from '@deepseek-ai/dsh-host-webserver'
import * as modulesClient from '../src/client/index.ts'
@@ -178,7 +178,8 @@ function constructWithRoute(
for (const packageName of packageNames) {
yield {
options: { name: packageName },
fiber: {},
// The Loader addresses an entry's plugin instance as `entry.fiber.ctx.fiber`.
fiber: { ctx: { fiber: {} } },
disabled: false,
parent: { tree: { ctx: { baseUrl: options.entryBaseUrl ?? ctx.baseUrl } } },
}
@@ -1289,7 +1290,8 @@ describe('client bundle activation', () => {
function emitLoaderEntryChange(context: Context, name: string): void {
context.emit('internal/plugin', {
entry: { options: { name } },
} as unknown as Fiber)
parent: { fiber: {} },
} as never)
}
describe('shared module declarations', () => {
@@ -142,7 +142,7 @@ async function composeHost(): Promise<Host> {
internal,
*entries() {
for (const name of [NO_EXPORT_ID, ASSETS_ID]) {
yield { options: { name }, fiber: {}, disabled: false, parent: { tree: { ctx: { baseUrl } } } }
yield { options: { name }, fiber: { ctx: { fiber: {} } }, disabled: false, parent: { tree: { ctx: { baseUrl } } } }
}
},
})
@@ -0,0 +1,256 @@
/** Host side of synced configuration: projection, secret removal, and graph publication from a real Loader. */
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import z from '@deepseek-ai/schemastery'
import { afterEach, expect, it, vi } from 'vitest'
import { ClientModuleRegistry } from '../src/index.ts'
import type { WebBootGraph } from '../src/client/manifest.ts'
import { syncedValues } from '../src/config-projection.ts'
import { SyncedConfigEntry } from '../src/client/synced-config.ts'
const roots: Context[] = []
let dir: string | undefined
afterEach(async () => {
await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose()))
if (dir !== undefined) rmSync(dir, { recursive: true, force: true })
dir = undefined
})
const Schema = z.object({
cacheDir: z.string().default('.cache'),
size: z.natural().default(1).volatile(),
apiKey: z.string().role('secret').volatile(),
office: z.object({ maxBytes: z.natural().default(8), token: z.string().role('secret') }).volatile(),
tokens: z.array(z.string().role('secret')).default([]).volatile(),
headers: z.dict(z.string().role('secret')).default({}).volatile(),
choice: z.union([z.object({ kind: z.const('a'), secret: z.string().role('secret') }), z.string()]).default('plain').volatile(),
wrapped: z.transform(z.natural().default(2), value => value).volatile(),
})
it('projects top-level volatile fields and removes every secret position', () => {
const effective = Schema({
size: 3, apiKey: 'k', office: { maxBytes: 9, token: 't' }, tokens: ['x'], headers: { a: 'h' },
choice: { kind: 'a', secret: 's' }, wrapped: 2, extra: 1,
})
expect(syncedValues(Schema, effective, 'pkg')).toEqual({
size: 3, office: { maxBytes: 9 }, tokens: [], headers: {}, choice: { kind: 'a' }, wrapped: 2,
})
expect(syncedValues(z.object({ ordinary: z.string().default('x') }), {}, 'pkg')).toBeUndefined()
expect(syncedValues(z.string(), 'x', 'pkg')).toBeUndefined()
})
it('reads intersection members, tolerates non-object values, and rejects lossy JSON', () => {
const Joined = z.intersect([
z.object({ a: z.natural().default(1).volatile() }),
z.object({ b: z.object({ c: z.string().role('secret') }).volatile(), d: z.dict(z.string()).volatile(), e: z.array(z.string()).volatile() }),
])
expect(syncedValues(Joined, { a: 1, b: 'scalar', d: 'scalar', e: 'scalar' }, 'pkg')).toEqual({ a: 1, b: 'scalar', d: 'scalar', e: 'scalar' })
expect(syncedValues(Joined, null, 'pkg')).toEqual({})
expect(() => syncedValues(Joined, { a: Number.NaN }, 'pkg')).toThrow('pkg Config field a is not lossless JSON')
})
/** A resolvable built browser package under a temporary node_modules. */
function writePackage(name: string): void {
dir ??= realpathSync(mkdtempSync(join(tmpdir(), 'dsh-synced-config-')))
const root = join(dir, 'node_modules', ...name.split('/'))
mkdirSync(join(root, 'lib'), { recursive: true })
writeFileSync(join(root, 'package.json'), JSON.stringify({
name, exports: { './client': './lib/client.js', './package.json': './package.json' }, dsh: { client: { platform: 'web' } },
}))
writeFileSync(join(root, 'lib', 'client.js'), 'module.exports = {}\n')
}
/** A real Loader whose rows import the given plugins, and the graph service over it. */
async function harness(plugins: Record<string, object>, configs: Record<string, object> = {}, disabled: string[] = []) {
for (const name of Object.keys(plugins)) writePackage(name)
const ctx = new Context()
roots.push(ctx)
ctx.baseUrl = pathToFileURL(dir!).href + '/'
await ctx.plugin(Loader)
ctx.loader.internal = { version: 'v2', import: async (name: string) => plugins[name] } as never
const entries: Record<string, Entry> = {}
for (const name of Object.keys(plugins)) {
entries[name] = ctx.loader.resolve(await ctx.loader.create({
name, disabled: disabled.includes(name), ...(configs[name] === undefined ? {} : { config: configs[name] }),
}))
}
await ctx.loader.await()
const fiber = ctx.plugin(ClientModuleRegistry)
await fiber.await()
const service = ctx.get('clientModules')!
const config = (id: string) => service.graph().entries.find(row => row.id === id)?.config
const changes = vi.fn()
service.onGraphChanged(changes)
return { ctx, service, entries, fiber, config, changes, plugins }
}
const initial = { size: 3, office: { maxBytes: 8 }, tokens: [], headers: {}, choice: 'plain' }
it('publishes volatile updates once, skips equal values, and keeps unsynced rows without config', async () => {
const h = await harness({
'@fixture/pkg': { Config: Schema, apply: () => {} },
'@fixture/plain': { apply: () => {} },
'@fixture/off': { Config: Schema, apply: () => {} },
}, { '@fixture/pkg': { size: 3, apiKey: 'k' }, '@fixture/plain': {} }, ['@fixture/off'])
expect(h.config('@fixture/pkg')).toEqual(initial)
expect(h.service.graph().entries.find(row => row.id === '@fixture/plain')).not.toHaveProperty('config')
const before = h.service.graph()
await h.entries['@fixture/pkg']!.update({ config: { size: 3, apiKey: 'changed' } })
expect(h.changes).not.toHaveBeenCalled()
expect(h.service.graph()).toBe(before)
await h.entries['@fixture/pkg']!.update({ config: { size: 4, apiKey: 'changed' } })
expect(h.changes).toHaveBeenCalledOnce()
expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 4 })
expect(h.service.graph().rev).not.toBe(before.rev)
})
it('republishes after an ordinary change restarts the plugin and drops values of a removed row', async () => {
const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } })
await h.entries['@fixture/pkg']!.update({ config: { size: 5, cacheDir: 'other' } })
await h.ctx.loader.await()
await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 5 }) })
h.ctx.loader.remove(h.entries['@fixture/pkg']!.id)
await h.ctx.loader.await()
await vi.waitFor(() => { expect(h.service.graph().entries).toEqual([]) })
await h.fiber.dispose()
})
it('publishes values its own schema resolves for a plugin that has not activated yet', async () => {
const h = await harness({ '@fixture/waiting': { inject: ['absent'], Config: Schema, apply: () => {} } }, {
'@fixture/waiting': { size: 3 },
})
expect(h.entries['@fixture/waiting']!.fiber!.ctx.fiber.effectiveConfig).toBeUndefined()
expect(h.config('@fixture/waiting')).toEqual(initial)
})
it('publishes values for an entry created after startup that has not activated yet', async () => {
const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } })
writePackage('@fixture/late')
h.plugins['@fixture/late'] = { inject: ['absent'], Config: Schema, apply: () => {} }
await h.ctx.loader.create({ name: '@fixture/late', config: { size: 7 } })
await vi.waitFor(() => { expect(h.config('@fixture/late')).toEqual({ ...initial, size: 7 }) })
})
const bootConfigOf = (ctx: Context, id: string) => (principal: { kind: string }): unknown => {
const table: { kind: string; name?: string; value?: unknown }[] = []
ctx.emit('webserver/index-inject', table as never, { principal } as never)
const graph = table.find(row => row.name === '__DSH_BOOT__')!.value as { entries: { id: string; config?: unknown }[] }
return graph.entries.find(row => row.id === id)!.config
}
it('serves configured values to the owner and schema defaults to every other Peer, at first render and through graphFor', async () => {
const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } })
const bootConfig = bootConfigOf(h.ctx, '@fixture/pkg')
const defaults = { ...initial, size: 1 }
const rowOf = (graph: WebBootGraph) => graph.entries.find(row => row.id === '@fixture/pkg')!.config
expect(bootConfig({ kind: 'owner' })).toEqual(initial)
expect(bootConfig({ kind: 'viewer' })).toEqual(defaults)
expect(h.service.graphFor(undefined)).toBe(h.service.graph())
expect(h.service.graphFor({ kind: 'owner' })).toBe(h.service.graph())
expect(rowOf(h.service.graphFor({ kind: 'viewer' } as never))).toEqual(defaults)
// A Remote access grant does not change which values a non-owner receives.
h.ctx.provide('remoteAccess', { snapshotFor: () => ({ type: 'baseline', owner: false, grants: [] }) } as never)
expect(bootConfig({ kind: 'viewer' })).toEqual(defaults)
})
it('serves no values to a non-owner Peer when the schema rejects an empty Config', async () => {
const Required = z.object({ size: z.natural().required().volatile() })
const h = await harness({ '@fixture/required': { Config: Required, apply: () => {} } }, { '@fixture/required': { size: 3 } })
const debug = vi.spyOn(h.ctx.logger, 'debug').mockImplementation(() => {})
await h.entries['@fixture/required']!.update({ config: { size: 4 } })
const bootConfig = bootConfigOf(h.ctx, '@fixture/required')
expect(bootConfig({ kind: 'owner' })).toEqual({ size: 4 })
expect(bootConfig({ kind: 'viewer' })).toBeUndefined()
expect(debug).toHaveBeenCalled()
})
it('keeps the batch artifacts and the prior batch generation when only synced values change', async () => {
const h = await harness({ '@fixture/pkg': { Config: Schema, apply: () => {} } }, { '@fixture/pkg': { size: 3 } })
const status = async (url: string) => (await h.service.fetchBundle(new Request(new URL(url, 'http://localhost/').href))).status
const first = h.service.graph().batches[0]!.url
writeFileSync(join(dir!, 'node_modules', '@fixture', 'pkg', 'lib', 'client.js'), 'module.exports = { generation: 2000 }\n')
h.service.rebuilt('@fixture/pkg')
const second = h.service.graph()
expect(second.batches[0]!.url).not.toBe(first)
await h.entries['@fixture/pkg']!.update({ config: { size: 4 } })
expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 4 })
expect(h.service.graph().batches).toBe(second.batches)
expect(await status(first)).toBe(200)
})
it('falls back to a live entry of the same name when the selected instance is removed', async () => {
const h = await harness({ '@fixture/other': { apply: () => {} }, '@fixture/pkg': { Config: Schema, apply: () => {} } }, {
'@fixture/pkg': { size: 1 },
})
// A disabled entry of the same name has no instance to fall back to.
await h.ctx.loader.create({ name: '@fixture/pkg', disabled: true })
const second = h.ctx.loader.resolve(await h.ctx.loader.create({ name: '@fixture/pkg', config: { size: 2 } }))
await h.ctx.loader.await()
await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 2 }) })
h.ctx.loader.remove(second.id)
await h.ctx.loader.await()
await vi.waitFor(() => { expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 1 }) })
await h.entries['@fixture/pkg']!.update({ config: { size: 3 } })
expect(h.config('@fixture/pkg')).toEqual({ ...initial, size: 3 })
// With no live entry left, the last values stay until the row leaves the graph.
h.ctx.loader.remove(h.entries['@fixture/pkg']!.id)
await h.ctx.loader.await()
})
it('keeps the last values of a row whose value cannot be synced', async () => {
const h = await harness({ '@fixture/lossy': { Config: z.object({ n: z.any().volatile() }), apply: () => {} } }, { '@fixture/lossy': { n: 1 } })
const errors = vi.spyOn(h.ctx.logger, 'error').mockImplementation(() => {})
expect(h.config('@fixture/lossy')).toEqual({ n: 1 })
await h.entries['@fixture/lossy']!.update({ config: { n: Number.POSITIVE_INFINITY } })
expect(errors).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining('@fixture/lossy Config field n') as string }))
expect(h.config('@fixture/lossy')).toEqual({ n: 1 })
})
it('keeps the fields each union branch or intersection member does not declare', () => {
const a = z.object({ a: z.string() })
const b = z.object({ b: z.string() })
const schema = z.object({
either: z.union([a, b]).volatile(),
both: z.intersect([a, b]).volatile(),
hidden: z.union([z.object({ kind: z.const('x'), token: z.string().role('secret') }), b]).volatile(),
})
expect(syncedValues(schema, { either: { a: 'one' }, both: { a: 'one', b: 'two' }, hidden: { kind: 'x', token: 't' } }, 'pkg'))
.toEqual({ either: { a: 'one' }, both: { a: 'one', b: 'two' }, hidden: { kind: 'x' } })
})
it('compares field values as JSON, so an empty array and an empty object differ while reordered keys do not', () => {
const entry = new SyncedConfigEntry({ list: [], map: { a: 1, b: 2 } })
expect(entry.config).toBeUndefined()
type Ref = { get(): unknown; subscribe(listener: () => void): () => void }
const config = entry.activate() as { list: Ref; map: Ref }
expect(entry.config).toBe(config)
const list = vi.fn()
const map = vi.fn()
config.list.subscribe(list)
config.map.subscribe(map)
entry.update({ list: {}, map: { b: 2, a: 1 }, extra: 1 })
expect(config.list.get()).toEqual({})
expect(list).toHaveBeenCalledOnce()
expect(map).not.toHaveBeenCalled()
expect(entry.empty).toBe(false)
entry.release()
expect(entry.config).toBeUndefined()
entry.update({})
expect(entry.empty).toBe(true)
expect(config.list.get()).toEqual({})
})
it('queues the new graph before the plugin\'s own volatile-update listeners run', async () => {
const order: string[] = []
const h = await harness({
'@fixture/ordered': { Config: Schema, apply: (ctx: Context) => { ctx.on('loader/volatile-update', () => { order.push('plugin') }) } },
}, { '@fixture/ordered': { size: 1 } })
h.service.onGraphChanged(() => { order.push('graph') })
await h.entries['@fixture/ordered']!.update({ config: { size: 2 } })
expect(order).toEqual(['graph', 'plugin'])
})
+5 -1
View File
@@ -13,6 +13,10 @@
{"path": "../../host/webserver"},
{"path": "../../util/package-manifest"},
{"path": "../script-realm"},
{"path": "../store"}
{"path": "../store"},
{"path": "../../../vendor/schemastery"},
{"path": "../../util/values"},
{"path": "../config"},
{"path": "../../typert/protocol"}
]
}
@@ -1,3 +1,4 @@
import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime'
import type { AssistantNodeInjected } from '../src/client/chat/AssistantNodeView.tsx'
import type { MessageId } from '@deepseek-ai/dsh-llm/types'
import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client'
@@ -105,12 +106,12 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true,
runtime.ctx.provide('locale', locale)
runtime.slots.installLocale(locale)
runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) })
await runtime.mount({ inject: [...injectMenus], apply: applyMenus })
await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 }))
await runtime.root.declare({
'main': { kind: 'keyed', scope: 'root' },
'settings.general.item': { kind: 'list', scope: 'root' },
}, (_props: { renderSlot?: unknown }) => null)
await runtime.mount({ inject: [...injectConversation], apply: applyConversation })
await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 }))
const registerGroups = withProcessGroups ? undefined
: vi.spyOn(runtime.ctx.uiConversation.groups, 'register').mockImplementation(() => () => {})
const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat })
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more