diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml index f29cf535f2..7f34aedf3f 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md index bc24420a59..6de1fd1ab8 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.md @@ -46,7 +46,7 @@ A `require.async("./client..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///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/??/client.js,/client.js&rev=` points to `/plugins/??/client.js.map,/client.js.map&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 diff --git a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md index bebd131c85..7e1e7d1d40 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-client-plugin-loading-model.zh.md @@ -46,7 +46,7 @@ Host 会快照每个已构建插件入口 bundle,并把每个调度阶段的 共享 tsdown 预设为每个插件入口与 chunk 产出 map,并把第一方源码路径重写成浏览器可识别的仓库形式 `/packages///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/??/client.js,/client.js&rev=` 指向 `/plugins/??/client.js.map,/client.js.map&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 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml index fdbd7de7cb..86b1b861c4 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md index b4c4c539ee..90f71ebcdf 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md index a5344f8b01..4b46aceeee 100644 --- a/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-14-webworker-preview-profile-parity.zh.md @@ -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 插件无需刷新页面即可挂载。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml new file mode 100644 index 0000000000..aad42e312a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md new file mode 100644 index 0000000000..5282c80450 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.md @@ -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 + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = 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): 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) { + 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 extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : 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`, 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(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 | diff --git a/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md new file mode 100644 index 0000000000..4afa3940b9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md @@ -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 + /** Synced as one value. */ + office: Volatile<{ maxBytes: number }> + /** Volatile but `role('secret')`: stripped on the Host; reads as undefined in the browser. */ + apiKey?: Volatile +} +``` + +```ts ignore-check +// src/index.ts — Host face; the only schema +export const Config: z = 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): 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) { + 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 extends Volatile, ObservableSnapshot> {} + +/** The Volatile fields of the shared Config type. */ +export type SyncedConfig = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : never +} +``` + +`get` 与 `getSnapshot` 返回同一个冻结快照:`get` 与 Host 的 volatile 引用写法一致,`getSnapshot` 与 `subscribe` 满足 `ObservableSnapshot`,引用本身即可放进 `hooks`,renderer 不需要额外适配。接口没有写操作;实现类只在 Client Modules 内部。 + +组件取值遵循 [client 规则](../../../../packages/client/AGENTS.md):插件在 slot inject 的 `hooks` 中手动注入 key 级数据源,组件只通过 renderer 绑定的 `use` 读取,不接触数据源本身。 + +### 归属 + +运行时归属仍在 `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(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 值都会缺失,插件需在每次读取时处理缺值 | diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml index 4124137839..749b8adffb 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md index 33ac74d954..43728342e9 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md index f8e8f85f71..c668e9615b 100644 --- a/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md +++ b/.agents/notes/implemented/feature/2026-10-14-host-release-change-refresh-prompt.zh.md @@ -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,以及确认框的渲染与回调。 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml new file mode 100644 index 0000000000..012f82ab67 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.i18n.yaml @@ -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 diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md new file mode 100644 index 0000000000..ba52a8881c --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.md @@ -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 | diff --git a/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md new file mode 100644 index 0000000000..4714b909ff --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-15-client-config-sync-migration.zh.md @@ -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` 在自身激活前就需要恢复参数,早于同步配置能参与的时间点 | diff --git a/apps/web/tests/assembled-boot.ts b/apps/web/tests/assembled-boot.ts index 3ecaa90a4d..a45ff68471 100644 --- a/apps/web/tests/assembled-boot.ts +++ b/apps/web/tests/assembled-boot.ts @@ -191,11 +191,6 @@ class ResizeObserverStub { unobserve(): void {} } -class EventSourceStub { - addEventListener(): void {} - close(): void {} -} - const win = window as FixtureWindow let unmount: (() => Promise) | 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) }) diff --git a/apps/web/tests/client-config-sync.e2e.ts b/apps/web/tests/client-config-sync.e2e.ts new file mode 100644 index 0000000000..f132739954 --- /dev/null +++ b/apps/web/tests/client-config-sync.e2e.ts @@ -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 | 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) diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 0e4ff0df1d..9b451d8de1 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -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) diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js b/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js new file mode 100644 index 0000000000..ee4d0c28ef --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/client.js @@ -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)) + }, + } + }, +}) diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml b/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml new file mode 100644 index 0000000000..aa75328148 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/cordis.patch.yml @@ -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 diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js b/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js new file mode 100644 index 0000000000..893707aa9a --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/index.js @@ -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() {} diff --git a/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json b/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json new file mode 100644 index 0000000000..188f4b8557 --- /dev/null +++ b/apps/web/tests/fixtures/plugins/fixture-synced-config/package.json @@ -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" + } + } +} diff --git a/apps/web/tests/server-restart.e2e.ts b/apps/web/tests/server-restart.e2e.ts index d5b3c180cb..1df9d3a390 100644 --- a/apps/web/tests/server-restart.e2e.ts +++ b/apps/web/tests/server-restart.e2e.ts @@ -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)) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index f42092cecf..a569e4fd0a 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -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", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index ad096eb295..810f80357f 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 15d626593d746219 - zh: 332d2135597249b8 + en: 4eb44ffc136cee25 + zh: a34b8a156fc22955 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 3f755e9995..0ad1e8ccd0 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -312,6 +312,8 @@ flowchart LR pkg_web_app["web-app"] svc_webApp["ctx.webApp
Served Web GUI"] pkg_harness_dev_context["harness-dev-context"] + pkg_client_config["client-config"] + svc_config["ctx.config
Browser synced configuration lookup"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
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. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 82a2f1bac5..4c8f97249e 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -314,6 +314,8 @@ flowchart LR pkg_web_app["web-app"] svc_webApp["ctx.webApp
Served Web GUI"] pkg_harness_dev_context["harness-dev-context"] + pkg_client_config["client-config"] + svc_config["ctx.config
Browser synced configuration lookup"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
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,不保留交付或完成状态。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ae715397bc..9ae3dfe8ce 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -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) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index be2fd88dfc..8817fd1a67 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -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) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index bae4217b1c..d76916c079 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -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` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 46d784aafd..556072d49e 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -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` | diff --git a/docs/module-graph.md b/docs/module-graph.md index e804dab125..78096e94d9 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -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` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 49229162ae..6a794771a7 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -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` | — | diff --git a/docs/subsystems/client-modules.md b/docs/subsystems/client-modules.md index 5b058a2508..5ca5a8fe92 100644 --- a/docs/subsystems/client-modules.md +++ b/docs/subsystems/client-modules.md @@ -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) + + + +### `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(packageName: string): SyncedConfig | undefined +``` + +Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts) diff --git a/docs/subsystems/client-modules.zh.md b/docs/subsystems/client-modules.zh.md index 9b2af16fda..417484bf26 100644 --- a/docs/subsystems/client-modules.zh.md +++ b/docs/subsystems/client-modules.zh.md @@ -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) + + + +### `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(packageName: string): SyncedConfig | undefined +``` + +Source: [`packages/client/config/src/types.ts`](../../packages/client/config/src/types.ts) diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml new file mode 100644 index 0000000000..865b86f2a9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.i18n.yaml @@ -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 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md new file mode 100644 index 0000000000..702c95e6b0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md new file mode 100644 index 0000000000..2b301590d0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/client-hmr-plugin-events-stream/guide.zh.md @@ -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` 请求。 diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index 4caa0e8c59..9fa55c92ae 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -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 diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index 20f87506d0..1652849636 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -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. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index 008b6af7bb..5e6c04eb05 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -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 会立即注册,并自行负责启动顺序;进程内调用不变。 diff --git a/packages/api/gateway/src/index.ts b/packages/api/gateway/src/index.ts index bcde443e70..7d154e4d06 100644 --- a/packages/api/gateway/src/index.ts +++ b/packages/api/gateway/src/index.ts @@ -147,6 +147,7 @@ type ConnectionRpcError = Extract[' 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 = { [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', }, ) diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index 6f8e6b5124..f7c53ad389 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -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>() private readonly missedHeartbeats = new WeakMap() @@ -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 } +/** + * 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() private writes = Promise.resolve() + /** Encoded bytes queued and not yet written. */ + private queuedBytes = 0 + private drained: PromiseWithResolvers | 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 = 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 { + while (this.queuedBytes > this.streamOutboxBytes && this.socket.readyState === WebSocket.OPEN && !signal.aborted) { + this.drained ??= Promise.withResolvers() + const cancelled = Promise.withResolvers() + 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 { 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((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 diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index 244f82e383..b90e1c2b89 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -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() } diff --git a/packages/api/gateway/tests/stream-server.host.spec.ts b/packages/api/gateway/tests/stream-server.host.spec.ts index fcf5047c95..f94a4725a1 100644 --- a/packages/api/gateway/tests/stream-server.host.spec.ts +++ b/packages/api/gateway/tests/stream-server.host.spec.ts @@ -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((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((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 {})()) 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; 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((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() + 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((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((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() + 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((resolve) => { setImmediate(resolve) }) + const held = holdWrites(acceptedSocket(entry.mux)) + sources.a.push('a1') + sources.b.push('b1') + sources.a.push('a2') + await new Promise((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() + let opened = 0 + const allOpen = Promise.withResolvers() + 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((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((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((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 { const admitted = peer ?? await fixturePeer() const mux = new RemoteStreamMuxServer(open, mapFailure, { heartbeatIntervalMs, streamInboxBytes, + streamOutboxBytes, compression, }) const http = createServer() diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 7d977cb888..b8e829ae07 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -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' diff --git a/packages/client/config/README.i18n.yaml b/packages/client/config/README.i18n.yaml new file mode 100644 index 0000000000..4df7511484 --- /dev/null +++ b/packages/client/config/README.i18n.yaml @@ -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 diff --git a/packages/client/config/README.md b/packages/client/config/README.md new file mode 100644 index 0000000000..beaecbfdb6 --- /dev/null +++ b/packages/client/config/README.md @@ -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) + +----- + + +## 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` | 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` | 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(packageName)`, a read-only lookup of another package's current activation object; importing the types also declares `ctx.config` | + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +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. + +
+ +----- + + +## 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) + +----- + + +## 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 + + + +- `resolveConfigByPackage` trusts the caller's Config type argument; a wrong type is not detected. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/config/README.zh.md b/packages/client/config/README.zh.md new file mode 100644 index 0000000000..2a4e43bec6 --- /dev/null +++ b/packages/client/config/README.zh.md @@ -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) + +----- + + +## 使用本包 + +插件包把本包列入 `devDependencies`,只用 `import type` 从 `@deepseek-ai/dsh-client-config/types` 导入: + +| 类型 | 用途 | +|---|---| +| `SyncedConfig` | 共享 Config 类型为 `C` 的 Client 面的 `apply` 配置:每个顶层 `Volatile` 字段对应一个 `SyncedConfigRef`。每个字段都可能读到 `undefined`(密钥、无法投影的值,或尚未与浏览器代码对应的 Host 构建),插件在每次读取时处理缺值 | +| `SyncedConfigRef` | 单个字段:`get()` 读取当前冻结值,写法与 Host 读取 volatile 引用一致;`getSnapshot` 与 `subscribe` 使它可以直接作为可观察数据源注入 slot 的 `hooks`。它没有写操作 | +| `SyncedConfigValues` | 图行携带的单个插件同步字段的 JSON 值 | +| `SyncedConfigService` | `ctx.config.resolveConfigByPackage(packageName)`,只读地查询另一个包当前激活的对象;导入这些类型也同时声明了 `ctx.config` | + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本包通过 `./types` 与两个面导出类型,Host 与 Client 的 `apply` 都不注册任何内容。所有类型由 Client Modules 实现:Host 面把值投影进图行,页面条目控制器把对象交给每次插件激活并提供 `ctx.config`。因此插件依赖这些类型,而不是依赖启动最早的 Client Modules 包。 + +
+ +----- + + +## 进一步探索 + +- [Agent Note:前端插件配置同步](../../../.agents/notes/implemented/architecture/2026-11-15-client-config-sync.zh.md) +- [Client Modules 同步插件配置](../modules/README.zh.md#synced-plugin-configuration) + +----- + + +## 模型体验 + +无,本包声明浏览器配置类型,不注册任何面向模型的内容。 + +#### KV Cache 影响 + +无;本包既不组装也不发送 provider 请求。 + +## 已知限制与延期工作 + + + +- `resolveConfigByPackage` 信任调用方给出的 Config 类型参数,类型写错不会被发现。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/client/config/locale/de.json b/packages/client/config/locale/de.json new file mode 100644 index 0000000000..9923227d40 --- /dev/null +++ b/packages/client/config/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Typen für synchronisierte Konfiguration", + "description": "Typen zum Lesen der Live-Host-Konfiguration in Browser-Plugins." + } +} diff --git a/packages/client/config/locale/en.json b/packages/client/config/locale/en.json new file mode 100644 index 0000000000..9d2545045d --- /dev/null +++ b/packages/client/config/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Synced configuration types", + "description": "Types for reading live Host configuration in browser plugins." + } +} diff --git a/packages/client/config/locale/es.json b/packages/client/config/locale/es.json new file mode 100644 index 0000000000..56b2228770 --- /dev/null +++ b/packages/client/config/locale/es.json @@ -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." + } +} diff --git a/packages/client/config/locale/fr.json b/packages/client/config/locale/fr.json new file mode 100644 index 0000000000..91d3c8efcd --- /dev/null +++ b/packages/client/config/locale/fr.json @@ -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." + } +} diff --git a/packages/client/config/locale/ja.json b/packages/client/config/locale/ja.json new file mode 100644 index 0000000000..b7401bec41 --- /dev/null +++ b/packages/client/config/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "同期設定の型", + "description": "ブラウザープラグインがライブの Host 設定を読み取るための型。" + } +} diff --git a/packages/client/config/locale/pt.json b/packages/client/config/locale/pt.json new file mode 100644 index 0000000000..7ceeeca489 --- /dev/null +++ b/packages/client/config/locale/pt.json @@ -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." + } +} diff --git a/packages/client/config/locale/ru.json b/packages/client/config/locale/ru.json new file mode 100644 index 0000000000..43e7f38637 --- /dev/null +++ b/packages/client/config/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Типы синхронизированной конфигурации", + "description": "Типы для чтения актуальной конфигурации Host в браузерных плагинах." + } +} diff --git a/packages/client/config/locale/zh.json b/packages/client/config/locale/zh.json new file mode 100644 index 0000000000..3729979770 --- /dev/null +++ b/packages/client/config/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "同步配置类型", + "description": "浏览器插件读取实时 Host 配置所用的类型。" + } +} diff --git a/packages/client/config/package.json b/packages/client/config/package.json new file mode 100644 index 0000000000..110580e5c7 --- /dev/null +++ b/packages/client/config/package.json @@ -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" + ] +} diff --git a/packages/client/config/src/client/index.ts b/packages/client/config/src/client/index.ts new file mode 100644 index 0000000000..895b2816b9 --- /dev/null +++ b/packages/client/config/src/client/index.ts @@ -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 {} diff --git a/packages/client/config/src/index.ts b/packages/client/config/src/index.ts new file mode 100644 index 0000000000..b80c7fc15e --- /dev/null +++ b/packages/client/config/src/index.ts @@ -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 {} diff --git a/packages/client/config/src/types.ts b/packages/client/config/src/types.ts new file mode 100644 index 0000000000..1553730bf6 --- /dev/null +++ b/packages/client/config/src/types.ts @@ -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 extends Volatile, ObservableSnapshot> {} + +/** + * 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 = { + readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: + NonNullable extends Volatile ? SyncedConfigRef : 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(packageName: string): SyncedConfig | 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 + } +} diff --git a/packages/client/config/tests/apply.client.spec.ts b/packages/client/config/tests/apply.client.spec.ts new file mode 100644 index 0000000000..bcd696fec6 --- /dev/null +++ b/packages/client/config/tests/apply.client.spec.ts @@ -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() +}) diff --git a/packages/client/config/tsconfig.json b/packages/client/config/tsconfig.json new file mode 100644 index 0000000000..337ff3d33d --- /dev/null +++ b/packages/client/config/tsconfig.json @@ -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" } + ] +} diff --git a/packages/client/config/tsdown.config.ts b/packages/client/config/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/config/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/hmr/README.i18n.yaml b/packages/client/hmr/README.i18n.yaml index 63402bfa3b..2604e22138 100644 --- a/packages/client/hmr/README.i18n.yaml +++ b/packages/client/hmr/README.i18n.yaml @@ -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 diff --git a/packages/client/hmr/README.md b/packages/client/hmr/README.md index 93cdef6c0e..0ca27432ef 100644 --- a/packages/client/hmr/README.md +++ b/packages/client/hmr/README.md @@ -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`) | @@ -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. ### Dev Note diff --git a/packages/client/hmr/README.zh.md b/packages/client/hmr/README.zh.md index cb893bd851..b38d3bf410 100644 --- a/packages/client/hmr/README.zh.md +++ b/packages/client/hmr/README.zh.md @@ -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`) | @@ -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 的安装不使用这条流;条目对账本身不依赖传输。 ### 开发备注 diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index 47a546bdc8..f532774873 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -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" ] } diff --git a/packages/client/hmr/src/client/index.ts b/packages/client/hmr/src/client/index.ts index 1e44b3db64..3e514fc816 100644 --- a/packages/client/hmr/src/client/index.ts +++ b/packages/client/hmr/src/client/index.ts @@ -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 +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 = 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): AsyncIterable { + 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 +} + +/** 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 { - 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 { + // `$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({ + 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(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> { + const unmount = await ctx.remote.$mount(pluginEventsRemote) const entries = ctx.modules.entries - const handle = (frame: Extract['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 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) => { receive(event.data) }) - return () => { source.close() } - }, 'client-hmr: event source') + ctx.remoteAccess.whenAccess('pluginEvents/follow', () => followPluginEvents(ctx, sinks)) + return unmount } diff --git a/packages/client/hmr/src/events.ts b/packages/client/hmr/src/events.ts deleted file mode 100644 index b041b67a48..0000000000 --- a/packages/client/hmr/src/events.ts +++ /dev/null @@ -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 } - | { 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 - 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) diff --git a/packages/client/hmr/src/index.ts b/packages/client/hmr/src/index.ts index bfef8803a0..c07826c697 100644 --- a/packages/client/hmr/src/index.ts +++ b/packages/client/hmr/src/index.ts @@ -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 = 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 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() - - 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) } diff --git a/packages/client/hmr/src/plugin-events.ts b/packages/client/hmr/src/plugin-events.ts new file mode 100644 index 0000000000..edf2217756 --- /dev/null +++ b/packages/client/hmr/src/plugin-events.ts @@ -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() + 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 { + return new Promise((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() + + /** @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 { + 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 diff --git a/packages/client/hmr/src/types.ts b/packages/client/hmr/src/types.ts new file mode 100644 index 0000000000..4d7ff2a2b1 --- /dev/null +++ b/packages/client/hmr/src/types.ts @@ -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 diff --git a/packages/client/hmr/tests/events.client.spec.ts b/packages/client/hmr/tests/events.client.spec.ts deleted file mode 100644 index 5fa07b800e..0000000000 --- a/packages/client/hmr/tests/events.client.spec.ts +++ /dev/null @@ -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' }) - } - }) -}) diff --git a/packages/client/hmr/tests/generated-remote-stub.ts b/packages/client/hmr/tests/generated-remote-stub.ts new file mode 100644 index 0000000000..43231c5f9a --- /dev/null +++ b/packages/client/hmr/tests/generated-remote-stub.ts @@ -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) diff --git a/packages/client/hmr/tests/node-half.client.spec.ts b/packages/client/hmr/tests/node-half.host.spec.ts similarity index 64% rename from packages/client/hmr/tests/node-half.client.spec.ts rename to packages/client/hmr/tests/node-half.host.spec.ts index fb212b71c8..bbc48a1dd5 100644 --- a/packages/client/hmr/tests/node-half.client.spec.ts +++ b/packages/client/hmr/tests/node-half.host.spec.ts @@ -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, 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 = { - 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((resolve) => { started = resolve }) - const activation = new Promise((resolve) => { release = resolve }) - const cleanup = new Promise((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(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() - } -}) diff --git a/packages/client/hmr/tests/plugin-events.host.spec.ts b/packages/client/hmr/tests/plugin-events.host.spec.ts new file mode 100644 index 0000000000..3f57c81a8b --- /dev/null +++ b/packages/client/hmr/tests/plugin-events.host.spec.ts @@ -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 = { + 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, count: number): Promise { + 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() +}) diff --git a/packages/client/hmr/tests/transport.client.spec.ts b/packages/client/hmr/tests/transport.client.spec.ts index 40c78b86bf..7fbbb11d5c 100644 --- a/packages/client/hmr/tests/transport.client.spec.ts +++ b/packages/client/hmr/tests/transport.client.spec.ts @@ -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): Promise { + 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((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({ - 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; ended: () => Error & { code?: string } }[] = [] + const follow = vi.fn(async function *(_signal: AbortSignal): AsyncIterable { 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((_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() }) diff --git a/packages/client/hmr/tsconfig.client.json b/packages/client/hmr/tsconfig.client.json new file mode 100644 index 0000000000..2bc09cb73e --- /dev/null +++ b/packages/client/hmr/tsconfig.client.json @@ -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" + } + ] +} diff --git a/packages/client/hmr/tsconfig.host.json b/packages/client/hmr/tsconfig.host.json new file mode 100644 index 0000000000..b502ad0868 --- /dev/null +++ b/packages/client/hmr/tsconfig.host.json @@ -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" + } + ] +} diff --git a/packages/client/hmr/tsconfig.json b/packages/client/hmr/tsconfig.json index 00226929f0..2eca820546 100644 --- a/packages/client/hmr/tsconfig.json +++ b/packages/client/hmr/tsconfig.json @@ -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" } ] } diff --git a/packages/client/hmr/tsdown.config.ts b/packages/client/hmr/tsdown.config.ts index 7aa03cebc1..620261533c 100644 --- a/packages/client/hmr/tsdown.config.ts +++ b/packages/client/hmr/tsdown.config.ts @@ -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 }) diff --git a/packages/client/modules/README.i18n.yaml b/packages/client/modules/README.i18n.yaml index f7ba81c650..0a0c62f370 100644 --- a/packages/client/modules/README.i18n.yaml +++ b/packages/client/modules/README.i18n.yaml @@ -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 diff --git a/packages/client/modules/README.md b/packages/client/modules/README.md index 78a7dad1e0..364f0cc3bf 100644 --- a/packages/client/modules/README.md +++ b/packages/client/modules/README.md @@ -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. + +### 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)` 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. + ### Host release changes @@ -107,7 +114,10 @@ The host contributes structured index rows that inject, into ``: 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. diff --git a/packages/client/modules/README.zh.md b/packages/client/modules/README.zh.md index 9a25d0372c..df2bef5b73 100644 --- a/packages/client/modules/README.zh.md +++ b/packages/client/modules/README.zh.md @@ -46,6 +46,13 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启 已打开的 Web 页面通过 HMR 传输跟随 Host 的完整模块图。启用普通插件会添加其 Loader 条目;停用会移除条目,并在其异步 effect 完成清理后回收未使用的模块与样式。再次启用会加载一个带样式的实例。其他 Loader 贡献方的条目及活动条目仍需使用的共享模块会保留。插件页面显示当前页面的同步失败,并提供不改变 Host 启用状态的重试。 + +### 同步插件配置 + +插件 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)` 为每个字段收到一个 `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 原有配置解析;其行若同时带同步值,激活失败。 + ### 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 增长,同时保留一代竞态容忍。 diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index 218305021b..9d0fb61a44 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -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", diff --git a/packages/client/modules/src/client/entries.ts b/packages/client/modules/src/client/entries.ts index f2f27d1f32..087632acf1 100644 --- a/packages/client/modules/src/client/entries.ts +++ b/packages/client/modules/src/client/entries.ts @@ -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() + /** Latest synced values per package that has appeared in the graph, and the Config object of its current activation. */ + private readonly synced = new Map() private readonly revisions = new Map() private loader: Loader | undefined private queue: Promise = 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) diff --git a/packages/client/modules/src/client/index.ts b/packages/client/modules/src/client/index.ts index 8e4d023b2c..2a989e866a 100644 --- a/packages/client/modules/src/client/index.ts +++ b/packages/client/modules/src/client/index.ts @@ -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: (packageName: string) => modules.entries.resolveConfigByPackage(packageName) as SyncedConfig | undefined, + } + ctx.reflect.provide('config', config) } diff --git a/packages/client/modules/src/client/manifest.ts b/packages/client/modules/src/client/manifest.ts index c9dd84d1c2..4bcc7d84ca 100644 --- a/packages/client/modules/src/client/manifest.ts +++ b/packages/client/modules/src/client/manifest.ts @@ -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 }), }) } diff --git a/packages/client/modules/src/client/synced-config.ts b/packages/client/modules/src/client/synced-config.ts new file mode 100644 index 0000000000..b77e48b3ff --- /dev/null +++ b/packages/client/modules/src/client/synced-config.ts @@ -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 implements SyncedConfigRef { + #value: VolatileSnapshot + readonly #listeners = new Set<() => void>() + + /** + * @param value - frozen initial value. + * @param attach - receives the controller's port; called once during construction. + */ + constructor(value: VolatileSnapshot, attach: (port: RefPort) => void) { + this.#value = value + attach({ + set: (next) => { this.#value = next as VolatileSnapshot }, + notify: () => { notifySubscribers(this.#listeners, 'synced configuration') }, + }) + } + + /** @returns the current frozen value; undefined when the Host sends none. */ + readonly get: () => VolatileSnapshot = () => this.#value + /** @returns the same value as {@link get}. */ + readonly getSnapshot: () => VolatileSnapshot = () => 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() + private readonly refs = new Map>() + /** 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 { + let ref = this.refs.get(field) + if (ref === undefined) { + ref = new SyncedConfigReference(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) + } +} diff --git a/packages/client/modules/src/config-projection.ts b/packages/client/modules/src/config-projection.ts new file mode 100644 index 0000000000..89f8d4aa5c --- /dev/null +++ b/packages/client/modules/src/config-projection.ts @@ -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 + 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 { + return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'get') === 'function' +} + +function isRecord(value: unknown): value is Record { + 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(node: SchemaNode, key: K): NonNullable { + 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((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 { + const rebuilt: Record = {} + 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 = {} + 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 +} diff --git a/packages/client/modules/src/config-sync.ts b/packages/client/modules/src/config-sync.ts new file mode 100644 index 0000000000..f21acc34f7 --- /dev/null +++ b/packages/client/modules/src/config-sync.ts @@ -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() + /** + * 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() + /** Loader entry name per row of the last composed graph. */ + private rows = new Map() + /** Current root plugin fiber per Loader entry name; of entries sharing a name, the one seen last. */ + private readonly fibers = new Map() + /** `loader/volatile-update` listener disposer per Loader entry name. */ + private readonly watches = new Map 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, 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): 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 + } + } +} diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index 4581333515..b3afc6fea5 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -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() 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 } } diff --git a/packages/client/modules/src/types.ts b/packages/client/modules/src/types.ts new file mode 100644 index 0000000000..c90db962ae --- /dev/null +++ b/packages/client/modules/src/types.ts @@ -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' diff --git a/packages/client/modules/tests/entries.client.spec.ts b/packages/client/modules/tests/entries.client.spec.ts index cc2b53d8ff..1826deaa99 100644 --- a/packages/client/modules/tests/entries.client.spec.ts +++ b/packages/client/modules/tests/entries.client.spec.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; 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 } + 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 } + 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 } + 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() diff --git a/packages/client/modules/tests/node-half.client.spec.ts b/packages/client/modules/tests/node-half.client.spec.ts index e7a55ddfb0..06a9ec69d9 100644 --- a/packages/client/modules/tests/node-half.client.spec.ts +++ b/packages/client/modules/tests/node-half.client.spec.ts @@ -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', () => { diff --git a/packages/client/modules/tests/package-assets.client.spec.ts b/packages/client/modules/tests/package-assets.client.spec.ts index 1e63c951ac..ca0572e806 100644 --- a/packages/client/modules/tests/package-assets.client.spec.ts +++ b/packages/client/modules/tests/package-assets.client.spec.ts @@ -142,7 +142,7 @@ async function composeHost(): Promise { 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 } } } } } }, }) diff --git a/packages/client/modules/tests/synced-config.client.spec.ts b/packages/client/modules/tests/synced-config.client.spec.ts new file mode 100644 index 0000000000..db3bb9f79b --- /dev/null +++ b/packages/client/modules/tests/synced-config.client.spec.ts @@ -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, configs: Record = {}, 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 = {} + 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']) +}) diff --git a/packages/client/modules/tsconfig.json b/packages/client/modules/tsconfig.json index 29b30c0509..7cfab229e2 100644 --- a/packages/client/modules/tsconfig.json +++ b/packages/client/modules/tsconfig.json @@ -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"} ] } diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 3d891a9a5f..5efab8c1d9 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -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 }) diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 7a6a7c5bcd..1864682b88 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -77,7 +78,7 @@ async function bench() { 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' }, 'shell.overlay': { kind: 'list', scope: 'root' }, @@ -87,7 +88,7 @@ async function bench() { const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation, - }) + }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const provide = vi.spyOn(runtime.ctx.uiSession, 'provide') const chat = await runtime.mount({ inject: [...injectChat], apply: applyChat }) const sourceDescriptor = provide.mock.calls[0]?.[0] diff --git a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx index 44d054ada8..0464c6d74a 100644 --- a/packages/client/ui-chat/tests/fence-slot.client.spec.tsx +++ b/packages/client/ui-chat/tests/fence-slot.client.spec.tsx @@ -1,5 +1,6 @@ // @vitest-environment jsdom /** Chat's Markdown fence Slot over the assembled Conversation and Chat plugins. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -106,7 +107,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) { 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.sessions.add({ id: SID, summary: { title: 'F', displayTitle: 'F', cwd: '/proj' }, @@ -118,7 +119,7 @@ async function renderChat(events: readonly SessionEventLikeEntry[]) { 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) return runtime.renderRoot() } diff --git a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx index 5e0f5cd8e3..95775d73f5 100644 --- a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx +++ b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx @@ -3,6 +3,7 @@ * that outlives the Chat panel, and history scrollback never does. */ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it } from 'vitest' @@ -70,12 +71,12 @@ async function bench() { 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.declare({ 'shell.overlay': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, }) - const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + const conversation = await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) let descriptor: Parameters[0] | undefined const provide = runtime.ctx.uiSession.provide.bind(runtime.ctx.uiSession) runtime.ctx.uiSession.provide = (next) => { descriptor ??= next; return provide(next) } diff --git a/packages/client/ui-context-menu/README.i18n.yaml b/packages/client/ui-context-menu/README.i18n.yaml index da161da095..33fc925b51 100644 --- a/packages/client/ui-context-menu/README.i18n.yaml +++ b/packages/client/ui-context-menu/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 725b47765ee8f30b /deepseek-ai-dsh-client-ui-context-menu/use-this-package: - en: 892cfb46cfcddcc0 - zh: c534b44e7ef53522 + en: e07cd4cb97b6c77e + zh: 97bba9f554dce3c7 /deepseek-ai-dsh-client-ui-context-menu/use-this-package/register-actions: en: 11bea09005de2678 zh: d56e25d2d93022aa diff --git a/packages/client/ui-context-menu/README.md b/packages/client/ui-context-menu/README.md index 704d8f5043..40137c1d10 100644 --- a/packages/client/ui-context-menu/README.md +++ b/packages/client/ui-context-menu/README.md @@ -25,7 +25,7 @@ Add actions to right-click menus without importing a React component. Targets re ## Use this package -The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. +The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. It is a volatile field of the Host entry's Config, so a change in `cordis.yml` reaches open pages without remounting the plugin and applies from the next menu preparation. The plugin injects `useContextMenu` into every Slot scope through `ctx.slots.provideRoot`. Call `const { getTriggerProps } = useContextMenu()` once in the component and spread `getTriggerProps(target, handlers?)` onto each trigger. The factory is an ordinary function and can run in loops. It handles right-click, Shift+F10, the ContextMenu key, viewport coordinates, and focus without scrolling. Existing handlers run first; `preventDefault()` keeps their ownership and prevents duplicate handling by composed or nested bindings. Repeated, composing, and unrelated key events remain untouched. Pass `undefined` to retain native behavior, or a target resolver to read business state when the gesture begins. The resolved object is captured before focus changes. Plain children receive event props or a factory through props or an existing delegate; no additional React Context is needed. Special editors and canvases can call `ctx.contextMenus.open()` directly. diff --git a/packages/client/ui-context-menu/README.zh.md b/packages/client/ui-context-menu/README.zh.md index 1fc68c3a1e..952d5896d2 100644 --- a/packages/client/ui-context-menu/README.zh.md +++ b/packages/client/ui-context-menu/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。 +Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。它是 Host 条目 Config 中的 volatile 字段,因此在 `cordis.yml` 中修改后,已打开的页面无需重新挂载插件,从下一次准备菜单起生效。 插件通过 `ctx.slots.provideRoot` 向每个 Slot 作用域注入 `useContextMenu`。组件调用一次 `const { getTriggerProps } = useContextMenu()`,再将 `getTriggerProps(target, handlers?)` 展开到各个触发元素上。该工厂是普通函数,可以在循环中调用;它统一处理右键、Shift+F10、ContextMenu 键、视口坐标及无滚动聚焦。已有处理器先运行,`preventDefault()` 保留其处理权,并防止组合或嵌套绑定重复处理。重复、输入法组合及无关按键保持原状。传入 `undefined` 保留原生行为,也可传入目标解析函数,在手势开始时读取业务状态。解析后的对象会在焦点变化前捕获。普通子组件通过 props 或现有 delegate 接收事件 props 或工厂,无需额外 React Context。特殊编辑器和 Canvas 可直接调用 `ctx.contextMenus.open()`。 diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json index e9c383ed59..9f56f52474 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -44,8 +44,10 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, "devDependencies": { - "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -59,7 +61,8 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*" + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-context-menu/src/client/index.ts b/packages/client/ui-context-menu/src/client/index.ts index b4244c4153..8d5f16a5f3 100644 --- a/packages/client/ui-context-menu/src/client/index.ts +++ b/packages/client/ui-context-menu/src/client/index.ts @@ -4,7 +4,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-locale/client' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ContextMenuConfig } from '../types.ts' import { MENU_TRANSITION_MS } from '@deepseek-ai/dsh-client-ui-primitives' import { menuTargetKey } from './target-key.ts' import { MenuRegistry } from './registry.ts' @@ -44,15 +45,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { /** Menu operation feedback. */ contextMenu: 'failed' | 'back' } } -/** Maximum time to prepare each contribution before omitting its pending actions. */ -export interface Config { resolutionTimeoutMs?: number } -/** Validated Client menu preparation budget. */ -export const Config: z = z.object({ resolutionTimeoutMs: z.natural().min(1).default(1000) }) +/** Preparation budget while the Host sends none; the value the Client used before the field moved to the Host. */ +const ABSENT_RESOLUTION_TIMEOUT_MS = 1000 /** Required overlay and localization services. */ export const inject = ['slots', 'locale', 'shortcuts'] -/** @param ctx - plugin-owned Client context. @param config - validated preparation budget. */ -export function apply(ctx: Context, config: Config = Config({})): void { +/** @param ctx - plugin-owned Client context. @param config - Host-synced preparation budget, read when each menu prepares. */ +export function apply(ctx: Context, config: SyncedConfig): void { ctx.effect(() => ctx.locale.register('contextMenu', dictionaries), 'context menu: locale') const t = ctx.locale.bind('contextMenu') const handle = createMenuStore() @@ -81,7 +80,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }, } } }) } - const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, config.resolutionTimeoutMs) + const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, () => config.resolutionTimeoutMs.get() ?? ABSENT_RESOLUTION_TIMEOUT_MS) const cancelOpening = (): void => { clearTimeout(openingTimer); finishOpening?.(); finishOpening = undefined active?.unsubscribe(); active?.resolution.dispose(); active = undefined diff --git a/packages/client/ui-context-menu/src/client/registry.ts b/packages/client/ui-context-menu/src/client/registry.ts index af89692538..b4d580dd3a 100644 --- a/packages/client/ui-context-menu/src/client/registry.ts +++ b/packages/client/ui-context-menu/src/client/registry.ts @@ -20,7 +20,10 @@ export class MenuRegistry { private readonly providers = new Map() private readonly occurrences = new Set<() => void>() private disposed = false - constructor(private readonly failed: (message?: string) => void, private readonly timeoutMs?: number) {} + constructor( + private readonly failed: (message?: string) => void, + private readonly timeoutMs: () => number | undefined = () => undefined, + ) {} /** * Register actions for subsequent openings. @@ -110,9 +113,10 @@ export class MenuRegistry { const result = provider.resolve(target, signal) if (result instanceof Promise) clear() preparing = result instanceof Promise ? new Promise((settle) => { - const timer = this.timeoutMs === undefined ? undefined : setTimeout(() => { + const timeoutMs = this.timeoutMs() + const timer = timeoutMs === undefined ? undefined : setTimeout(() => { deadline.abort(); this.failed() - }, this.timeoutMs) + }, timeoutMs) const finish = (): void => { clearTimeout(timer); signal.removeEventListener('abort', finish); settle() } signal.addEventListener('abort', finish, { once: true }) void result.then(accept).catch(() => { if (!signal.aborted) this.failed() }).finally(finish) diff --git a/packages/client/ui-context-menu/src/index.ts b/packages/client/ui-context-menu/src/index.ts index 77258040c7..c639cbcea8 100644 --- a/packages/client/ui-context-menu/src/index.ts +++ b/packages/client/ui-context-menu/src/index.ts @@ -1,4 +1,14 @@ -/** Host Loader entry; menus belong to the Client. */ +/** Host Loader entry declaring the browser menu preparation budget; menus belong to the Client. */ +import z from '@deepseek-ai/schemastery' +import type { ContextMenuConfig } from './types.ts' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export type Config = ContextMenuConfig + +/** Live preparation budget synced to the browser. */ +export const Config = z.object({ + resolutionTimeoutMs: z.natural().min(1).default(1000).volatile(), +}) /** Register the browser plugin without Host behavior. */ export function apply(): void {} diff --git a/packages/client/ui-context-menu/src/types.ts b/packages/client/ui-context-menu/src/types.ts new file mode 100644 index 0000000000..20e045cfeb --- /dev/null +++ b/packages/client/ui-context-menu/src/types.ts @@ -0,0 +1,8 @@ +/** Context-menu plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' + +/** Live preparation budget; the browser receives it through its synced Config. */ +export interface ContextMenuConfig { + /** Maximum time in milliseconds to prepare each contribution before omitting its pending actions. */ + resolutionTimeoutMs: Volatile +} diff --git a/packages/client/ui-context-menu/tests/button.client.spec.tsx b/packages/client/ui-context-menu/tests/button.client.spec.tsx index 9b381ff29b..7c4c46d9c5 100644 --- a/packages/client/ui-context-menu/tests/button.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/button.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -35,7 +36,7 @@ it('shows late registered kinds without preparing actions and withdraws them wit ) const view = runtime.renderRoot() expect(view.queryByRole('button')).toBeNull() - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) expect(view.queryByRole('button')).toBeNull() const resolve = vi.fn(() => new Promise(() => {})) const row = await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ @@ -67,7 +68,7 @@ it('shows the label tooltip on the compact toolbar button but not on row buttons {renderFactorySlot('contextMenu.button', { target: target('header'), label: 'Header menu', size: 'sm' })} {renderFactorySlot('contextMenu.button', { target: target('row'), label: 'Row menu' })} ) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [], })) } }) @@ -99,7 +100,7 @@ it('toggles moved buttons by target identity, replaces other targets, and preser {renderSlot('shell.overlay', {})} }) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'header', target: 'header', order: 0, resolve: () => [{ id: 'open', label: 'Open' }], })) } }) @@ -170,7 +171,7 @@ it('keeps an open button expanded after its owner updates display metadata in th update = setCurrent return renderFactorySlot('contextMenu.button', { target: current, label: 'Entity menu' }) }) - await runtime.mount({ inject, apply }) + await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: ['contextMenus'], apply: (ctx: Context) => { ctx.effect(() => ctx.contextMenus.register({ id: 'entity', target: 'entity', order: 0, resolve: () => [], })) } }) diff --git a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx index b84e470bbe..718d3edad6 100644 --- a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { bindSnapshotSelector, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' @@ -97,7 +98,7 @@ it('dispatches captured icon keys in rows, submenus and footers and retires rend runtime.slots.installLocale(locale) await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ({ renderSlot }) => <>{renderSlot('shell.overlay', {})}) - const menuPlugin = await runtime.mount({ inject, apply }) + const menuPlugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const run = vi.fn() const contribution = await runtime.mount({ inject: ['contextMenus'], apply(ctx) { ctx.effect(() => ctx.contextMenus.register({ id: 'icons', target: 'session', order: 0, resolve: () => [ diff --git a/packages/client/ui-context-menu/tests/plugin.client.spec.ts b/packages/client/ui-context-menu/tests/plugin.client.spec.ts index 4d2ab784ba..81d8ebc835 100644 --- a/packages/client/ui-context-menu/tests/plugin.client.spec.ts +++ b/packages/client/ui-context-menu/tests/plugin.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import type { MenuAction } from '../src/client/types.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { Context } from '@deepseek-ai/cordis' @@ -28,7 +29,7 @@ it('lets an external contribution open another menu and withdraws its actions wh }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const menuFiber = ctx.plugin({ inject, apply }) + const menuFiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await menuFiber.await() expect(hostApply).not.toThrow() const run = vi.fn() @@ -101,7 +102,8 @@ it('waits for metadata, toggles nearby repeated gestures, replaces occurrences, register: (entry: { store: ReturnType }) => { store = entry.store.create(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + // No budget from the Host: preparation uses the 1000ms the Client used before the field moved to the Host. + const fiber = ctx.plugin({ inject, apply }, syncedConfig({})) await fiber.await() let finish!: (actions: readonly MenuAction[]) => void ctx.contextMenus.register({ target: 'pluginDocument', id: 'slow', order: 0, @@ -148,7 +150,7 @@ it('keeps trigger focus through replacement and ignores non-dismissal events and register: (entry: { inject: () => MenuOverlayInjected }) => { overlay = entry.inject(); return () => {} }, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() const notify = ctx.contextMenus.notify.bind(ctx.contextMenus) ctx.contextMenus.register({ target: 'pluginDocument', id: 'plain', order: 0, resolve: () => [{ id: 'copy', label: 'Copy' }] }) @@ -194,7 +196,7 @@ it('leaves unbound keyboard gestures native', async () => { inject: () => () => {}, } as never) ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) - const fiber = ctx.plugin({ inject, apply }) + const fiber = ctx.plugin({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) await fiber.await() try { const event = new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true }) diff --git a/packages/client/ui-context-menu/tests/registry.client.spec.ts b/packages/client/ui-context-menu/tests/registry.client.spec.ts index 20f77e808b..ea7c2ea7d0 100644 --- a/packages/client/ui-context-menu/tests/registry.client.spec.ts +++ b/packages/client/ui-context-menu/tests/registry.client.spec.ts @@ -175,7 +175,7 @@ describe('menu contribution lifecycle', () => { it('omits a provider that misses its deadline and ignores its late result', async () => { vi.useFakeTimers() - const failed = vi.fn(), registry = new MenuRegistry(failed, 50) + const failed = vi.fn(), registry = new MenuRegistry(failed, () => 50) const waiting = deferred() let signal!: AbortSignal registry.register({ id: 'slow', target: 'extension', order: 0, resolve: (_target, value) => { signal = value; return waiting.promise } }) diff --git a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx index 507911379f..2af1690b61 100644 --- a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx +++ b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, createEvent, fireEvent, render } from '@testing-library/react' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { createPortal } from 'react-dom' @@ -85,7 +86,7 @@ it('injects the hook through the root Slot and withdraws both its prop and retai retained = useContextMenu().getTriggerProps(target('injected')) return }) - const plugin = await runtime.mount({ inject, apply }) + const plugin = await runtime.mount({ inject, apply }, syncedConfig({ resolutionTimeoutMs: 1000 })) const view = runtime.renderRoot() expect(received).toBe(true) act(() => { fireEvent.contextMenu(view.getByRole('button')) }) diff --git a/packages/client/ui-context-menu/tsconfig.json b/packages/client/ui-context-menu/tsconfig.json index e12f61a4c8..572b52f447 100644 --- a/packages/client/ui-context-menu/tsconfig.json +++ b/packages/client/ui-context-menu/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 89ea06d3e0..3ab67ca713 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 4919c08c24d2453b - zh: 45566252950a1ed1 + en: e06ba99fdd2f3e1c + zh: 0fb899d6cedb351a /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 528c8e368c..acfb61d3f5 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -132,7 +132,7 @@ Clicking unused space inside an editable composer preserves its current caret or Each composer attempt carries its original occurrence time, gesture, delivery intent, and Session model/run-state snapshot through asynchronous command arbitration. The snapshot also records whether the Session is still blank and the Agent preset id the Session records. The ordinary-message notification fires once before reference serialization, including attachment-only submissions; handled or claimed commands do not notify. Snapshot and notification failures cannot block sending. On Desktop, the notification reports `send_button_click`, which carries `is_new_session` (true while the Session is blank) and `agent_preset`, the preset category: `creator` for `cordis`; `ptc`, `minimal`, and `standard` under their own ids; `other` for any other preset. `agent_preset` is omitted while the Session records no preset. Custom preset ids are not sent. -A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. +A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads`, a volatile field of the Host entry's Config, defaults to two active Worker transports and a raised value starts queued transfers at once, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. Every mounted composer, including a subagent conversation open in the right Sidebar, joins one document-level paste route. A paste whose clipboard carries files, while focus is outside any input, text area, or editable element, enters the composer that most recently held focus, or the main Conversation's composer before any other composer has held focus or while the focused one cannot accept files; a paste inside a focused editor stays with that editor, and clipboard text without files is never inserted this way. A composer in a hidden or inert subtree, such as a collapsed Sidebar or an unselected tab, is never addressed, and while a modal dialog or menu is open only a composer inside it can be. When no addressable composer can accept files, the paste keeps the browser's default handling. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index c43343c7be..f727eeb1cd 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -132,7 +132,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 每次输入框提交都携带原始发生时间、操作来源、投递意图以及会话模型和运行状态快照,贯穿异步命令裁决。快照还记录会话是否仍为空白,以及会话记录的 Agent preset id。普通消息通知在引用序列化前发出一次,纯附件提交也遵循这一规则;已处理或认领的命令不发出通知。快照读取与通知消费异常不能阻断发送。在桌面端,该通知报告 `send_button_click`,携带 `is_new_session`(会话为空白时为 true)和表示 preset 类别的 `agent_preset`:`cordis` 记为 `creator`;`ptc`、`minimal` 与 `standard` 沿用各自的 id;其他 preset 记为 `other`。会话未记录 preset 时省略 `agent_preset`。不发送自定义 preset 的 id。 -默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 +默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 是 Host 条目 Config 中的 volatile 字段,默认允许两个 Worker transport 同时运行,调高后立即启动排队中的传输,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 每个已挂载的 composer(包括在右侧栏打开的子代理对话)都加入同一条文档级粘贴路由。焦点不在任何输入框、文本区域或可编辑元素内时,剪贴板带有文件的粘贴会进入最近一次获得焦点的 composer;在其他 composer 获得焦点之前,或最近聚焦的 composer 当前无法接收文件时,则进入主 Conversation 的 composer。已聚焦编辑器内的粘贴仍由该编辑器处理,不含文件的剪贴板文字不会经此插入。位于隐藏或 inert 子树中的 composer(例如折叠的侧栏或未选中的标签页)不会成为目标;打开模态对话框或菜单时,只有其中的 composer 可以成为目标。没有可作为目标的 composer 能接收文件时,粘贴保留浏览器的默认处理。 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index abfcd2fdab..737e3aa960 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -102,7 +102,8 @@ "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "zod": "4.6.6", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 4f292f0ece..b7b32009ed 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -2,7 +2,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Registers the target-neutral Conversation assembly, shell, input, and docks. */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' -import z from '@deepseek-ai/schemastery' +import type { SyncedConfig } from '@deepseek-ai/dsh-client-config/types' +import type { ConversationConfig } from '../types.ts' import type { ISessions, SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' import { IconPaperclipOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' @@ -67,16 +68,6 @@ export const inject = [ 'slots', 'sessions', 'fileUpload', 'uiSession', 'uiSession.sessionStatus', 'uiWorkspace', 'locale', 'configForms', ] -/** Conversation runtime configuration. */ -export interface Config { - /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ - maxConcurrentFileUploads?: number -} - -/** Validated Conversation runtime configuration. */ -export const Config: z = z.object({ - maxConcurrentFileUploads: z.natural().min(1).default(2), -}) // Stable no-session sources keep the renderer's observable-hook cache and // hook order unchanged across current-Session transitions. @@ -158,12 +149,12 @@ function concreteConversation(ctx: Context): ConversationController { /** * Mount the Conversation core and target-neutral presentation. * @param ctx - Client root context. + * @param config - Host-synced live configuration. */ -export function apply(ctx: Context, config: Config = Config({})): void { +export function apply(ctx: Context, config: SyncedConfig): void { const sessions = ctx.sessions const slots = ctx.slots - // Schemastery's field default is materialized before Cordis calls apply. - const maxConcurrentFileUploads = config.maxConcurrentFileUploads as number + const fileUploadLimit = config.maxConcurrentFileUploads const workspaceNavigation = ctx.get('uiWorkspace') as WorkspaceNavigation const uiConversation = new UiConversation(ctx, sessions) uiConversation.userText.register(sessionReferenceRule) @@ -602,7 +593,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { ctx.plugin(ConversationController, { input: inputHub, blocks: composerBlocks, - maxConcurrentFileUploads, + maxConcurrentFileUploads: fileUploadLimit, }) ctx.plugin(todoDockEntry) ctx.plugin(queueDockEntry) diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 8a1b95e941..b2ce918f76 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -24,8 +24,7 @@ export type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode, UserTextRule, UserTextTransformContext, } from './contract/user-text.ts' export type { UserTextRegistry } from './conversation/user-text-registry.ts' -export { apply, Config, inject } from './apply.ts' -export type { Config as ConversationConfig } from './apply.ts' +export { apply, inject } from './apply.ts' export { UiConversation } from './conversation/assembly.ts' export type { ConversationBinding } from './conversation/assembly.ts' export type { ConversationGroupRegistry } from './conversation/group-registry.ts' diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 98454ba0f0..e4eb324030 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -20,7 +20,7 @@ import type {} from '@deepseek-ai/dsh-client-file-upload/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { FileAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ComposerAttachment, ComposerFileAttachment, ComposerImageAttachment, DraftFileUpload, } from './contract/slots.ts' @@ -149,6 +149,9 @@ export class UnsupportedImageMediaTypeError extends Error { } } +/** Upload concurrency while the Host sends no limit; the value the Client used before the field moved to the Host. */ +const ABSENT_UPLOAD_LIMIT = 2 + /** Scope-addressed conversation service (root singleton, provided as `conversation`). */ export class ConversationController extends Service implements IConversation { /** The per-session input machine registry (SessionInputResolver face). */ @@ -172,7 +175,7 @@ export class ConversationController extends Service implements IConversation { readonly settle: () => void }> = [] private activeFileUploads = 0 - private readonly maxConcurrentFileUploads: number + private readonly maxConcurrentFileUploads: ObservableSnapshot /** * @param ctx - owning root context (the plugin apply context; the service @@ -184,12 +187,14 @@ export class ConversationController extends Service implements IConversation { constructor(ctx: Context, config: { input: SessionInputResolver blocks: ComposerBlocks - maxConcurrentFileUploads: number + /** Live upload concurrency limit, absent until the Host sends one; a raised limit starts queued uploads at once. */ + maxConcurrentFileUploads: ObservableSnapshot }) { super(ctx, 'conversation') this.input = config.input this.blocks = config.blocks this.maxConcurrentFileUploads = config.maxConcurrentFileUploads + ctx.effect(() => config.maxConcurrentFileUploads.subscribe(() => { this.pumpFileUploads() }), 'conversation: upload concurrency') ctx.effect(() => async () => { const operations = [...this.fileUploadOperations.values()] for (const operation of operations) operation.controller.abort() @@ -458,7 +463,7 @@ export class ConversationController extends Service implements IConversation { /** Start queued upload Workers until the configured concurrency is occupied. */ private pumpFileUploads(): void { - while (this.activeFileUploads < this.maxConcurrentFileUploads) { + while (this.activeFileUploads < (this.maxConcurrentFileUploads.getSnapshot() ?? ABSENT_UPLOAD_LIMIT)) { const task = this.fileUploadQueue.shift() if (task === undefined) return this.activeFileUploads += 1 diff --git a/packages/client/ui-conversation/src/index.ts b/packages/client/ui-conversation/src/index.ts index 90c4366a1a..23b557467b 100644 --- a/packages/client/ui-conversation/src/index.ts +++ b/packages/client/ui-conversation/src/index.ts @@ -1,9 +1,9 @@ /** Browser conversation preferences. */ import type {} from '@deepseek-ai/dsh-settings' -import type { Volatile, Context } from '@deepseek-ai/cordis' -import type { BusyEnterBehavior } from './submission-settings.ts' +import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +import type { ConversationConfig } from './types.ts' import { BUSY_ENTER_FIELD } from './submission-settings.ts' import { ConversationSettingsFields } from './submission-settings.ts' @@ -13,15 +13,13 @@ export { DEFAULT_BUSY_ENTER_BEHAVIOR, type BusyEnterBehavior, type ConversationSettings, } from './submission-settings.ts' -/** Runtime preferences projected to the browser. */ -export interface Config { - /** Enter key behavior while a turn is running. */ - busyEnter: Volatile -} +/** Live preferences; the browser receives every field through its synced Config. */ +export type Config = ConversationConfig /** Live preferences projected to the browser. */ export const Config = z.object({ [BUSY_ENTER_FIELD]: ConversationSettingsFields[BUSY_ENTER_FIELD].volatile(), + maxConcurrentFileUploads: z.natural().min(1).default(2).volatile(), }) /** Register browser conversation preferences. diff --git a/packages/client/ui-conversation/src/types.ts b/packages/client/ui-conversation/src/types.ts new file mode 100644 index 0000000000..e7138d1959 --- /dev/null +++ b/packages/client/ui-conversation/src/types.ts @@ -0,0 +1,11 @@ +/** Conversation plugin configuration shared by the Host and Client faces; types only. */ +import type { Volatile } from '@deepseek-ai/cordis' +import type { BusyEnterBehavior } from './submission-settings.ts' + +/** Live preferences; the browser receives every field through its synced Config. */ +export interface ConversationConfig { + /** Enter key behavior while a turn is running. */ + busyEnter: Volatile + /** Maximum generic-file uploads allowed to run concurrently in browser Workers. */ + maxConcurrentFileUploads: Volatile +} diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index e6384343ef..b5d57c4efd 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { render, cleanup } from '@testing-library/react' import { $getRoot, $isTextNode, PASTE_COMMAND } from 'lexical' @@ -110,7 +111,7 @@ async function bench(renderQuote = false) { 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' }, 'quote-probe': { kind: 'single', scope: 'session' }, @@ -120,7 +121,7 @@ async function bench(renderQuote = false) { ) : null) - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (renderQuote) await runtime.mount(messageQuotes) runtime.renderRoot() const entryOf = (key: 'main.conversation' | 'conversation.session' | 'conversation.session.header' | 'conversation.composer.bar') => diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index 154d31ec9f..907b6ec015 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { describe, expect, it, vi } from 'vitest' import { @@ -27,14 +28,14 @@ async function bench(options: { declareConversation?: boolean } = {}) { 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 })) if (options.declareConversation !== false) { await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, }, (_props: { renderSlot?: unknown }) => null) } - const feature = await runtime.mount({ inject: [...inject], apply }) + const feature = await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) if (options.declareConversation !== false) runtime.renderRoot() return { runtime, feature, developerTools } } diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index c8e96efdbc..b2506a1eab 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Conversation assembly acceptance independent of Tool presentation. */ import './control-row-dom.ts' @@ -88,7 +89,7 @@ async function bench(opts?: { blank?: boolean }) { 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.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -100,7 +101,7 @@ async function bench(opts?: { blank?: boolean }) { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) return runtime } @@ -113,9 +114,9 @@ describe('resident composer', () => { 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(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() const textarea = view.container.querySelector('[data-composer-input]') @@ -142,12 +143,12 @@ describe('resident composer', () => { 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.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1', title: 'Proj', path: '/proj', sessionIds: [SID] }] as never }) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) const view = runtime.renderRoot() @@ -211,7 +212,7 @@ describe('prompt rejection through the assembled composer', () => { 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 })) const prompt = vi.fn(async () => ({ ok: false, error: new RemoteError('session/agent-busy', 'prompt rejected before acceptance', { reason: 'busy' }), @@ -223,7 +224,7 @@ describe('prompt rejection through the assembled composer', () => { }) openSession(SID) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...inject], apply }) + await runtime.mount({ inject: [...inject], apply }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) const view = runtime.renderRoot() const composer = view.container.querySelector('[data-composer-input]')! diff --git a/packages/client/ui-conversation/tests/config.host.spec.ts b/packages/client/ui-conversation/tests/config.host.spec.ts index 25420eff00..5eb8088838 100644 --- a/packages/client/ui-conversation/tests/config.host.spec.ts +++ b/packages/client/ui-conversation/tests/config.host.spec.ts @@ -18,9 +18,11 @@ describe('ui-conversation host', () => { await ctx.plugin(SessionProjectionRegistry) const configuration = await liveConfig(ctx, HostPlugin) const { fiber } = configuration - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ + busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR, maxConcurrentFileUploads: 2, + }) await configuration.update({ busyEnter: 'steer' }) - expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer', maxConcurrentFileUploads: 2 }) await expect(configuration.update({ busyEnter: 'invalid' })).rejects.toThrow() await fiber.dispose() }) diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts index f758d2def7..df098003bb 100644 --- a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -3,6 +3,7 @@ // a removed Session releases them, and a page unload reports what it discarded. import { AttachmentId } from '@deepseek-ai/dsh-attachment' import { brandString } from '@deepseek-ai/dsh-brand' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -59,7 +60,7 @@ async function bench(prepare?: () => void) { await runtime.ctx.plugin(ConversationController, { input: hub, blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads: 2, + maxConcurrentFileUploads: createSnapshotStore(2), }).await() const root = runtime.ctx.get('conversation') as ConversationController const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index 9b93ef4240..51f14c108a 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -3,6 +3,7 @@ // TestSessions mints tagged scopes through the production createScope, so the // service's scopeOf/binding path runs against production resolution (no local // tag probe). +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { UserMessage } from '@deepseek-ai/dsh-llm/types' import type { MessageId } from '@deepseek-ai/dsh-llm/types' import { Context } from '@deepseek-ai/cordis' @@ -31,7 +32,7 @@ const UPLOAD_IMAGES = true /** `createDrafts` mode of a draft whose images travel inline, as a subagent continuation's do. */ const INLINE_IMAGES = false -async function bench(maxConcurrentFileUploads = 2) { +async function bench(maxConcurrentFileUploads: number | 'absent' = 2) { const runtime = await SlotTestRuntime.create() runtime.fileUpload.upload = (sessionId: SessionId, ...args: unknown[]) => { const session = runtime.sessions.behavior(sessionId) as { @@ -62,16 +63,17 @@ async function bench(maxConcurrentFileUploads = 2) { // config.input is required (the apply shares its hub with the inject // factories); the bench passes its own instance explicitly. const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + const uploadLimit = createSnapshotStore(maxConcurrentFileUploads === 'absent' ? undefined : maxConcurrentFileUploads) const fiber = runtime.ctx.plugin(ConversationController, { input: hub, blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads, + maxConcurrentFileUploads: uploadLimit, }) await fiber.await() const root = runtime.ctx.get('conversation') as ConversationController const scoped = runtime.sessions.scope('s1')!.get('conversation') as ConversationController const shell = hub.shellFor(runtime.sessions.binding('s1')!) - return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference } + return { runtime, fiber, root, scoped, hub, shell, prompt, updateQueue, cancel, loadOlder, reference, uploadLimit } } describe('ConversationController', () => { @@ -320,7 +322,8 @@ describe('ConversationController', () => { }) it('bounds upload Workers, advances on settlement, and skips a queued file removed by the user', async () => { - const b = await bench(2) + // With no limit from the Host, two uploads run at once, as before the limit moved to the Host. + const b = await bench('absent') const session = b.runtime.sessions.binding('s1')!.session type UploadResult = { ok: true @@ -369,6 +372,21 @@ describe('ConversationController', () => { await b.runtime.dispose() }) + it('starts a queued upload at once when the Host raises the upload limit', async () => { + const b = await bench(2) + const session = b.runtime.sessions.binding('s1')!.session + const uploadFile = vi.fn((_data: Uint8Array, _name?: string, signal?: AbortSignal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })) + ;(session as { uploadFile?: unknown }).uploadFile = uploadFile + b.root.createDrafts(session.sessionId, ['one', 'two', 'three'].map(name => + new File([Uint8Array.of(1)], `${name}.txt`, { type: 'text/plain' })), UPLOAD_IMAGES) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(2) }) + b.uploadLimit.set(3) + await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledTimes(3) }) + await b.runtime.dispose() + }) + it('keeps one upload alive and observable while another Session is open', async () => { const b = await bench() const session = b.runtime.sessions.binding('s1')!.session @@ -606,7 +624,7 @@ describe('ConversationController', () => { await bare.plugin(ConversationController, { input: new InputHub(bare, makeTranslate(zh, {})), blocks: new ComposerBlockRegistry(), - maxConcurrentFileUploads: 2, + maxConcurrentFileUploads: createSnapshotStore(2), }).await() const orphan = bare.get('conversation') as ConversationController await expect(orphan.send('x')).rejects.toThrow(/sessions service unavailable/) diff --git a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts index f1f93856f1..4bb28dc0c1 100644 --- a/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts +++ b/packages/client/ui-conversation/tests/stop-shortcut.client.spec.ts @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' import type { SessionPendingInteractionBase } from '@deepseek-ai/dsh-client-ui-session/client' import type { Shortcuts, ShortcutContext, ShortcutGesture } from '@deepseek-ai/dsh-client-shortcuts/client' @@ -30,7 +31,7 @@ async function bench() { await reference.ready const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) const fiber = runtime.ctx.plugin(ConversationController, { - input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: 2, + input: hub, blocks: new ComposerBlockRegistry(), maxConcurrentFileUploads: createSnapshotStore(2), }) await fiber.await() const conversation = new UiConversation(runtime.ctx, runtime.sessions) diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index 759d52d183..dcac12eda3 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -9,6 +9,9 @@ "src" ], "references": [ + { + "path": "../config" + }, { "path": "../../../vendor/schemastery" }, diff --git a/packages/client/ui-conversation/tsconfig.host.json b/packages/client/ui-conversation/tsconfig.host.json index ec30b21bfe..aed18a8dc9 100644 --- a/packages/client/ui-conversation/tsconfig.host.json +++ b/packages/client/ui-conversation/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/submission-settings.ts", + "src/types.ts", "src/index.ts" ], "references": [ diff --git a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx index 7393ce1d5a..d00a17cf35 100644 --- a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx @@ -3,6 +3,7 @@ * The account takeover inside the shipped composition: the frame-wide notice * chain, the account settings page, and the one shared native Platform host. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -111,7 +112,7 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) - await runtime.mount({ apply: applyMenus, inject: injectMenus }) + await runtime.mount({ apply: applyMenus, inject: injectMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) runtime.slots.installLocale(locale) runtime.ctx.effect(() => locale.register('settings.account', { en, zh }), 'spec: account dictionaries') await runtime.declare({ @@ -119,7 +120,7 @@ async function bench() { 'settings.section': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, }) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) let descriptor: Parameters[0] | undefined const provide = runtime.ctx.uiSession.provide.bind(runtime.ctx.uiSession) runtime.ctx.uiSession.provide = (next) => { descriptor ??= next; return provide(next) } diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 3d1f634711..1380ed4bab 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Sidebar presentation and tab subscriptions through the production slot renderer. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -81,7 +82,7 @@ async function mountSeat(viewportWidth = 1440, canShow = true, entryCount = 0, o const catalog = createSnapshotStore([]) runtime.ctx.provide('shortcuts', { register: () => () => {}, catalog } as never) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.declare({ 'sidebar-right.test.opener': { kind: 'single', scope: 'session' }, 'rightbar': { kind: 'single', scope: 'root' }, diff --git a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx index 5dc1711ca4..c2172a1ab4 100644 --- a/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-tool/tests/assembly-surfaces.client.spec.tsx @@ -1,3 +1,4 @@ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { toolSessionEvents } from './tool-fixtures.client.ts' @@ -104,7 +105,7 @@ async function bench(nodes: ToolResultNode[]) { 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.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -116,7 +117,7 @@ async function bench(nodes: ToolResultNode[]) { }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) return runtime diff --git a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx index 91cf3bc474..5e6968e33d 100644 --- a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx +++ b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -143,7 +144,7 @@ async function bench(snapshot: ChatSnapshot) { locale.register(CONVERSATION_NS, { zh: conversationZh, en: conversationEn }) 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(ROOT_CHILDREN, AppRoot) await runtime.mount({ inject: [...injectChat], apply: applyChat }) diff --git a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx index 0d16e96f13..0c68634e68 100644 --- a/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx +++ b/packages/client/ui-tool/tests/toolview-slot.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -100,7 +101,7 @@ async function bench(nodes: ToolResultNode[]) { 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.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/w' }, @@ -112,7 +113,7 @@ async function bench(nodes: ToolResultNode[]) { }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) return { runtime, slots: runtime.slots, layout, openWorkspacePath, sidebarRight } @@ -381,7 +382,7 @@ describe('registrant declaration injection', () => { 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(LAYOUT_CHILDREN, AppRoot) // Third-party posture, mounted BEFORE ui-conversation. Plugin apply runs, @@ -403,7 +404,7 @@ describe('registrant declaration injection', () => { expect(runtime.slots.entries('tool.call.toolview')).toHaveLength(0) // Mounting the package declares the slot and activates the waiting entry. - await runtime.mount({ inject: [...injectConversation], apply: applyConversation }) + await runtime.mount({ inject: [...injectConversation], apply: applyConversation }, syncedConfig({ busyEnter: 'queue', maxConcurrentFileUploads: 2 })) await runtime.mount({ inject: [...injectChat], apply: applyChat }) await runtime.mount({ inject: [...injectTool], apply: applyTool }) expect(runtime.slots.entries('tool.call.toolview').map(e => e.options.key)) diff --git a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx index 1adc908ff6..216348dd92 100644 --- a/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/access-assembly.client.spec.tsx @@ -7,6 +7,7 @@ * remote-access snapshot owner itself and renders the real slot tree, so the Workspace access Hooks * are the renderer's bindings over one non-owner snapshot. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, screen } from '@testing-library/react' import type { AccessEffect, RemoteEndpoint, TypertResourceKind } from '@deepseek-ai/dsh-api-remote-access/client' @@ -79,7 +80,7 @@ async function bench(access: ClientAccessState, options: { ungroupedSession?: Se { 'sidebar.workspaces': { kind: 'single', scope: 'root', inject: SECTION_INJECT } } as never, SidebarFrame as never, ) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: [...inject], apply }) return runtime } diff --git a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx index 26a7fe523e..2d245f47f8 100644 --- a/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx +++ b/packages/client/ui-workspace/tests/host-home-staleness.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' /** @@ -41,7 +42,7 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1' as WorkspaceId, title: 'Project', path: '/home/u/Documents/project', diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index fedc107546..ed0ada567b 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' /** @@ -49,7 +50,7 @@ async function createRuntime(): Promise { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) return runtime } diff --git a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx index c6e361a813..ae59b2fbe6 100644 --- a/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker-factory.client.spec.tsx @@ -9,6 +9,7 @@ * listed Workspaces, the occupancy-gated add entry, and the creation hop * before `onPick`. */ +import { syncedConfig } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, screen } from '@testing-library/react' import { useRef, useState } from 'react' @@ -95,7 +96,7 @@ async function bench(): Promise { sessionIds: [], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }] as never }) - await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }, syncedConfig({ resolutionTimeoutMs: 1000 })) await runtime.mount({ inject: [...inject], apply }) await runtime.root.declare({} as never, ImportDialog as never) runtime.renderRoot() diff --git a/packages/experimental/liveshare/package.json b/packages/experimental/liveshare/package.json index 6a54cb1dd0..ad4c49b727 100644 --- a/packages/experimental/liveshare/package.json +++ b/packages/experimental/liveshare/package.json @@ -93,6 +93,7 @@ "@deepseek-ai/dsh-api-workspace-files": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-file-upload": "workspace:*", + "@deepseek-ai/dsh-client-hmr": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-modules": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", diff --git a/packages/experimental/liveshare/src/client/endpoint-classification.ts b/packages/experimental/liveshare/src/client/endpoint-classification.ts index c880912024..869f5090ef 100644 --- a/packages/experimental/liveshare/src/client/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/client/endpoint-classification.ts @@ -9,6 +9,7 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-api-remote-access/remote' import type { RemoteEndpoint } from '@deepseek-ai/dsh-api-remote-access/client' +import type {} from '@deepseek-ai/dsh-client-hmr/remote' import type {} from '@deepseek-ai/dsh-cua/remote' import type {} from '@deepseek-ai/dsh-experimental-api-speech-to-text/remote' import type {} from '@deepseek-ai/dsh-experimental-claude-code-mods/remote' diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index 7d5a6129cf..6a1f62f889 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -42,6 +42,7 @@ export const VIEWER_ENDPOINT_CLASSES = { 'llm/listProviders': 'reader-global-read', // the page lists providers 'session/canOpenWorkspacePath': 'reader-global-read', // the page asks whether a path can be opened 'session/modelCatalog': 'reader-global-read', // the page reads the model catalog + 'pluginEvents/follow': 'reader-global-read', // the page follows the plugin graph; the Host sends a non-owner schema defaults, never configured values 'productAnalytics/enabled': 'reader-global-read', // the page asks whether this host accepts analytics 'productAnalytics/report': 'reader-global-read', // the page reports its own product events 'productAnalytics/watchPolicy': 'reader-global-read', // the page follows the analytics policy diff --git a/packages/experimental/liveshare/src/host/viewer-access-policy.ts b/packages/experimental/liveshare/src/host/viewer-access-policy.ts index c9fbac8422..6d4cc510bf 100644 --- a/packages/experimental/liveshare/src/host/viewer-access-policy.ts +++ b/packages/experimental/liveshare/src/host/viewer-access-policy.ts @@ -107,6 +107,7 @@ const VIEWER_GLOBAL_ROLE: RemoteAccessRole<'global'> = { 'session/control', 'session/list', 'session/modelCatalog', + 'pluginEvents/follow', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', diff --git a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts index 504fc19e27..0e7a07fd73 100644 --- a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts @@ -43,7 +43,7 @@ const CALL = { request: {} } */ const GLOBAL_ACTIONS = [ 'commands/list', 'llm/listConfigurableProviders', 'llm/listProviders', 'session/canOpenWorkspacePath', - 'session/control', 'session/list', 'session/modelCatalog', + 'session/control', 'session/list', 'session/modelCatalog', 'pluginEvents/follow', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', 'speech/cancelPreparation', 'speech/catalog', 'speech/follow', 'speech/prepare', 'speech/transcribe', 'workspace/follow', diff --git a/packages/experimental/liveshare/tests/viewer-fixture.client.ts b/packages/experimental/liveshare/tests/viewer-fixture.client.ts index 775dabbd95..d08c678980 100644 --- a/packages/experimental/liveshare/tests/viewer-fixture.client.ts +++ b/packages/experimental/liveshare/tests/viewer-fixture.client.ts @@ -440,7 +440,8 @@ const FIXTURE_GLOBAL_READS = [ 'commands/list', 'llm/listConfigurableProviders', 'llm/listProviders', 'productAnalytics/enabled', 'productAnalytics/report', 'productAnalytics/watchPolicy', 'speech/cancelPreparation', 'speech/catalog', 'speech/follow', 'speech/prepare', 'speech/transcribe', - 'session/canOpenWorkspacePath', 'session/control', 'session/list', 'session/modelCatalog', 'workspace/follow', + 'session/canOpenWorkspacePath', 'session/control', 'session/list', 'session/modelCatalog', 'pluginEvents/follow', + 'workspace/follow', ] as const type FixtureControlFrame = diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 127c9db024..b5f37426fb 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -125,7 +125,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'contextMenu.content\', () => ctx.slots.register(\n { name: \'contextMenu.content\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-context-menu/src/client/index.ts:42', + source: 'packages/client/ui-context-menu/src/client/index.ts:43', }, { key: 'contextMenu.icon', @@ -171,7 +171,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'contextMenu.icon\', () => ctx.slots.register(\n { name: \'contextMenu.icon\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-context-menu/src/client/index.ts:40', + source: 'packages/client/ui-context-menu/src/client/index.ts:41', }, { key: 'conversation.approval.detail', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 29a6bea8cf..695b45116b 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -599,9 +599,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'graph(): WebBootGraph', - description: 'Current composed entry graph (stable object between changes).', + description: 'Current composed entry graph (stable object between changes), carrying the configured synced values.', parameters: [], - returns: 'the graph served as `window.__DSH_BOOT__`.', + returns: 'the graph served as the owner\'s `window.__DSH_BOOT__`.', + }, + { + signature: 'graphFor(principal: Principal | undefined): WebBootGraph', + description: '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.', + parameters: [{ name: 'principal', description: '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.', }, { signature: 'clientPath(id: string): string | undefined', @@ -635,7 +641,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'onGraphChanged(listener: () => void): () => void', - description: 'Fires after any flush that recomposed the graph (row added/removed, or a rebuilt rev change). Pull model: listeners re-read graph.', + description: '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 graph.', parameters: [{ name: 'listener', description: 'notified with no payload.' }], returns: 'the unsubscriber.', }, @@ -718,6 +724,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'config', + summary: 'Read-only access to other packages\' synced Config; a plugin receives its own through `apply`.', + description: 'Read-only access to other packages\' synced Config; a plugin receives its own through `apply`.', + methods: [ + { + signature: 'resolveConfigByPackage(packageName: string): SyncedConfig | undefined', + description: '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.', + parameters: [{ name: 'packageName', description: 'package name of the graph row.' }], + returns: 'the object, or undefined while no activation of the package is running.', + }, + ], + }, { key: 'configEditor', summary: 'Persist complete raw configs and apply them through the normal Loader path.', @@ -10292,6 +10311,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SurfaceSnapshot', declaration: 'export interface SurfaceSnapshot {\n readonly generation: number;\n readonly tree: readonly SerializedNode[] | null;\n}', }, + { + name: 'SyncedConfig', + declaration: 'export type SyncedConfig = {\n readonly [K in keyof C as NonNullable extends Volatile ? K : never]-?: NonNullable extends Volatile ? SyncedConfigRef : never;\n};', + }, + { + name: 'SyncedConfigRef', + declaration: 'export interface SyncedConfigRef extends Volatile, ObservableSnapshot> {\n}', + }, + { + name: 'SyncedConfigValues', + declaration: 'export type SyncedConfigValues = {\n readonly [field: string]: JsonValue;\n};', + }, { name: 'SystemMessage', declaration: 'export interface SystemMessage extends MessageBase {\n readonly role: \'system\';\n readonly source: MessageSourceMap[\'system-prompt\'];\n}', @@ -10914,7 +10945,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WebBootEntry', - declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n}', + declaration: 'export interface WebBootEntry {\n id: string;\n url: string;\n rev: string;\n inject?: string[];\n immediately?: boolean;\n external?: string[];\n config?: SyncedConfigValues;\n}', }, { name: 'WebBootGraph', diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 42de37bfbc..7d790712a9 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -64,9 +64,10 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| +| `@deepseek-ai/dsh-client-config` | no | Types of browser-synced plugin configuration | | `@deepseek-ai/dsh-client-connection` | yes | Authenticated RPC transport and generation lifecycle | | `@deepseek-ai/dsh-client-file-upload` | no | Agent-scoped browser file upload, streaming intake, and staged receipt service | -| `@deepseek-ai/dsh-client-hmr` | yes | Web client graph synchronization and rebuilt-bundle reload transport | +| `@deepseek-ai/dsh-client-hmr` | yes | Web client graph and rebuilt-bundle delivery over an authenticated Remote stream | | `@deepseek-ai/dsh-client-locale` | no | Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries | | `@deepseek-ai/dsh-client-modules` | no | Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam | | `@deepseek-ai/dsh-client-product-analytics` | yes | Desktop product event collection and authenticated Host reporting | diff --git a/packages/test-support/client-runtime/package.json b/packages/test-support/client-runtime/package.json index f20d9bfb91..9c129667e8 100644 --- a/packages/test-support/client-runtime/package.json +++ b/packages/test-support/client-runtime/package.json @@ -90,7 +90,8 @@ "@deepseek-ai/dsh-web-app": "workspace:*", "react": "^18.2.0", "react-dom": "^18.2.0", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-config": "workspace:*" }, "files": [ "lib/index.js", diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index 52002d2829..cfb6a626a1 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -63,5 +63,7 @@ export const remoteDefaultResponses: RemoteTable = { 'terminal/watch': openStream([[]]), // ui-connector-account `apply`: the registered connector accounts, none in a default composition, then open. 'connectorAccounts/watch': openStream([{ accounts: [] }]), + // client-hmr browser `apply`: open without a baseline, so the page keeps the boot graph the harness composed. + 'pluginEvents/follow': openStream(), }, } diff --git a/packages/test-support/client-runtime/src/assembly/remote-proxies.ts b/packages/test-support/client-runtime/src/assembly/remote-proxies.ts index d1a3b09142..3b88825ea5 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-proxies.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-proxies.ts @@ -23,22 +23,29 @@ export const REMOTES_PACKAGE = '@deepseek-ai/dsh-api-remotes' const PREFIX = 'remote.' +/** Namespaces a roster package mounts through its own generated Remote client; a proxy would collide with that mount. */ +const SELF_MOUNTED_NAMESPACES: Readonly> = { + pluginEvents: '@deepseek-ai/dsh-client-hmr', +} + /** * Namespaces to provide: every `remote.` a roster module injects, plus the - * namespace of every endpoint the mock has a rule for. - * @param modules - loaded roster modules. + * namespace of every endpoint the mock has a rule for, except a namespace that + * a roster package mounts itself. + * @param modules - loaded roster modules keyed by package name. * @param mock - the spec's mock. * @returns sorted namespace names. */ -export function remoteNamespacesOf(modules: Iterable, mock: RemoteMock): readonly string[] { +export function remoteNamespacesOf(modules: ReadonlyMap, mock: RemoteMock): readonly string[] { const names = new Set() - for (const module of modules) { + for (const module of modules.values()) { for (const service of injectNames(module.inject)) if (service.startsWith(PREFIX)) names.add(service.slice(PREFIX.length)) } for (const endpoint of mock.endpoints()) { const slash = endpoint.indexOf('/') if (slash > 0 && !endpoint.startsWith('$')) names.add(endpoint.slice(0, slash)) } + for (const [namespace, owner] of Object.entries(SELF_MOUNTED_NAMESPACES)) if (modules.has(owner)) names.delete(namespace) return [...names].sort() } diff --git a/packages/test-support/client-runtime/src/assembly/test-client.ts b/packages/test-support/client-runtime/src/assembly/test-client.ts index 0593eac143..698f8d9474 100644 --- a/packages/test-support/client-runtime/src/assembly/test-client.ts +++ b/packages/test-support/client-runtime/src/assembly/test-client.ts @@ -86,7 +86,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 5_000 /** * Browser globals jsdom lacks that roster plugins touch at apply or mount: - * client-hmr opens an `EventSource`; layout components observe size, media queries, and font loading. + * layout components observe size, media queries, and font loading. * Inert stand-ins, installed only where the global is absent. */ const JSDOM_SHIMS: Readonly> = { @@ -95,10 +95,6 @@ const JSDOM_SHIMS: Readonly> = { addListener() {}, removeListener() {}, }), - EventSource: class { - addEventListener(): void {} - close(): void {} - }, ResizeObserver: class { observe(): void {} disconnect(): void {} @@ -259,7 +255,7 @@ export class TestClient { mountPoint = resolveMountPoint(options.mount) release = sharedJsdomShims.acquire() const system = createInProcessModules(graphFromRoster(roster.rows), modules) - ctx.plugin(remoteProxiesPlugin(remoteNamespacesOf(modules.values(), mock), mock) as Plugin) + ctx.plugin(remoteProxiesPlugin(remoteNamespacesOf(modules, mock), mock) as Plugin) // The dropped remote-access row's Hooks: every action is allowed on every resource unless the spec fixes the answers. if (generated.includes(REMOTE_ACCESS_PACKAGE)) { ctx.plugin(options.access === undefined ? allowAllAccessPlugin : staticAccessPlugin(options.access)) diff --git a/packages/test-support/client-runtime/src/index.ts b/packages/test-support/client-runtime/src/index.ts index 5eee1c7a74..2ed5c0f75a 100644 --- a/packages/test-support/client-runtime/src/index.ts +++ b/packages/test-support/client-runtime/src/index.ts @@ -62,6 +62,7 @@ export type { FixtureSnapshot, SessionBehaviorOverrides, SessionFixture, SessionFixtureSnapshot, Stabilizer, } from './fixtures.ts' export { contextMenuHook } from './context-menu.ts' +export { syncedConfig } from './synced-config.ts' export { makeTranslate } from './translate.ts' export { allowAllAccess, allowAllAccessPlugin, StaticRemoteAccess, staticAccessPlugin } from './access.ts' export type { AccessStandardProps, StaticAccessPlugin } from './access.ts' @@ -310,15 +311,16 @@ export class SlotTestRuntime { * so a missing provider fails loud instead of suspending the fiber forever * (deliberate load-order suspension tests use `ctx.plugin` directly). * @param plugin - plugin value (function, class, or `{ inject, apply }` object). + * @param config - the plugin's `apply` config, such as a {@link syncedConfig} object for a Client face with synced fields. * @returns handle owning the fiber's explicit disposal. */ - async mount(plugin: Plugin): Promise { + async mount(plugin: Plugin, config?: unknown): Promise { const required = Object.keys(Inject.resolve((plugin as { inject?: Inject }).inject)) const missing = required.filter(name => this.ctx.get(name) === undefined) if (missing.length > 0) { throw new Error(`mount would suspend: missing service(s) ${missing.join(', ')} — provide() them first`) } - const fiber = this.ctx.plugin(plugin) + const fiber = this.ctx.plugin(plugin, config) await this.stabilizer(async () => { await fiber.await() }) diff --git a/packages/test-support/client-runtime/src/synced-config.ts b/packages/test-support/client-runtime/src/synced-config.ts new file mode 100644 index 0000000000..24cd67c675 --- /dev/null +++ b/packages/test-support/client-runtime/src/synced-config.ts @@ -0,0 +1,12 @@ +/** Synced Config objects for specs that mount a Client plugin face directly instead of through the page entry controller. */ +import type { SyncedConfig, SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types' +import { SyncedConfigEntry } from '@deepseek-ai/dsh-client-modules/src/client/synced-config.ts' + +/** + * Build the object a plugin activation receives as its `apply` config, holding fixed values. + * @param values - JSON values of the plugin's top-level volatile fields. + * @returns the activation's read-only Config object. + */ +export function syncedConfig(values: SyncedConfigValues): SyncedConfig { + return new SyncedConfigEntry(values).activate() as SyncedConfig +} diff --git a/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts index 4bd4835b59..81a653fa8c 100644 --- a/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-dependencies.client.spec.ts @@ -13,13 +13,14 @@ const hmrTest = createClientTest({ roster: hmrRoster }, { awaitConnected: false const sessionTest = createClientTest({ roster: sessionRoster }) describe('bundle dependency closures', () => { - hmrTest('activates HMR with its declared module provider and no Connection', async ({ start }) => { + hmrTest('activates HMR with its declared module and Remote carrier providers', async ({ start }) => { expect(hmrRoster.rows.map(row => row.name)).toContain(MODULES) const client = await start() const entry = [...client.ctx.loader.entries()].find(row => row.options.name === HMR) expect(entry?.fiber?.state).toBe(FiberState.ACTIVE) expect(client.ctx.get('modules')).toBeDefined() - expect(client.ctx.get('connection')).toBeUndefined() + expect(client.ctx.get('config')).toBeDefined() + expect(client.ctx.get('remote')).toBeDefined() }, 60_000) sessionTest('activates Session Controller with its declared file-upload provider', async ({ mock, start }) => { diff --git a/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts index 3f6593c120..a4f235b751 100644 --- a/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-remote-proxies.client.spec.ts @@ -18,12 +18,16 @@ async function drain(source: AsyncIterable): Promise { describe('remoteNamespacesOf', () => { it('collects remote. injects in both inject forms plus the namespaces of registered endpoints, skipping Gateway-internal ones', () => { - const modules: ClientPluginModule[] = [ - { apply() {}, inject: ['slots', 'remote.settings', 'remote'] }, - { apply() {}, inject: { 'remote.session': { required: true }, connection: { required: false } } }, - { apply() {} }, - ] + const modules = new Map([ + ['a', { apply() {}, inject: ['slots', 'remote.settings', 'remote'] }], + ['b', { apply() {}, inject: { 'remote.session': { required: true }, connection: { required: false } } }], + ['c', { apply() {} }], + ]) const mock = RemoteMock.create().unary('goals/create', ok({ id: 'g' })).stream('workspace/follow', openStream()) + .stream('pluginEvents/follow', openStream()) + expect(remoteNamespacesOf(modules, mock)).toEqual(['goals', 'pluginEvents', 'session', 'settings', 'workspace']) + // A namespace its own roster package mounts gets no proxy. + modules.set('@deepseek-ai/dsh-client-hmr', { apply() {} }) expect(remoteNamespacesOf(modules, mock)).toEqual(['goals', 'session', 'settings', 'workspace']) }) }) diff --git a/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts index 2dd5de587e..69236c6a78 100644 --- a/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-test-client.client.spec.ts @@ -19,7 +19,7 @@ const PARALLEL_PROBE = '@deepseek-ai/dsh-client-test-parallel-probe' /** Declared by ui-sidebar, whose SlotMap merge is outside this package's compilation face. */ const SIDEBAR_SETTINGS = 'sidebar.settings' as never const BRAND = '@deepseek-ai/dsh-client-ui-brand-official' -const globals = globalThis as { EventSource?: unknown; ResizeObserver?: unknown; matchMedia?: typeof window.matchMedia } +const globals = globalThis as { ResizeObserver?: unknown; matchMedia?: typeof window.matchMedia } /** The whole roster's first boot pays the cold module transform of every plugin package. */ const COLD_BOOT_TIMEOUT_MS = 60_000 @@ -44,7 +44,6 @@ describe('TestClient (jsdom)', () => { expect(document.body.contains(container)).toBe(true) expect(container.childElementCount).toBeGreaterThan(0) expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeDefined() expect(globals.ResizeObserver).toBeDefined() const query = globals.matchMedia!('(pointer: coarse)') expect(query.media).toBe('(pointer: coarse)') @@ -57,7 +56,6 @@ describe('TestClient (jsdom)', () => { await client.dispose() expect(document.body.contains(container)).toBe(false) expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeUndefined() expect(globals.ResizeObserver).toBeUndefined() expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBeUndefined() @@ -75,10 +73,10 @@ describe('TestClient (jsdom)', () => { }) const client = await started({ roster: API_ROSTER }) expect(globals.ResizeObserver).toBe(existing) - expect(globals.EventSource).toBeDefined() + expect(globals.matchMedia).toBeDefined() await client.dispose() expect(globals.ResizeObserver).toBe(existing) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBe(fonts) }) @@ -118,11 +116,11 @@ describe('TestClient (jsdom)', () => { expect(mockB.log.calls('session/rename')).toHaveLength(1) await a.dispose() expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeDefined() + expect(globals.matchMedia).toBeDefined() expect(document.fonts).toBeInstanceOf(EventTarget) await b.dispose() expect('__DSH_TRANSPORT__' in globalThis).toBe(false) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() expect(document.fonts).toBeUndefined() }) @@ -278,6 +276,6 @@ describe('TestClient (jsdom)', () => { const mock = RemoteMock.create().stream('$events', openStream([])) await expect(TestClient.start({ roster }, mock, { connectTimeoutMs: 300 })) .rejects.toThrow(/connection state is \S+ after 300ms; unmatched: \[unary workspace\/follow\]; streams: \[.*\$events \(open\).*\]/) - expect(globals.EventSource).toBeUndefined() + expect(globals.matchMedia).toBeUndefined() }) }) diff --git a/packages/test-support/client-runtime/tsconfig.json b/packages/test-support/client-runtime/tsconfig.json index 6301534ed9..9777e82c3b 100644 --- a/packages/test-support/client-runtime/tsconfig.json +++ b/packages/test-support/client-runtime/tsconfig.json @@ -12,6 +12,9 @@ "src" ], "references": [ + { + "path": "../../client/config" + }, { "path": "../../../vendor/cordis" }, @@ -91,7 +94,7 @@ "path": "../remote-mock" }, { - "path": "../../client/hmr" + "path": "../../client/hmr/tsconfig.client.json" }, { "path": "../../client/ui-context-menu" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a10b001fff..a14cc82f1f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3571,6 +3571,18 @@ importers: specifier: 0.2.3 version: 0.2.3 + packages/client/config: + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + packages/client/connection: dependencies: '@deepseek-ai/dsh-brand': @@ -3650,9 +3662,18 @@ importers: packages/client/hmr: dependencies: + '@deepseek-ai/dsh-deque': + specifier: workspace:* + version: link:../../util/deque + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -3660,15 +3681,15 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remote-access': + specifier: workspace:* + version: link:../../api/remote-access '@deepseek-ai/dsh-client-modules': specifier: workspace:* version: link:../modules - '@deepseek-ai/dsh-host-webserver': - specifier: workspace:* - version: link:../../host/webserver - eventsource-parser: - specifier: ^3.1.0 - version: 3.1.0 packages/client/locale: dependencies: @@ -3721,6 +3742,9 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../../vendor/loader + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-script-realm': specifier: workspace:* version: link:../script-realm @@ -3733,6 +3757,15 @@ importers: '@deepseek-ai/dsh-package-manifest': specifier: workspace:* version: link:../../util/package-manifest + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery packages/client/product-analytics: dependencies: @@ -4454,6 +4487,10 @@ importers: version: 18.3.1(react@18.3.1) packages/client/ui-context-menu: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -4461,6 +4498,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../locale @@ -4491,9 +4531,6 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session - '@deepseek-ai/schemastery': - specifier: link:../../../vendor/schemastery - version: link:../../../vendor/schemastery react: specifier: ^18.2.0 version: 18.3.1 @@ -4528,6 +4565,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../config '@deepseek-ai/dsh-client-file-upload': specifier: workspace:* version: link:../file-upload @@ -11513,6 +11553,9 @@ importers: '@deepseek-ai/dsh-client-file-upload': specifier: workspace:* version: link:../../client/file-upload + '@deepseek-ai/dsh-client-hmr': + specifier: workspace:* + version: link:../../client/hmr '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../../client/locale @@ -18841,6 +18884,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-client-config': + specifier: workspace:* + version: link:../../client/config '@deepseek-ai/dsh-client-connection': specifier: workspace:* version: link:../../client/connection diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 9364bc666e..b82bb3e81d 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -81,6 +81,7 @@ export const SERVICE_PAGE: Record = { shell: 'shell.md', shellEnv: 'shell.md', clientModules: 'client-modules.md', + config: 'client-modules.md', ptcRuntime: 'ptc-runtime.md', browserUse: 'browser-use.md', computerUse: 'computer-use.md', @@ -1067,6 +1068,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { ConnectorAccountRegistration: 'Plugins page account registration is owned by packages/client/ui-connector-account/README.md', ConnectorAccountsView: 'registered account stream item is owned by packages/client/ui-connector-account/README.md', ConnectorOperationId: 'account operation id is owned by packages/client/ui-connector-account/README.md', + SyncedConfig: 'packages/client/config/README.md', ActionCardDecision: 'packages/experimental/action-cards/README.md', ActionCardKind: 'packages/experimental/action-cards/README.md', ActionCardResult: 'packages/experimental/action-cards/README.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 21449ee8d8..4ab7f30dba 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -960,6 +960,15 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['harness-dev-context'], note: '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.', }, + { + key: 'config', + pkg: 'client-config', + title: 'Browser synced configuration lookup', + mode: 'service', + implementations: ['client-modules'], + consumers: [], + note: 'Types-only declaration; the client-modules plugin face provides the read-only lookup of each package\'s current synced Config.', + }, { key: 'clientModules', pkg: 'client-modules', diff --git a/scripts/no-unknown-casts.baseline.json b/scripts/no-unknown-casts.baseline.json index 5b255eabbd..f1ce3ad4af 100644 --- a/scripts/no-unknown-casts.baseline.json +++ b/scripts/no-unknown-casts.baseline.json @@ -370,12 +370,6 @@ "12a2d457945d43a02ab415318a8f6744ef620abd1fe272e12a164fa4ff476289": 1, "37d0e226122b7a3a4253e22583da5c77cc3690554dc959c74bf570589f3224fd": 1 }, - "packages/client/hmr/tests/node-half.client.spec.ts": { - "46197efe57255c9d92d64476470c89d0602c7333bf98ad75509bf43c1b357a3b": 1 - }, - "packages/client/hmr/tests/transport.client.spec.ts": { - "3f1a5cec801bec1f78158f48fca9f53657f85a8bb1f6ff4690fce56ab5ff8e98": 1 - }, "packages/client/locale/tests/apply.client.spec.ts": { "04984a2ce1486250236e638e0197da0a1a840855ed3975c59130a85358c7e5fe": 1 }, @@ -388,7 +382,6 @@ "packages/client/modules/tests/node-half.client.spec.ts": { "621628e4e895b24171e82d1b3fa3ecb12970e8eb0dfccab8bacc8c5784188a28": 2, "6c4ace8d135ab45685d0152eefb0f8156bbf95f66cefedd9a1a8da081d3cb180": 1, - "8eb8ea3592cbd4e828a33b2cbe2876089d3923738996fb2259ded563811a1a85": 1, "c4f0b7f87a16d26a1e4e7ef7a07991e789f0bbcfdbe2240a97fcd879668b5b3f": 1, "f549d88ac2b1db67fb33f18a024c116051ff83d3f8ad0433ba4ceedc679e9044": 2 }, diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts index 0217bfd484..d2a7fa1c1e 100644 --- a/scripts/plugin-entry-existing-exports.ts +++ b/scripts/plugin-entry-existing-exports.ts @@ -36,7 +36,6 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = { 'API_PATH', 'CONNECT_PATH', 'Peer', 'RpcId', 'clientRequestSchema', 'rpcErrorSchema', 'rpcIdSchema', 'rpcMessageSchema', 'rpcResultSchema', 'serverResponseSchema', 'transportError', ], - '@deepseek-ai/dsh-client-hmr': ['EVENTS_ENDPOINT'], '@deepseek-ai/dsh-client-locale': ['LOCALE_IDS', 'LOCALE_PREFERENCE_FIELD', 'LOCALE_SETTINGS_NAMESPACE'], '@deepseek-ai/dsh-client-modules': ['bootInjections', 'orderByModuleGraph', 'stripClientSuffix'], '@deepseek-ai/dsh-client-ui-chat': [ diff --git a/scripts/product-package-policy.ts b/scripts/product-package-policy.ts index dffe399876..5a72d4502f 100644 --- a/scripts/product-package-policy.ts +++ b/scripts/product-package-policy.ts @@ -53,4 +53,5 @@ export const PRODUCT_PACKAGE_POLICY: Readonly> = { * blocks. A package moves on or off this list with its context behavior. */ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { + 'packages/client/config': { kind: 'none', reason: 'Browser configuration types register nothing and add no model input.' }, 'packages/client/script-realm': { kind: 'none', reason: 'Optional browser execution-provider registration contributes no model input.' }, 'packages/client/script-realm-iframe': { kind: 'none', reason: 'Same-origin browser script environments contribute no model input.' }, 'packages/client/ui-context-menu': { kind: 'none', reason: 'Client menu presentation and contributed callbacks add no model input.' }, diff --git a/scripts/verify-product-use.ts b/scripts/verify-product-use.ts index d4a1f0a73b..f6472656b9 100644 --- a/scripts/verify-product-use.ts +++ b/scripts/verify-product-use.ts @@ -261,7 +261,7 @@ function validCategory(path: string, category: ProductPackagePolicy['category']) case 'sdk': return path === 'packages/sdk/client' case 'build': return path === 'packages/typert/generator' case 'web-distribution': return path === 'packages/client/web' || path === 'packages/client/ui-dockkit' - case 'declarations': return path === 'packages/util/package-manifest' + case 'declarations': return path === 'packages/util/package-manifest' || path === 'packages/client/config' default: return assertNever(category) } } diff --git a/tsconfig.base.json b/tsconfig.base.json index 4c59ea686e..81d372e5d6 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -310,8 +310,14 @@ "@deepseek-ai/dsh-client-file-upload/types": ["./packages/client/file-upload/src/types.ts"], "@deepseek-ai/dsh-api-remotes": ["./packages/api/remotes/src"], "@deepseek-ai/dsh-api-remotes/client": ["./packages/api/remotes/src/client/index.ts"], + "@deepseek-ai/dsh-client-config": ["./packages/client/config/src"], + "@deepseek-ai/dsh-client-config/client": ["./packages/client/config/src/client"], + "@deepseek-ai/dsh-client-config/types": ["./packages/client/config/src/types.ts"], "@deepseek-ai/dsh-client-hmr": ["./packages/client/hmr/src"], + "@deepseek-ai/dsh-client-hmr/client": ["./packages/client/hmr/src/client"], + "@deepseek-ai/dsh-client-hmr/types": ["./packages/client/hmr/src/types.ts"], "@deepseek-ai/dsh-client-modules": ["./packages/client/modules/src"], + "@deepseek-ai/dsh-client-modules/types": ["./packages/client/modules/src/types.ts"], "@deepseek-ai/dsh-cordis-client-runner": ["./packages/extensions/cordis-client-runner/src"], "@deepseek-ai/dsh-cordis-client-runner/client": ["./packages/extensions/cordis-client-runner/src/client"], "@deepseek-ai/dsh-client-ui-cordis": ["./packages/extensions/ui-cordis/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index e9970cfac2..23e80ae3c6 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -96,7 +96,8 @@ { "path": "./packages/experimental/liveshare/tsconfig.client.json" }, { "path": "./packages/experimental/session-inspector" }, { "path": "./packages/experimental/client-ui-forge/tsconfig.client.json" }, - { "path": "./packages/client/hmr" }, + { "path": "./packages/client/config" }, + { "path": "./packages/client/hmr/tsconfig.client.json" }, { "path": "./packages/client/connection/tsconfig.client.json" }, { "path": "./packages/client/file-upload/tsconfig.client.json" }, { "path": "./packages/typert/registry" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index de2f128aef..54885bffae 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -119,6 +119,7 @@ "apps/web/tests/plugin-install-github.e2e.ts", "apps/web/tests/plugin-install-silent-failure.e2e.ts", "apps/web/tests/client-plugin-live.e2e.ts", + "apps/web/tests/client-config-sync.e2e.ts", "apps/web/tests/icon-skin.e2e.ts", "apps/web/tests/draft-initialization.e2e.ts", "apps/web/tests/settings-chrome.e2e.ts", @@ -373,6 +374,7 @@ { "path": "./packages/util/home-paths" }, { "path": "./packages/client/ui-plugin-manager/tsconfig.host.json" }, { "path": "./packages/client/ui-trajectory/tsconfig.host.json" }, + { "path": "./packages/client/hmr/tsconfig.host.json" }, { "path": "./packages/client/ui-session-status/tsconfig.host.json" }, { "path": "./packages/util/time" }, { "path": "./packages/util/timeout" }, diff --git a/vitest.config.ts b/vitest.config.ts index 88cc120257..2925690a66 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -189,12 +189,16 @@ const claudeCodeTestingAliases = { 'claude-code': fileURLToPath(new URL('./packages/experimental/claude-code-mods/tests/support/claude-code.ts', import.meta.url)), } -// The LiveShare client entry statically imports its generated `./remote` contribution, which exists +// These client entries statically import their generated `./remote` contribution, which exists // only in built `lib/` output. On a clean checkout Vite resolves that import while transforming the // entry, before `vi.mock` can answer it, so the jsdom assembly suites need a resolvable stand-in. const liveshareRemoteBuild = fileURLToPath(new URL('./packages/experimental/liveshare/lib/typert.remote-client.js', import.meta.url)) const chatImportRemoteBuild = fileURLToPath(new URL('./packages/experimental/deepseek-chat-import/lib/typert.remote-client.js', import.meta.url)) +const hmrRemoteBuild = fileURLToPath(new URL('./packages/client/hmr/lib/typert.remote-client.js', import.meta.url)) const generatedRemoteAliases = { + ...existsSync(hmrRemoteBuild) ? {} : { + '@deepseek-ai/dsh-client-hmr/remote': fileURLToPath(new URL('./packages/client/hmr/tests/generated-remote-stub.ts', import.meta.url)), + }, ...existsSync(liveshareRemoteBuild) ? {} : { '@deepseek-ai/dsh-experimental-liveshare/remote': fileURLToPath(new URL('./packages/experimental/liveshare/tests/generated-remote-stub.ts', import.meta.url)), },