Merge remote-tracking branch 'origin/master' into dshw/pr-2423
# Conflicts: # packages/client/ui-sidebar/src/client/SidebarRoot.tsx
This commit is contained in:
@@ -89,9 +89,9 @@ If `test:gui` is red on code you did not touch, neither silently fix nor ignore
|
||||
|
||||
## New plugin package checklist
|
||||
|
||||
Bringing up a new `packages/client/<name>` plugin package (ui-workspace is a complete example; ui-sidebar/ui-question are minimal skeletons):
|
||||
Bringing up a new `packages/client/<name>` plugin package (ui-workspace is a complete example; ui-sidebar/ui-user-questions are minimal skeletons):
|
||||
|
||||
1. **Package skeleton**: `package.json` (`@deepseek-ai/dsh-client-<name>`, exports `.`/`./invariant`/`./client`/`./src/*`/`./package.json`, `dsh.client` manifest, `files` list), `tsconfig.json` (extends `tsconfig.base.client.json`, one `references` entry per workspace dependency plus `support/invariants`), `tsdown.config.ts` (`clientBundle(id, ['lib/types/index.js', 'lib/types/invariant.js'])`), `src/index.ts` (empty node-half apply), `src/invariant.ts` (companion with a real reason), `src/css-modules.d.ts` when using CSS Modules, `README.md` with the Model Experience section.
|
||||
1. **Package skeleton**: `package.json` (`@deepseek-ai/dsh-client-<name>`, exports `.`/`./invariant`/`./client`/`./src/*`/`./package.json`, `dsh.client` manifest, `files` list), `tsconfig.json` (extends `tsconfig.base.client.json`, one `references` entry per workspace dependency plus `runtime-diagnostics/invariants`), `tsdown.config.ts` (`clientBundle(id, ['lib/types/index.js', 'lib/types/invariant.js'])`), `src/index.ts` (empty node-half apply), `src/invariant.ts` (companion with a real reason), `src/css-modules.d.ts` when using CSS Modules, `README.md` with the Model Experience section.
|
||||
2. **Three registration surfaces, all required** (missing any one fails at a different, later point): the `tsconfig.client.json` aggregate `references` entry; a `dsh.client` row in `packages/bundle/web-app/cordis.patch.yml`; a `packages/bundle/web-app/package.json` dependency (profile boots resolve bare row names through the healed `$DSH_HOME/profiles/node_modules` fallback, which mirrors the app's and each bundle's declared dependencies — a row whose package no manifest declares fails to import). `pnpm-workspace.yaml` already globs `packages/*/*`.
|
||||
3. **dsh.client manifest semantics**: `platform: 'web'` always; `immediately: true` only for stage-one-prefetch infrastructure rows. `inject` lists package-name dependency edges — they are **informational only** (preflight display, HMR diffing); they do not sequence entry activation or apply order. Activation order is cordis fiber inject waiting on *services*, nothing else.
|
||||
4. **Registering into another package's slot**: apply order is unconstrained, and a business service is not a declaration barrier. Use `ctx.slots.inject(name, () => ctx.slots.register(...))`; it waits on the actual declaration, removes the contribution when that declaration collapses, reruns after redeclaration, and leaves with the caller's plugin fiber. Return a generator yielding each registration when several contributions must install and roll back atomically. A bare `slots.register` into an undeclared slot remains an error; keep service edges only for services the contribution actually reads.
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/README.md
|
||||
README.md: b9452d1f763be5be6953cb7973da8a2c909ed979
|
||||
README.zh.md: 0dfb6e6b6d619f111e36d5bdf57d127ac1ca9ef5
|
||||
README.md: f22ae99113f7f313c60304ac4c5fc53c8e3172ab
|
||||
README.zh.md: c4aa20c9f5f317bbe5dbb6f6731f6eb6d5d7ac7c
|
||||
+10
-10
@@ -14,7 +14,7 @@ The browser side of the dsh web GUI: shell boot, browser-host communication, sha
|
||||
| [`hmr/`](hmr/README.md) | Refreshes client plugins during development. |
|
||||
| [`locale/`](locale/README.md) | Provides localization preferences and message dictionaries. |
|
||||
| [`schema-form/`](schema-form/README.md) | Provides schema-backed draft handling for settings editors. |
|
||||
| [`test-runtime/`](test-runtime/README.md) | Provides shared repository test support for client feature packages. |
|
||||
| [`test-runtime/`](../test-support/client-runtime/README.md) | Provides shared repository test support for client feature packages. |
|
||||
| [`ui-slots/`](ui-slots/README.md) | Defines how UI features register and compose extension slots. |
|
||||
| [`ui-theme/`](ui-theme/README.md) | Applies the selected color theme. |
|
||||
| [`ui-primitives/`](ui-primitives/README.md) | Provides shared React controls, icons, and content renderers. |
|
||||
@@ -27,21 +27,21 @@ The browser side of the dsh web GUI: shell boot, browser-host communication, sha
|
||||
| [`ui-workflow-run/`](ui-workflow-run/README.md) | Replays durable workflow runs as nested Chat disclosures with live-only child navigation. |
|
||||
| [`ui-goal/`](ui-goal/README.md) | Presents and manages the current goal. |
|
||||
| [`ui-trajectory/`](ui-trajectory/README.md) | Presents alternate views of agent activity. |
|
||||
| [`ui-command/`](ui-command/README.md) | Provides session-aware command discovery and dispatch. |
|
||||
| [`ui-slash/`](ui-slash/README.md) | Coordinates inline command and reference suggestions. |
|
||||
| [`ui-commands/`](ui-commands/README.md) | Provides session-aware command discovery and dispatch. |
|
||||
| [`ui-input-trigger/`](ui-input-trigger/README.md) | Coordinates inline command and reference suggestions. |
|
||||
| [`ui-skill/`](ui-skill/README.md) | Adds skill references to inline suggestions. |
|
||||
| [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references. |
|
||||
| [`ui-task/`](ui-task/README.md) | Lists this session's background tasks in the conversation header. |
|
||||
| [`ui-model/`](ui-model/README.md) | Provides model selection in conversation surfaces. |
|
||||
| [`ui-permission/`](ui-permission/README.md) | Configures default permissions and switches the current session's access. |
|
||||
| [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs in the conversation header. |
|
||||
| [`ui-model-selection/`](ui-model-selection/README.md) | Provides model selection in conversation surfaces. |
|
||||
| [`ui-permission/`](ui-permission-presets/README.md) | Configures default permissions and switches the current session's access. |
|
||||
| [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control. |
|
||||
| [`ui-plugin-config/`](ui-plugin-config/README.md) | Owns the Plugins settings section, its tab extension point, and configurable host-plane plugin cards. |
|
||||
| [`ui-question/`](ui-question/README.md) | Presents interactive questions requested by the agent. |
|
||||
| [`ui-settings-plugins/`](ui-settings-plugins/README.md) | Owns the Plugins settings section, its tab extension point, and configurable host-plane plugin cards. |
|
||||
| [`ui-user-questions/`](ui-user-questions/README.md) | Presents interactive questions requested by the agent. |
|
||||
| [`ui-agent-preset/`](ui-agent-preset/README.md) | Selects a session's agent preset and authors preset compositions. |
|
||||
| [`ui-settings/`](ui-settings/README.md) | Hosts the settings interface and its extension areas. |
|
||||
| [`ui-settings-general/`](ui-settings-general/README.md) | Provides the general settings section. |
|
||||
| [`ui-models/`](ui-models/README.md) | Provides model-provider configuration and DeepSeek onboarding. |
|
||||
| [`ui-plugins/`](ui-plugins/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings. |
|
||||
| [`ui-settings-models/`](ui-settings-models/README.md) | Provides model-provider configuration and DeepSeek onboarding. |
|
||||
| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings. |
|
||||
|
||||
Each child reference owns its contract and detailed behavior. The [slot system standard](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md) and [web client architecture note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md) own the cross-package composition and loading decisions.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ dsh web GUI 的浏览器侧:shell 启动、浏览器与宿主通信、共享 U
|
||||
| [`hmr/`](hmr/README.md) | 在开发期间刷新客户端插件。 |
|
||||
| [`locale/`](locale/README.md) | 提供本地化偏好与消息词典。 |
|
||||
| [`schema-form/`](schema-form/README.md) | 为设置编辑器提供 schema 驱动的草稿处理。 |
|
||||
| [`test-runtime/`](test-runtime/README.md) | 为客户端功能包提供共享的仓库测试支持。 |
|
||||
| [`test-runtime/`](../test-support/client-runtime/README.md) | 为客户端功能包提供共享的仓库测试支持。 |
|
||||
| [`ui-slots/`](ui-slots/README.md) | 定义 UI 功能注册和组合扩展 slot 的方式。 |
|
||||
| [`ui-theme/`](ui-theme/README.md) | 应用所选颜色主题。 |
|
||||
| [`ui-primitives/`](ui-primitives/README.md) | 提供共享 React 控件、图标和内容渲染器。 |
|
||||
@@ -27,21 +27,21 @@ dsh web GUI 的浏览器侧:shell 启动、浏览器与宿主通信、共享 U
|
||||
| [`ui-workflow-run/`](ui-workflow-run/README.md) | 把持久工作流运行回放为 Chat 嵌套折叠项,并只为实时子 Session 提供导航。 |
|
||||
| [`ui-goal/`](ui-goal/README.md) | 展示和管理当前目标。 |
|
||||
| [`ui-trajectory/`](ui-trajectory/README.md) | 提供 agent(智能体)活动的其他视图。 |
|
||||
| [`ui-command/`](ui-command/README.md) | 提供会话感知的命令发现与分发。 |
|
||||
| [`ui-slash/`](ui-slash/README.md) | 协调内联命令和引用建议。 |
|
||||
| [`ui-commands/`](ui-commands/README.md) | 提供会话感知的命令发现与分发。 |
|
||||
| [`ui-input-trigger/`](ui-input-trigger/README.md) | 协调内联命令和引用建议。 |
|
||||
| [`ui-skill/`](ui-skill/README.md) | 向内联建议添加 skill(技能)引用。 |
|
||||
| [`ui-subagent/`](ui-subagent/README.md) | 提供 subagent(子 agent)导航、子级 transcript(文本记录)的状态和内联引用。 |
|
||||
| [`ui-task/`](ui-task/README.md) | 在会话标题栏列出当前会话的后台任务。 |
|
||||
| [`ui-model/`](ui-model/README.md) | 在对话界面中提供模型选择。 |
|
||||
| [`ui-permission/`](ui-permission/README.md) | 配置默认权限并切换当前会话的访问模式。 |
|
||||
| [`ui-jobs/`](ui-jobs/README.md) | 在会话标题栏列出当前会话的后台任务。 |
|
||||
| [`ui-model-selection/`](ui-model-selection/README.md) | 在对话界面中提供模型选择。 |
|
||||
| [`ui-permission/`](ui-permission-presets/README.md) | 配置默认权限并切换当前会话的访问模式。 |
|
||||
| [`ui-plan/`](ui-plan/README.md) | 展示生效中的 plan mode 状态及其退出控件。 |
|
||||
| [`ui-plugin-config/`](ui-plugin-config/README.md) | 拥有“插件”设置分区、它的标签页扩展点,以及可配置的宿主平面插件卡片。 |
|
||||
| [`ui-question/`](ui-question/README.md) | 展示 agent 请求的交互式问题。 |
|
||||
| [`ui-settings-plugins/`](ui-settings-plugins/README.md) | 拥有“插件”设置分区、它的标签页扩展点,以及可配置的宿主平面插件卡片。 |
|
||||
| [`ui-user-questions/`](ui-user-questions/README.md) | 展示 agent 请求的交互式问题。 |
|
||||
| [`ui-agent-preset/`](ui-agent-preset/README.md) | 选择会话的 agent 预设,并编写预设组合。 |
|
||||
| [`ui-settings/`](ui-settings/README.md) | 承载设置界面及其扩展区域。 |
|
||||
| [`ui-settings-general/`](ui-settings-general/README.md) | 提供常规设置分区。 |
|
||||
| [`ui-models/`](ui-models/README.md) | 提供模型提供方配置与 DeepSeek 配置引导。 |
|
||||
| [`ui-plugins/`](ui-plugins/README.md) | 向“插件”设置贡献只读的 Host Loader 清单标签页。 |
|
||||
| [`ui-settings-models/`](ui-settings-models/README.md) | 提供模型提供方配置与 DeepSeek 配置引导。 |
|
||||
| [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | 向“插件”设置贡献只读的 Host Loader 清单标签页。 |
|
||||
|
||||
每个子文档负责自身的约定和详细行为。[slot 系统标准](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md)与 [Web 客户端架构 Agent Note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md)负责跨包组合与加载决策。
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/connection/README.md
|
||||
README.md: d3727df981ecbc022345def48b38fbc879e29cb2
|
||||
README.zh.md: 5e632bf6d7135bda60178f0699691aff2d5623db
|
||||
README.md: 3315552dd0400697d5a96639598c5f5bb2bb4f5b
|
||||
README.zh.md: 0dc251f1e5410bd0d74ef450c6d8df3dc9cdab81
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared api client + current-page loopback state + observable generation-scoped `hostDescription` + single-consumer stream-loop starter); the export face carries the wire contract types, the `AbstractApiClient` abstraction, and the loop's sink/config types. Each successful readiness handshake publishes the exact `host.describe` value before `onConnected`; generation loss and explicit stop clear it, so native-capability consumers never retain a disconnected answer. The browser carrier uses HTTP POST for unary and respond operations and opens one downlink-only WebSocket each for `events.mux` and `events.host`; the in-process carrier satisfies the same two-stream abstraction. The Host half owns the single `/api` route and its Fetch bridge; a registered TypeRT interceptor claims its Remote endpoints before the API Proxy fallback. Loopback hostname classification stays package-internal: the `/api` Host fence and WebSocket upgrades use it directly, while other client plugins consume the derived `ctx.connection.isLoopback` state. The node half's `/api` route pins the privileged method set (`host.pickDirectory`, `host.openPath`, and the whole configuration plane — `settings.describe`/`openDocument`/`update`/`replace`/`mutate` and `credentials.describe`/`set`/`unset`; reads and native actions included, since describing returns the exposed configuration, opening acts on the Host desktop, and probing an arbitrary reference reports where a credential comes from — and the agent-preset authoring plane, `agentPreset.read`/`copy`/`openDocument`/`remove`, since a composition names the plugins a session runs, so reading one is reconnaissance, and copy/remove/openDocument manage the roster and drive the host desktop (authoring is copy-only, so none of them accepts composition text or a path); `agentPreset.list` and `agentPreset.select` stay out — the roster carries only ids and trust, and choosing a preset grants nothing `session.create`'s own `agentPreset` did not, over a default that already carries bash) to loopback by passing the trust fence with an empty trust list — a declared `trustedHosts` authority reaches every other method, while these stay loopback-local until a real authentication layer exists. The platform carriers and ConnectionController loop are package-internal; apply selects and drives them. The downlink boundary is documented in the [WebSocket downlink carrier Agent Note](../../../.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md).
|
||||
Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared api client + current-page loopback state + observable generation-scoped `hostDescription` + single-consumer stream-loop starter); the export face carries the wire contract types, the `AbstractApiClient` abstraction, and the loop's sink/config types. Each successful readiness handshake publishes the exact `host.describe` value before `onConnected`; generation loss and explicit stop clear it, so native-capability consumers never retain a disconnected answer. The browser carrier uses HTTP POST for unary and respond operations and opens one downlink-only WebSocket each for `events.mux` and `events.host`; the in-process carrier satisfies the same two-stream abstraction. The Host half owns the single `/api` route and its Fetch bridge; a registered Typert interceptor claims its Remote endpoints before the API Proxy fallback. Loopback hostname classification stays package-internal: the `/api` Host fence and WebSocket upgrades use it directly, while other client plugins consume the derived `ctx.connection.isLoopback` state. The node half's `/api` route pins the privileged method set (`host.pickDirectory`, `host.openPath`, and the whole configuration plane — `settings.describe`/`openDocument`/`update`/`replace`/`mutate` and `credentials.describe`/`set`/`unset`; reads and native actions included, since describing returns the exposed configuration, opening acts on the Host desktop, and probing an arbitrary reference reports where a credential comes from — and the agent-preset authoring plane, `agentPreset.read`/`copy`/`openDocument`/`remove`, since a composition names the plugins a session runs, so reading one is reconnaissance, and copy/remove/openDocument manage the roster and drive the host desktop (authoring is copy-only, so none of them accepts composition text or a path); `agentPreset.list` and `agentPreset.select` stay out — the roster carries only ids and trust, and choosing a preset grants nothing `session.create`'s own `agentPreset` did not, over a default that already carries bash) to loopback by passing the trust fence with an empty trust list — a declared `trustedHosts` authority reaches every other method, while these stay loopback-local until a real authentication layer exists. The platform carriers and ConnectionController loop are package-internal; apply selects and drives them. The downlink boundary is documented in the [WebSocket downlink carrier Agent Note](../../../.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md).
|
||||
|
||||
## /api browser-trust fence
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 当前页面的 loopback 状态 + 可观察且按 generation 生效的 `hostDescription` + 单消费方流循环启动器);导出表层携带协议约定类型、`AbstractApiClient` 抽象,以及循环的 sink/配置类型。每次就绪握手成功后,都会在 `onConnected` 之前发布完整的 `host.describe` 值;generation 失效或显式 stop 会清空它,因此原生能力消费者不会保留已经断线的判断。浏览器载体以 HTTP POST 发送 unary/respond,并为 `events.mux` 与 `events.host` 各开一条只下行的 WebSocket;进程内载体满足同一双流抽象。Host half 持有唯一 `/api` route 及其 Fetch bridge;已注册的 TypeRT interceptor 会先认领自己的 Remote endpoint,未认领请求再回退 API Proxy。Loopback hostname 判定逻辑留在包内部:`/api` Host fence 与 WebSocket upgrade 会直接使用它,其他客户端插件则消费派生的 `ctx.connection.isLoopback` 状态。node 半侧的 `/api` 路由让特权方法集(`host.pickDirectory`、`host.openPath`,以及整个配置面——`settings.describe`/`openDocument`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`;读取与原生操作也在内,因为 describe 会返回已暴露的配置、打开操作会作用于 Host 桌面,而探测任意引用会报出某条凭据来自何处——以及 agent(智能体) preset 的创作面 `agentPreset.read`/`copy`/`openDocument`/`remove`,因为组装指明了一个会话所运行的插件,读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面(创作只有复制一种写入,因此这些方法都不接收组装文本或路径);`agentPreset.list` 与 `agentPreset.select` 不在其中——名单只携带 id 与信任级别,而选择一个 preset 并不比 `session.create` 自带的 `agentPreset` 多给任何能力,何况默认 preset 本就带着 bash)以空信任表过信任 fence,从而钉在回环——已声明的 `trustedHosts` 授权可达其余全部方法,而这些方法在真正的认证层出现之前仍只限回环本机。平台载体与 ConnectionController 循环属于包内部;apply 负责选择并驱动它们。下行边界见 [WebSocket 下行载体 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md)。
|
||||
协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 当前页面的 loopback 状态 + 可观察且按 generation 生效的 `hostDescription` + 单消费方流循环启动器);导出表层携带协议约定类型、`AbstractApiClient` 抽象,以及循环的 sink/配置类型。每次就绪握手成功后,都会在 `onConnected` 之前发布完整的 `host.describe` 值;generation 失效或显式 stop 会清空它,因此原生能力消费者不会保留已经断线的判断。浏览器载体以 HTTP POST 发送 unary/respond,并为 `events.mux` 与 `events.host` 各开一条只下行的 WebSocket;进程内载体满足同一双流抽象。Host half 持有唯一 `/api` route 及其 Fetch bridge;已注册的 Typert interceptor 会先认领自己的 Remote endpoint,未认领请求再回退 API Proxy。Loopback hostname 判定逻辑留在包内部:`/api` Host fence 与 WebSocket upgrade 会直接使用它,其他客户端插件则消费派生的 `ctx.connection.isLoopback` 状态。node 半侧的 `/api` 路由让特权方法集(`host.pickDirectory`、`host.openPath`,以及整个配置面——`settings.describe`/`openDocument`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`;读取与原生操作也在内,因为 describe 会返回已暴露的配置、打开操作会作用于 Host 桌面,而探测任意引用会报出某条凭据来自何处——以及 agent(智能体) preset 的创作面 `agentPreset.read`/`copy`/`openDocument`/`remove`,因为组装指明了一个会话所运行的插件,读取它是侦察,而 copy/remove/openDocument 管理名单并驱动宿主桌面(创作只有复制一种写入,因此这些方法都不接收组装文本或路径);`agentPreset.list` 与 `agentPreset.select` 不在其中——名单只携带 id 与信任级别,而选择一个 preset 并不比 `session.create` 自带的 `agentPreset` 多给任何能力,何况默认 preset 本就带着 bash)以空信任表过信任 fence,从而钉在回环——已声明的 `trustedHosts` 授权可达其余全部方法,而这些方法在真正的认证层出现之前仍只限回环本机。平台载体与 ConnectionController 循环属于包内部;apply 负责选择并驱动它们。下行边界见 [WebSocket 下行载体 Agent Note](../../../.agents/notes/implemented/architecture/2026-08-04-websocket-downlink-carrier.md)。
|
||||
|
||||
## /api 浏览器信任栅栏
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-connection",
|
||||
"description": "Wire consumer layer: HTTP-up/WebSocket-down client, ConnectionController dual streams with reconnect, and fixture api",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -17,7 +17,7 @@ export type {
|
||||
SettingsApi, SettingsNamespaceView, SettingsPathOpView, SettingsSecretView,
|
||||
CredentialsApi, CredentialView, ConfigurableProviderView, DiscoveredModelView, LlmApi,
|
||||
SubagentsApi, SubagentAddress, SubagentCatalog, SubagentListEntry, SubagentPromptReceipt,
|
||||
TaskView,
|
||||
JobView,
|
||||
} from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
export type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools/presentation'
|
||||
export type {
|
||||
|
||||
@@ -108,7 +108,7 @@ function sgr(code: number, body: string): string {
|
||||
* TERMINAL_EXIT_STATUS and deliberately absent from this text: the real bash
|
||||
* presenter CONSUMES its `[exit code: N]` marker out of the body, because a
|
||||
* terminal card shows the exit as its own pill and leaving the marker in would
|
||||
* render it twice (packages/bash/tool-bash/src/render.ts).
|
||||
* render it twice (packages/shell/tool-bash/src/render.ts).
|
||||
*/
|
||||
const TERMINAL_OUTPUT_FIXTURE = [
|
||||
sgr(1, 'Running 4 checks'),
|
||||
@@ -771,7 +771,7 @@ function planViewOf(log: readonly SessionEvent[]): { active: boolean; pending: b
|
||||
}
|
||||
|
||||
/** Fixture parallel of the host's projection units: whole current values per key over the full log. */
|
||||
/** Fixture preset table (the host PermissionService defaults). */
|
||||
/** Fixture preset table (the host PermissionPresetService defaults). */
|
||||
const PERMISSION_PRESETS: Record<string, { sandbox: string; approval: string; description: string }> = {
|
||||
'workspace-write': { sandbox: 'workspace-write', approval: 'ask', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' },
|
||||
'danger-full-access': { sandbox: 'danger-full-access', approval: 'never', description: 'Full file access without approval prompts.' },
|
||||
|
||||
@@ -22,7 +22,7 @@ export type {
|
||||
ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning,
|
||||
MessageId, ModelReasoningEffort, ModelSelection, QueueAction, QueuedInboxItem, SessionModels,
|
||||
SubagentsApi, SubagentAddress, SubagentCatalog, SubagentListEntry, SubagentPromptReceipt,
|
||||
TaskView,
|
||||
JobView,
|
||||
RpcRequest, RpcResponse, RpcResult, RpcError, RpcErrorCode,
|
||||
ClientRequest, ServerResponse, ServerRequest, ClientResponse, RpcMessage, RpcReceipt,
|
||||
HostDescription, IApiClient, SessionId, SessionEvent, ContentBlock, StreamChunk,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import type {} from '@deepseek-ai/dsh-attachment'
|
||||
// Activates the httpServer Context merge used below.
|
||||
// Activates the webServer Context merge used below.
|
||||
import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
|
||||
import { API_PATH, HOST_EVENTS_PATH, MUX_EVENTS_PATH } from './api-path.ts'
|
||||
@@ -44,7 +44,7 @@ function assertImageBodyCapacity(ctx: Context, maxRequestBodyBytes: number): voi
|
||||
}
|
||||
|
||||
/** Services required before providing Connection; API Proxy is an optional `/api` fallback. */
|
||||
export const inject = ['httpServer']
|
||||
export const inject = ['webServer']
|
||||
|
||||
/** Plugin config: the deployment's non-loopback serving authorities. */
|
||||
export interface ConnectionConfig {
|
||||
@@ -170,7 +170,7 @@ export function apply(ctx: Context, config?: ConnectionConfig): void {
|
||||
await bridge(req, res, fetchHandler, maxRequestBodyBytes)
|
||||
},
|
||||
}
|
||||
ctx.effect(() => ctx.httpServer.register(route), 'client-connection: /api route')
|
||||
ctx.effect(() => ctx.webServer.register(route), 'client-connection: /api route')
|
||||
ctx.inject(['apiProxy'], (apiCtx) => {
|
||||
assertImageBodyCapacity(apiCtx, maxRequestBodyBytes)
|
||||
const downlinks = new WebSocketDownlinks(apiCtx.apiProxy)
|
||||
@@ -178,7 +178,7 @@ export function apply(ctx: Context, config?: ConnectionConfig): void {
|
||||
path: string,
|
||||
handle: WebUpgradeRoute['handler'],
|
||||
): void => {
|
||||
apiCtx.effect(() => apiCtx.httpServer.registerUpgrade({
|
||||
apiCtx.effect(() => apiCtx.webServer.registerUpgrade({
|
||||
path,
|
||||
handler: (req, socket, head) => {
|
||||
if (!isTrustedApiRequest(req, trustedHosts)) {
|
||||
|
||||
@@ -109,7 +109,7 @@ export class HostConnectionService extends Service implements HostConnectionHand
|
||||
},
|
||||
}
|
||||
return owner.effect(
|
||||
() => owner.httpServer.register(route),
|
||||
() => owner.webServer.register(route),
|
||||
`client-connection: ${channel} rpc channel`,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import type { AttachmentStore } from '@deepseek-ai/dsh-attachment'
|
||||
import { RpcId, type ClientRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import type { HttpServerService, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { WebServer, WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { API_PATH, apply, HOST_EVENTS_PATH, inject, MUX_EVENTS_PATH, type HostConnectionHandle } from '../src/index.ts'
|
||||
|
||||
/** Structural httpServer fake recording both route registries. */
|
||||
/** Structural webServer fake recording both route registries. */
|
||||
function fakeHttpServer(
|
||||
routes: WebRoute[],
|
||||
upgrades: WebUpgradeRoute[],
|
||||
): Pick<HttpServerService, 'register' | 'registerUpgrade' | 'tapIndex' | 'port'> {
|
||||
): Pick<WebServer, 'register' | 'registerUpgrade' | 'tapIndex' | 'port'> {
|
||||
return {
|
||||
register(route) {
|
||||
if (routes.some(candidate => candidate.kind === route.kind && candidate.path === route.path)) {
|
||||
@@ -82,7 +82,7 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{
|
||||
const ctx = new Context()
|
||||
const routes: WebRoute[] = []
|
||||
const upgrades: WebUpgradeRoute[] = []
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, upgrades) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer)
|
||||
ctx.provide('apiProxy', {} as unknown as ApiProxy)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply }, config)
|
||||
await fiber.await()
|
||||
@@ -93,7 +93,7 @@ describe('connection node half', () => {
|
||||
it('fails loud when the carrier cap cannot hold the configured image batch', () => {
|
||||
const ctx = new Context()
|
||||
const routes: WebRoute[] = []
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, []) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer)
|
||||
ctx.provide('attachments', {
|
||||
imageLimits: { maxMessageImageBytes: 20 * 1024 * 1024 },
|
||||
} as AttachmentStore)
|
||||
@@ -107,7 +107,7 @@ describe('connection node half', () => {
|
||||
const routes: WebRoute[] = []
|
||||
const upgrades: WebUpgradeRoute[] = []
|
||||
const ctx = new Context()
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, upgrades) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, upgrades) as WebServer)
|
||||
ctx.provide('apiProxy', {} as unknown as ApiProxy)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] })
|
||||
await expect(fiber).rejects.toThrow(/not a bare host\[:port\] authority/)
|
||||
@@ -216,7 +216,7 @@ describe('connection node half', () => {
|
||||
it('provides a disposable dedicated RPC channel without requiring apiProxy', async () => {
|
||||
const ctx = new Context()
|
||||
const routes: WebRoute[] = []
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, []) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
expect(routes).toHaveLength(1)
|
||||
@@ -262,7 +262,7 @@ describe('connection node half', () => {
|
||||
it('dispatches claimed /api endpoints before the API Proxy fallback and withdraws the claim', async () => {
|
||||
const ctx = new Context()
|
||||
const routes: WebRoute[] = []
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, []) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer)
|
||||
ctx.provide('apiProxy', {} as unknown as ApiProxy)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] })
|
||||
await fiber.await()
|
||||
@@ -340,7 +340,7 @@ describe('connection node half', () => {
|
||||
it('applies the configured trust fence and JSON envelope checks to generic channels', async () => {
|
||||
const ctx = new Context()
|
||||
const routes: WebRoute[] = []
|
||||
ctx.provide('httpServer', fakeHttpServer(routes, []) as HttpServerService)
|
||||
ctx.provide('webServer', fakeHttpServer(routes, []) as WebServer)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.example'] })
|
||||
await fiber.await()
|
||||
const connection = ctx.get('connection') as HostConnectionHandle
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"path": "../../llm/llm"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../util/brand"
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"path": "../../host/webserver"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-hmr",
|
||||
"description": "Dev-only hot-reload driver for script-loaded client entries: SSE rebuilt frames → invalidate/prefetch → fiber swap through the vendored Loader entry",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -12,7 +12,7 @@ import { statSync } from 'node:fs'
|
||||
import type { ServerResponse } from 'node:http'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
// Empty type imports carry the clientModuleHost/httpServer Context merges.
|
||||
// Empty type imports carry the clientModuleHost/webServer Context merges.
|
||||
import type {} from '@deepseek-ai/dsh-client-modules'
|
||||
import type {} from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { PluginsEventFrame } from './events.ts'
|
||||
@@ -25,7 +25,7 @@ export { EVENTS_ENDPOINT } from './events.ts'
|
||||
export const name = 'client-hmr'
|
||||
|
||||
/** Required services: the web plugin table and the route registry. */
|
||||
export const inject = ['clientModuleHost', 'httpServer']
|
||||
export const inject = ['clientModules', 'webServer']
|
||||
|
||||
/** Plugin config, validated by the same-named schemastery schema. */
|
||||
export interface Config {
|
||||
@@ -51,7 +51,7 @@ interface WatchedBundle {
|
||||
|
||||
/**
|
||||
* Mount the dev chain: bundle watches, rebuilt reporting, and the SSE channel.
|
||||
* @param ctx - host plugin context carrying clientModuleHost and httpServer.
|
||||
* @param ctx - host plugin context carrying clientModuleHost and webServer.
|
||||
* @param config - validated {@link Config}.
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
@@ -65,7 +65,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
try {
|
||||
// rebuilt() re-hashes; an unchanged hash stays silent (clientModuleHost
|
||||
// fires onRebuilt only on a real rev change).
|
||||
ctx.clientModuleHost.rebuilt(id)
|
||||
ctx.clientModules.rebuilt(id)
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
if (code === 'ENOENT') {
|
||||
@@ -117,8 +117,8 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// rows (or rows whose bundle path moved), add watches for new rows.
|
||||
const syncWatches = (): void => {
|
||||
const rows = new Map<string, string>()
|
||||
for (const row of ctx.clientModuleHost.graph().entries) {
|
||||
const path = ctx.clientModuleHost.clientPath(row.id)
|
||||
for (const row of ctx.clientModules.graph().entries) {
|
||||
const path = ctx.clientModules.clientPath(row.id)
|
||||
if (path !== undefined) rows.set(row.id, path)
|
||||
}
|
||||
for (const [id, watch] of watched) {
|
||||
@@ -135,7 +135,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// rows arriving later (boot-window activations, including this plugin's
|
||||
// own row — no self-exemption, a modules/hmr rebuild rides the same chain).
|
||||
syncWatches()
|
||||
const unsubscribe = ctx.clientModuleHost.onGraphChanged(syncWatches)
|
||||
const unsubscribe = ctx.clientModules.onGraphChanged(syncWatches)
|
||||
const timer = setInterval(pollWatches, pollIntervalMs)
|
||||
timer.unref()
|
||||
return () => {
|
||||
@@ -157,13 +157,13 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// 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')
|
||||
res.write(sseData({ type: 'graph', graph: ctx.clientModuleHost.graph() }))
|
||||
res.write(sseData({ type: 'graph', graph: ctx.clientModules.graph() }))
|
||||
connections.add(res)
|
||||
res.on('close', () => { connections.delete(res) })
|
||||
}
|
||||
|
||||
ctx.effect(() => {
|
||||
const disposeRoute = ctx.httpServer.register({
|
||||
const disposeRoute = ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: EVENTS_ENDPOINT,
|
||||
handler: (req, res) => {
|
||||
@@ -177,7 +177,7 @@ export function apply(ctx: Context, config: Config): void {
|
||||
connect(res)
|
||||
},
|
||||
})
|
||||
const unsubscribe = ctx.clientModuleHost.onRebuilt((id, rev) => {
|
||||
const unsubscribe = ctx.clientModules.onRebuilt((id, rev) => {
|
||||
const line = sseData({ type: 'rebuilt', id, rev })
|
||||
for (const res of connections) res.write(line)
|
||||
})
|
||||
|
||||
@@ -7,8 +7,8 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { WebBootGraph, ClientModuleHostService } from '@deepseek-ai/dsh-client-modules'
|
||||
import type { WebRoute, HttpServerService } from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { WebBootGraph, ClientModuleRegistry } 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'
|
||||
|
||||
const POLL_MS = 20
|
||||
@@ -23,7 +23,7 @@ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
|
||||
* Structural (Pick+cast): the plugin only touches the read/notify surface;
|
||||
* the service class carries private scan state a literal need not reproduce.
|
||||
*/
|
||||
type FakeHost = ClientModuleHostService & { rebuiltCalls: string[]; fireGraphChanged(): void }
|
||||
type FakeHost = ClientModuleRegistry & { rebuiltCalls: string[]; fireGraphChanged(): void }
|
||||
interface FakeHostOptions {
|
||||
beforeGraphRead?: () => void
|
||||
rebuilt?: (id: string) => string | undefined
|
||||
@@ -58,8 +58,8 @@ function fakeClientModuleHost(rows: Map<string, string>, options: FakeHostOption
|
||||
|
||||
// Structural fake: the plugin only touches register(); the service class
|
||||
// carries private state a literal cannot (and need not) reproduce.
|
||||
function fakeHttpServer(routes: WebRoute[]): HttpServerService {
|
||||
const fake: Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> = {
|
||||
function fakeHttpServer(routes: WebRoute[]): WebServer {
|
||||
const fake: Pick<WebServer, 'register' | 'tapIndex' | 'port'> = {
|
||||
register(route) {
|
||||
routes.push(route)
|
||||
return () => { routes.splice(routes.indexOf(route), 1) }
|
||||
@@ -67,13 +67,13 @@ function fakeHttpServer(routes: WebRoute[]): HttpServerService {
|
||||
tapIndex: () => () => {},
|
||||
port: 0,
|
||||
}
|
||||
return fake as HttpServerService
|
||||
return fake as WebServer
|
||||
}
|
||||
|
||||
async function mount(clientModuleHost: FakeHost, httpServer: HttpServerService) {
|
||||
async function mount(clientModuleHost: FakeHost, webServer: WebServer) {
|
||||
const ctx = new Context()
|
||||
ctx.provide('clientModuleHost', clientModuleHost)
|
||||
ctx.provide('httpServer', httpServer)
|
||||
ctx.provide('clientModules', clientModuleHost)
|
||||
ctx.provide('webServer', webServer)
|
||||
const fiber = ctx.plugin(
|
||||
{ inject: [...inject], Config, apply },
|
||||
{ pollIntervalMs: POLL_MS },
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"path": "../../../vendor/schemastery"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/locale/README.md
|
||||
README.md: 5bea46cd4e3ace61bd2251610abdf0812ded9604
|
||||
README.zh.md: 2333bc7c2b2f5918c35286064c50131153ee8711
|
||||
README.md: a63807f093dc12831a41196e61008151868e3205
|
||||
README.zh.md: b302e6055ba30d2db0948c0a6f1551c4a9dcb24c
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Locale plugin: LocaleService — the `zh`/`en` preference stored as `locale.preference` in `$DSH_HOME/settings.yaml`; when that explicit Host value is absent, a fresh browser starts provisionally in the language `navigator` asks for (primary-subtag matching, with `zh` when it asks for no language this app ships). The Host read runs after plugin activation so an unavailable settings service cannot block the page; its result replaces the provisional browser value live. Remote browsers retain only a process-local selection because the settings API is loopback-only. `locale/change` fires on switches. The service also owns the ns×locale dictionary registry (typed `register(ns, {zh, en})` checked against `LocaleNamespaceMap`, `bind(ns)`→`TranslateNS<ns>`; lookup chain ns → common → zh → key), implements the slot system's `LocaleFace`, and installs itself through `ctx.slots.installLocale`, backing the framework-injected `t` standard seat (`Translate`/`TranslateNS` are ui-slots types; import them from there — this package only re-exports for dictionary owners' convenience). The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary.
|
||||
Locale plugin: LocaleRuntime — the `zh`/`en` preference stored as `locale.preference` in `$DSH_HOME/settings.yaml`; when that explicit Host value is absent, a fresh browser starts provisionally in the language `navigator` asks for (primary-subtag matching, with `zh` when it asks for no language this app ships). The Host read runs after plugin activation so an unavailable settings service cannot block the page; its result replaces the provisional browser value live. Remote browsers retain only a process-local selection because the settings API is loopback-only. `locale/change` fires on switches. The service also owns the ns×locale dictionary registry (typed `register(ns, {zh, en})` checked against `LocaleNamespaceMap`, `bind(ns)`→`TranslateNS<ns>`; lookup chain ns → common → zh → key), implements the slot system's `LocaleFace`, and installs itself through `ctx.slots.installLocale`, backing the framework-injected `t` standard seat (`Translate`/`TranslateNS` are ui-slots types; import them from there — this package only re-exports for dictionary owners' convenience). The [Host-backed preferences decision](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md) owns the persistence boundary.
|
||||
|
||||
## Model Experience
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
locale 插件:LocaleService——`zh`/`en` 偏好以 `locale.preference` 存储在 `$DSH_HOME/settings.yaml` 中;若没有显式 Host 值,全新浏览器会暂时使用 `navigator` 请求的语言(按主子标签匹配;若其请求的语言本应用都不提供,则使用 `zh`)。Host 读取在插件激活后执行,因此 settings 服务不可用不会阻塞页面;读取结果会实时替换浏览器暂定值。settings API 仅限回环请求,因此远程浏览器的选择仅保留在进程内。`locale/change` 仅在切换语言时触发。该服务还拥有 ns×locale 字典注册表(类型化 `register(ns, {zh, en})` 按 `LocaleNamespaceMap` 校验,`bind(ns)`→`TranslateNS<ns>`;查找链 ns → common → zh → key),实现 slot 系统的 `LocaleFace`,并经 `ctx.slots.installLocale` 自行安装,支撑框架注入的 `t` 标准席位(`Translate`/`TranslateNS` 是 ui-slots 的类型;请从那里导入——本包的再导出仅为字典所有者提供便利)。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md)拥有。
|
||||
locale 插件:LocaleRuntime——`zh`/`en` 偏好以 `locale.preference` 存储在 `$DSH_HOME/settings.yaml` 中;若没有显式 Host 值,全新浏览器会暂时使用 `navigator` 请求的语言(按主子标签匹配;若其请求的语言本应用都不提供,则使用 `zh`)。Host 读取在插件激活后执行,因此 settings 服务不可用不会阻塞页面;读取结果会实时替换浏览器暂定值。settings API 仅限回环请求,因此远程浏览器的选择仅保留在进程内。`locale/change` 仅在切换语言时触发。该服务还拥有 ns×locale 字典注册表(类型化 `register(ns, {zh, en})` 按 `LocaleNamespaceMap` 校验,`bind(ns)`→`TranslateNS<ns>`;查找链 ns → common → zh → key),实现 slot 系统的 `LocaleFace`,并经 `ctx.slots.installLocale` 自行安装,支撑框架注入的 `t` 标准席位(`Translate`/`TranslateNS` 是 ui-slots 的类型;请从那里导入——本包的再导出仅为字典所有者提供便利)。该持久化边界由[Host settings 支撑的偏好决策](../../../.agents/notes/implemented/bug-fix/2026-08-06-host-backed-web-preferences.md)拥有。
|
||||
|
||||
## 模型体验
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-locale",
|
||||
"description": "Locale plugin: Host-backed zh/en preference, browser-derived fallback, locale snapshots, and typed namespace dictionaries",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -71,7 +71,7 @@ export interface LocaleSnapshot {
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
locale: LocaleService
|
||||
locale: LocaleRuntime
|
||||
}
|
||||
interface Events {
|
||||
/**
|
||||
@@ -111,7 +111,7 @@ const LOCALES: readonly LocaleDefinition[] = Object.freeze([
|
||||
* LocaleFace getSnapshot/subscribe pair the render machinery consumes
|
||||
* (installed via `ctx.slots.installLocale`).
|
||||
*/
|
||||
export class LocaleService {
|
||||
export class LocaleRuntime {
|
||||
private dicts = new Map<string, Map<string, LocaleDict>>()
|
||||
private bound = new Map<string, Translate>()
|
||||
private snapshot: LocaleSnapshot
|
||||
@@ -354,7 +354,7 @@ export const inject = ['slots', 'connection', 'remote', 'settingsScope']
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
const host = ctx.settingsScope.bind<LocaleSettings>({ namespace: LOCALE_SETTINGS_NAMESPACE })
|
||||
const locale = new LocaleService(ctx, host)
|
||||
const locale = new LocaleRuntime(ctx, host)
|
||||
locale.register(COMMON_NS, { zh, en })
|
||||
locale.register(SETTINGS_NS, { zh: settingsZh, en: settingsEn })
|
||||
ctx.provide('locale', locale)
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
* recovery after an HMR collapse of the declaring entry. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { SettingsScopeService } from '@deepseek-ai/dsh-client-ui-settings/client'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { SettingsScopeBinder } from '@deepseek-ai/dsh-client-ui-settings/client'
|
||||
import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import {
|
||||
apply, inject, SETTINGS_NS,
|
||||
} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type { LanguageRowInjected, LocaleService } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type { LanguageRowInjected, LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { LOCALE_SETTINGS_NAMESPACE, LocaleSettingsSchema } from '../src/locale-settings.ts'
|
||||
import { LanguageRow } from '../src/client/LanguageRow.tsx'
|
||||
import type { createLanguageRowStore } from '../src/client/settings-store.ts'
|
||||
@@ -18,7 +18,7 @@ const SLOT = 'settings.general.item'
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SlotsService).await()
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
let preference: string | undefined
|
||||
let revision = 0
|
||||
const namespace = () => ({
|
||||
@@ -47,15 +47,15 @@ async function bench() {
|
||||
ctx.provide('connection', { api: { settings: { describe, mutate } }, isLoopback: true } as never)
|
||||
// The settings transport and the forwarded-event port the plugin injects.
|
||||
new TestRemote(ctx)
|
||||
await ctx.plugin(SettingsScopeService).await()
|
||||
await ctx.plugin(SettingsScopeBinder).await()
|
||||
return {
|
||||
ctx, slots: ctx.get('slots') as SlotsService, describe, mutate,
|
||||
ctx, slots: ctx.get('slots') as SlotRegistry, describe, mutate,
|
||||
setHostPreference: (next: string | undefined) => { preference = next; revision += 1 },
|
||||
}
|
||||
}
|
||||
|
||||
/** Stand in for the settings shell: declare the General item slot from root. */
|
||||
function declareItems(slots: SlotsService): () => void {
|
||||
function declareItems(slots: SlotRegistry): () => void {
|
||||
return slots.register(
|
||||
{ name: 'root', children: { [SLOT]: { kind: 'list', scope: 'root' } } } as never,
|
||||
() => null,
|
||||
@@ -64,7 +64,7 @@ function declareItems(slots: SlotsService): () => void {
|
||||
|
||||
/** Mirror the framework's inject choreography: bake a real instance from the
|
||||
* declared handle and hand its actions to the entry's inject factory. */
|
||||
function faceOf(slots: SlotsService) {
|
||||
function faceOf(slots: SlotRegistry) {
|
||||
const entry = slots.entries(SLOT).find(e => e.component === LanguageRow)!
|
||||
const handle = entry.store as ReturnType<typeof createLanguageRowStore>
|
||||
const instance = handle.create()
|
||||
@@ -91,7 +91,7 @@ describe('locale apply', () => {
|
||||
const before = await bench()
|
||||
declareItems(before.slots)
|
||||
await before.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const locale = before.ctx.get('locale') as LocaleService
|
||||
const locale = before.ctx.get('locale') as LocaleRuntime
|
||||
// Base dictionaries are registered: the (ns, locale) seats are occupied.
|
||||
expect(() => locale.register('common', 'zh', {})).toThrow('already has locale')
|
||||
expect(() => locale.register('common', 'en', {})).toThrow('already has locale')
|
||||
@@ -112,7 +112,7 @@ describe('locale apply', () => {
|
||||
const b = await bench()
|
||||
declareItems(b.slots)
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const locale = b.ctx.get('locale') as LocaleService
|
||||
const locale = b.ctx.get('locale') as LocaleRuntime
|
||||
// An event ahead of any inject hits the unbound-actions arm.
|
||||
locale.setLocale('en')
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('locale apply', () => {
|
||||
b.setHostPreference('en')
|
||||
declareItems(b.slots)
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const locale = b.ctx.get('locale') as LocaleService
|
||||
const locale = b.ctx.get('locale') as LocaleRuntime
|
||||
await vi.waitFor(() => { expect(locale.getLocale().active).toBe('en') })
|
||||
b.setHostPreference(undefined)
|
||||
b.ctx.remote.$dispatch('settings/document-updated', [LOCALE_SETTINGS_NAMESPACE, 0])
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Settings, settingsNamespace, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
|
||||
import { SettingsProvider, settingsNamespace, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
|
||||
import {
|
||||
LOCALE_SETTINGS_NAMESPACE, apply,
|
||||
} from '@deepseek-ai/dsh-client-locale'
|
||||
|
||||
class MemorySettings extends Settings {
|
||||
class MemorySettings extends SettingsProvider {
|
||||
readonly writable = true
|
||||
protected load(): Promise<Record<string, unknown>> { return Promise.resolve({}) }
|
||||
protected persist(_ns: SettingsNamespace, _section: Record<string, unknown>): Promise<void> {
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { apply as nodeApply } from '@deepseek-ai/dsh-client-locale'
|
||||
import { apply as clientApply, COMMON_NS, LocaleService, inject } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { apply as clientApply, COMMON_NS, LocaleRuntime, inject } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import * as LocaleInvariant from '@deepseek-ai/dsh-client-locale/invariant'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
||||
import { stubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
|
||||
describe('invariant companion', () => {
|
||||
it('registers under the package name with an empty installer', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(InvariantRegistry, { enabled: true })
|
||||
await expect(ctx.plugin(LocaleInvariant).await()).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
@@ -23,16 +23,16 @@ describe('invariant companion', () => {
|
||||
// The feature registers its own Language settings row, hence the slots edge.
|
||||
expect(inject).toEqual(['slots', 'connection', 'remote', 'settingsScope'])
|
||||
const ctx = new Context()
|
||||
new SlotsService(ctx)
|
||||
new SlotRegistry(ctx)
|
||||
ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never)
|
||||
// The settings row's transport and the forwarded-event port.
|
||||
ctx.provide('remote', { $on: () => () => {} } as never)
|
||||
ctx.provide('settingsScope', { bind: () => stubSettingsScope().scope } as never)
|
||||
await ctx.plugin({ inject, apply: clientApply }).await()
|
||||
const locale = ctx.get('locale')
|
||||
expect(locale).toBeInstanceOf(LocaleService)
|
||||
expect(locale).toBeInstanceOf(LocaleRuntime)
|
||||
// Seeded dictionaries occupy the (ns, locale) seats even while empty.
|
||||
expect(() => (locale as LocaleService).register(COMMON_NS, 'zh', {})).toThrow('already has locale')
|
||||
expect(() => (locale as LocaleService).register(COMMON_NS, 'en', {})).toThrow('already has locale')
|
||||
expect(() => (locale as LocaleRuntime).register(COMMON_NS, 'zh', {})).toThrow('already has locale')
|
||||
expect(() => (locale as LocaleRuntime).register(COMMON_NS, 'en', {})).toThrow('already has locale')
|
||||
})
|
||||
})
|
||||
@@ -16,7 +16,7 @@ const OPTIONS = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }]
|
||||
/** Empty global standard-kit hooks (the row reads neither). */
|
||||
function emptySessions() {
|
||||
const store = createSnapshotStore<SessionListState>(
|
||||
{ ids: [], byId: {}, current: undefined, phase: 'ready', subagentsByParent: {}, tasksBySession: {}, currentAddress: undefined })
|
||||
{ ids: [], byId: {}, current: undefined, phase: 'ready', subagentsByParent: {}, jobsBySession: {}, currentAddress: undefined })
|
||||
return bindSnapshotSelector(store)
|
||||
}
|
||||
function emptyWorkspaces() {
|
||||
|
||||
@@ -3,17 +3,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { LocaleSettings, LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
|
||||
const make = (host?: StubSettingsScope<LocaleSettings>): {
|
||||
ctx: Context
|
||||
svc: LocaleService
|
||||
svc: LocaleRuntime
|
||||
events: LocaleSnapshot[]
|
||||
} => {
|
||||
const ctx = new Context()
|
||||
const events: LocaleSnapshot[] = []
|
||||
ctx.on('locale/change', (snapshot) => { events.push(snapshot) })
|
||||
return { ctx, svc: new LocaleService(ctx, host?.scope), events }
|
||||
return { ctx, svc: new LocaleRuntime(ctx, host?.scope), events }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,7 +27,7 @@ const stubLanguages = (...tags: string[]): void => {
|
||||
vi.stubGlobal('navigator', { languages: tags, language: tags[0] ?? '' })
|
||||
}
|
||||
|
||||
describe('LocaleService', () => {
|
||||
describe('LocaleRuntime', () => {
|
||||
beforeEach(() => {
|
||||
// A Chinese browser is the baseline these specs assert their zh state on.
|
||||
stubLanguages('zh-CN')
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"path": "../../settings/settings"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../ui-settings"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-modules",
|
||||
"description": "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",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* negative "not a client package" verdict) is cached per name and never
|
||||
* expires — plugin-set changes take effect on restart; bundle content
|
||||
* changes reach the graph only through
|
||||
* {@link ClientModuleHostService.rebuilt}.
|
||||
* {@link ClientModuleRegistry.rebuilt}.
|
||||
* @module @deepseek-ai/dsh-client-modules
|
||||
*/
|
||||
|
||||
@@ -39,7 +39,7 @@ export type {
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
/** The web plugin table (provided by the client-modules node half). */
|
||||
clientModuleHost: ClientModuleHostService
|
||||
clientModules: ClientModuleRegistry
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,8 +181,8 @@ export function injectBootManifest(html: string, graph: WebBootGraph): string {
|
||||
* already-loaded entries aggregates into one loud throw (FAILED fiber; the
|
||||
* boot activation audit reports it).
|
||||
*/
|
||||
export class ClientModuleHostService extends Service {
|
||||
static inject = ['httpServer', 'loader']
|
||||
export class ClientModuleRegistry extends Service {
|
||||
static inject = ['webServer', 'loader']
|
||||
|
||||
private readonly table = new Map<string, WebPluginRecord>()
|
||||
// Negative verdicts (unresolvable specifier — builtins like cordis:include,
|
||||
@@ -198,10 +198,10 @@ export class ClientModuleHostService extends Service {
|
||||
|
||||
/**
|
||||
* Build the service: subscribe, seed, and run the activation flush.
|
||||
* @param ctx - plugin context carrying httpServer and loader.
|
||||
* @param ctx - plugin context carrying webServer and loader.
|
||||
*/
|
||||
constructor(ctx: Context) {
|
||||
super(ctx, 'clientModuleHost')
|
||||
super(ctx, 'clientModules')
|
||||
// Resolution anchor: the config tree's baseUrl (the cordis.yml directory,
|
||||
// whose package declares every composed plugin as a dependency). The
|
||||
// modules package's own URL would miss sibling packages under pnpm's
|
||||
@@ -239,11 +239,11 @@ export class ClientModuleHostService extends Service {
|
||||
}
|
||||
|
||||
ctx.effect(
|
||||
() => ctx.httpServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }),
|
||||
() => ctx.webServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }),
|
||||
'client-modules: bundle route',
|
||||
)
|
||||
ctx.effect(
|
||||
() => ctx.httpServer.tapIndex(html => injectBootManifest(html, this.composed)),
|
||||
() => ctx.webServer.tapIndex(html => injectBootManifest(html, this.composed)),
|
||||
'client-modules: boot manifest injection',
|
||||
)
|
||||
}
|
||||
@@ -457,4 +457,4 @@ export class ClientModuleHostService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
export default ClientModuleHostService
|
||||
export default ClientModuleRegistry
|
||||
@@ -25,7 +25,7 @@ export const inject = ['invariants']
|
||||
*/
|
||||
const install: InvariantInstaller = (ctx, fail) => {
|
||||
ctx.on('internal/plugin', () => {
|
||||
const host = ctx.get('clientModuleHost')
|
||||
const host = ctx.get('clientModules')
|
||||
if (host === undefined) return // browser side / host without the node half: nothing to audit
|
||||
for (const row of host.graph().entries) {
|
||||
if (host.clientPath(row.id) === undefined) {
|
||||
|
||||
@@ -7,8 +7,8 @@ import { dirname, join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { HttpServerService, WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { ClientModuleHostService } from '../src/index.ts'
|
||||
import type { WebServer, WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { ClientModuleRegistry } from '../src/index.ts'
|
||||
|
||||
let root: string | undefined
|
||||
|
||||
@@ -38,7 +38,7 @@ function writePackage(
|
||||
}
|
||||
|
||||
/** Construct the node-half service and capture its plugin-bundle route. */
|
||||
function constructWithRoute(packageNames: string[]): { service: ClientModuleHostService; route: WebRoute } {
|
||||
function constructWithRoute(packageNames: string[]): { service: ClientModuleRegistry; route: WebRoute } {
|
||||
const ctx = new Context()
|
||||
ctx.baseUrl = pathToFileURL(root!).href + '/'
|
||||
ctx.provide('loader', {
|
||||
@@ -49,7 +49,7 @@ function constructWithRoute(packageNames: string[]): { service: ClientModuleHost
|
||||
},
|
||||
})
|
||||
let route: WebRoute | undefined
|
||||
const httpServer: Pick<HttpServerService, 'port' | 'register' | 'tapIndex'> = {
|
||||
const webServer: Pick<WebServer, 'port' | 'register' | 'tapIndex'> = {
|
||||
port: 0,
|
||||
register: (candidate) => {
|
||||
if (candidate.path === '/plugins') route = candidate
|
||||
@@ -57,14 +57,14 @@ function constructWithRoute(packageNames: string[]): { service: ClientModuleHost
|
||||
},
|
||||
tapIndex: () => () => {},
|
||||
}
|
||||
ctx.provide('httpServer', httpServer as HttpServerService)
|
||||
const service = new ClientModuleHostService(ctx)
|
||||
ctx.provide('webServer', webServer as WebServer)
|
||||
const service = new ClientModuleRegistry(ctx)
|
||||
if (route === undefined) throw new Error('client bundle route was not registered')
|
||||
return { service, route }
|
||||
}
|
||||
|
||||
/** Construct the node-half service over the enabled fixture entries. */
|
||||
function construct(packageNames: string[]): ClientModuleHostService {
|
||||
function construct(packageNames: string[]): ClientModuleRegistry {
|
||||
return constructWithRoute(packageNames).service
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,6 @@
|
||||
{ "path": "../../../vendor/cordis" },
|
||||
{ "path": "../../../vendor/loader" },
|
||||
{ "path": "../../host/webserver" },
|
||||
{ "path": "../../support/invariants" }
|
||||
{ "path": "../../runtime-diagnostics/invariants" }
|
||||
]
|
||||
}
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/runtime/README.md
|
||||
README.md: 441f5462d98c8a9e92ebc9f08cdd7568e89fd427
|
||||
README.zh.md: f4ec9ac53c10f8f375c837556db7623c95d11c17
|
||||
README.md: 1fb91bc8ca1bf9beae0ea12632acd9572db58670
|
||||
README.zh.md: 294a77d7081f5b475aca8b50f6c6d8322370375d
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list and scope state, and the shared event window and history paging used by registered conversation view targets. WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into Session and Workspace owners and hands each generic `host/remote-event` frame to `ctx.remote.$dispatch`; domain packages subscribe to their owner events through `ctx.remote.$on` and decide which caches or session rows they invalidate. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions.
|
||||
Client cordis boot and React-free object services: SlotRegistry wraps SlotCore and supplies renderer data sources; SessionRuntime owns Session objects, list and scope state, and the shared event window and history paging used by registered conversation view targets. WorkspaceRuntime depends on SessionRuntime and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into Session and Workspace owners and hands each generic `host/remote-event` frame to `ctx.remote.$dispatch`; domain packages subscribe to their owner events through `ctx.remote.$on` and decide which caches or session rows they invalidate. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions.
|
||||
|
||||
For each prompt that can reach a local root or continuable child Agent, the runtime samples the browser's current `Intl.DateTimeFormat().resolvedOptions().timeZone` and attaches it to that one Session or subagent prompt RPC. It is neither cached nor included in Session creation or fork state, so travel and concurrent tabs keep message-local provenance. A browser that cannot provide a non-empty zone fails the prompt locally instead of silently substituting deployment state.
|
||||
|
||||
@@ -16,25 +16,25 @@ The callback returns one synchronous disposer or an iterable of disposers. A gen
|
||||
|
||||
## Workspace and Session lists
|
||||
|
||||
Workspace and Session lists have independent monotone `pending` → `ready` baseline phases and separate refresh activity/error state. Incremental upsert/removal/order frames and unary mutation echoes arriving during a list request replay over its response. Every successful Workspace baseline re-establishes Host-durable Workspace order so reconnects adopt changes committed while this client was offline. `WorkspacesService.insertBefore` installs an optimistic order immediately; only the latest unary echo may replace it, a newer Host order frame outranks an older echo, and a latest rejected request restores the last Host-confirmed order rather than an earlier uncommitted drag. Removed Workspace ids retain process-local tombstones so late changed frames cannot resurrect them. Workspace recency is derived only after both baselines are ready and never changes Workspace list order.
|
||||
Workspace and Session lists have independent monotone `pending` → `ready` baseline phases and separate refresh activity/error state. Incremental upsert/removal/order frames and unary mutation echoes arriving during a list request replay over its response. Every successful Workspace baseline re-establishes Host-durable Workspace order so reconnects adopt changes committed while this client was offline. `WorkspaceRuntime.insertBefore` installs an optimistic order immediately; only the latest unary echo may replace it, a newer Host order frame outranks an older echo, and a latest rejected request restores the last Host-confirmed order rather than an earlier uncommitted drag. Removed Workspace ids retain process-local tombstones so late changed frames cannot resurrect them. Workspace recency is derived only after both baselines are ready and never changes Workspace list order.
|
||||
|
||||
`SessionSummary.pendingInteraction` classifies the live user action blocking a Session as `approval`, `plan-review`, or `question`. `SessionManager` tracks answerable requested/resolved mux frames by their stable request identities even before a Session object is instantiated; pre-instantiation buffering retains every live request, replaces replay duplicates, and removes resolved requests so the list status always has a matching answerable `PendingWait` when the Session is opened. The first pending question takes presentation priority over concurrent approvals to match composer routing, while only a request that satisfies the plan-review composer's binary rendering constraints keeps the distinct `plan-review` status. The state is connection-generation scoped: disconnect clears it, and mux-open replay restores only requests that remain pending.
|
||||
|
||||
`WorkspacesService.delete(workspaceId)` removes the registration from the client projection after the successful unary response; the matching `host/workspace-removed` frame is idempotent and synchronizes other tabs. Session state and the current Session selection are independent, so accounted Sessions immediately project under Ungrouped after their Workspace disappears.
|
||||
`WorkspaceRuntime.delete(workspaceId)` removes the registration from the client projection after the successful unary response; the matching `host/workspace-removed` frame is idempotent and synchronizes other tabs. Session state and the current Session selection are independent, so accounted Sessions immediately project under Ungrouped after their Workspace disappears.
|
||||
|
||||
`WorkspaceListState.archivedSessionIds` mirrors the Host's registry-global archive set (a `readonly SessionId[]` in Host order, replaced only when membership changes; consumers needing O(1) lookups build a transient Set). It is full-snapshot state: the `workspace.list` baseline, the `archiveSession` unary echo, and the `host/archived-sessions-changed` frame each install the complete set. `WorkspacesService.archiveSession(sessionId)` archives over the wire; the projection sweep clears the current selection into the New Session view state whenever it lands in the archive set — one rule covering the local echo, another tab's frame, and a reconnect baseline restoring a selection archived while this client was away. A set installed while a `workspace.list` request is in flight also supersedes that stale baseline's set. Grouping surfaces hide members everywhere while the session rows stay in the list store.
|
||||
`WorkspaceListState.archivedSessionIds` mirrors the Host's registry-global archive set (a `readonly SessionId[]` in Host order, replaced only when membership changes; consumers needing O(1) lookups build a transient Set). It is full-snapshot state: the `workspace.list` baseline, the `archiveSession` unary echo, and the `host/archived-sessions-changed` frame each install the complete set. `WorkspaceRuntime.archiveSession(sessionId)` archives over the wire; the projection sweep clears the current selection into the New Session view state whenever it lands in the archive set — one rule covering the local echo, another tab's frame, and a reconnect baseline restoring a selection archived while this client was away. A set installed while a `workspace.list` request is in flight also supersedes that stale baseline's set. Grouping surfaces hide members everywhere while the session rows stay in the list store.
|
||||
|
||||
SlotsService gives the renderer separate bare observables for `useSessions` and `useWorkspaces`; web-react creates the hooks. Workspace business state does not enter `SessionListState` or an entry store.
|
||||
SlotRegistry gives the renderer separate bare observables for `useSessions` and `useWorkspaces`; web-react creates the hooks. Workspace business state does not enter `SessionListState` or an entry store.
|
||||
|
||||
`indexSubagentDescendants()` derives per-parent total and running descendant counts from the retained list mirror. It follows only uninterrupted `origin: 'subagent'` ancestry, so an ordinary fork starts a separate ownership subtree; cycles stop without throwing, and a missing parent remains a harmless key until its summary arrives.
|
||||
|
||||
`SessionListState.tasksBySession` mirrors the Host's `session/tasks` frames last-wins, keyed by session and needing no Session instance. An emptied set is stored as an absent key, so absence and `[]` are one representation and consumers never test a sentinel. Two clears keep it from outliving its truth: `session/subscribed` drops the session's mirror, because a fresh generation sends a baseline only for a non-empty set and a retained list would survive as a phantom, and `host/session-removed` drops it again, because owner disposal removed the records on the mux stream while the removal frame rides the host stream, leaving the two with no relative order.
|
||||
`SessionListState.jobsBySession` mirrors the Host's `session/jobs` frames last-wins, keyed by session and needing no Session instance. An emptied set is stored as an absent key, so absence and `[]` are one representation and consumers never test a sentinel. Two clears keep it from outliving its truth: `session/subscribed` drops the session's mirror, because a fresh generation sends a baseline only for a non-empty set and a retained list would survive as a phantom, and `host/session-removed` drops it again, because owner disposal removed the records on the mux stream while the removal frame rides the host stream, leaving the two with no relative order.
|
||||
|
||||
`SessionsService.search(query, signal)` is a stateless one-shot action over the `session.search` RPC. It returns ranked session/snippet pairs without putting query, loading, or error state into the shared Session list, so each UI owner controls debounce, cancellation, stale-response suppression, and fallback presentation. `searchResultLimit` re-exposes `SESSION_SEARCH_RESULT_LIMIT` — the bound the response schema itself enforces — as injected presentation data, so client plugins do not duplicate it. It is a protocol constant rather than per-connection state, so the connection handle does not carry it.
|
||||
`SessionRuntime.search(query, signal)` is a stateless one-shot action over the `session.search` RPC. It returns ranked session/snippet pairs without putting query, loading, or error state into the shared Session list, so each UI owner controls debounce, cancellation, stale-response suppression, and fallback presentation. `searchResultLimit` re-exposes `SESSION_SEARCH_RESULT_LIMIT` — the bound the response schema itself enforces — as injected presentation data, so client plugins do not duplicate it. It is a protocol constant rather than per-connection state, so the connection handle does not carry it.
|
||||
|
||||
## New Session and the blank mirror
|
||||
|
||||
`WorkspacesService.connectWorkspace(workspaceId)` resolves the session a New Session flow lands in: it reuses the workspace's existing blank session from the list mirror (`blank && cwd == workspace.path && sessionIds.includes(id)` — the host's own membership rule, never cwd alone, so a cwd-matching unaccounted blank session is never hijacked) or calls `session.create({workspaceId})`, returning the session id for the caller to open. The shared `startSession` action targets an explicit Workspace first, then the current Session's Workspace, then the derived recent Workspace; with no Workspace it clears into the blank New Session page. `SessionSummary.blank` mirrors the host's derived empty-log bit and only ever lowers on the client: seeded by `session.list` / the `host/session-added` frame, flipped false by the first ACCEPTED local `prompt()` (on the RPC success response — acceptance proves the user message is in the host log; a rejected first prompt keeps the session blank and reusable) and by any `running: true` status frame, re-aligned by every list re-pull. List surfaces hide blank rows; the store carries every row. `SessionsService.create` accepts an optional caller-preallocated SessionId and throws `SessionCreateError` (carrying `requestedSessionId`) on failure.
|
||||
`WorkspaceRuntime.connectWorkspace(workspaceId)` resolves the session a New Session flow lands in: it reuses the workspace's existing blank session from the list mirror (`blank && cwd == workspace.path && sessionIds.includes(id)` — the host's own membership rule, never cwd alone, so a cwd-matching unaccounted blank session is never hijacked) or calls `session.create({workspaceId})`, returning the session id for the caller to open. The shared `startSession` action targets an explicit Workspace first, then the current Session's Workspace, then the derived recent Workspace; with no Workspace it clears into the blank New Session page. `SessionSummary.blank` mirrors the host's derived empty-log bit and only ever lowers on the client: seeded by `session.list` / the `host/session-added` frame, flipped false by the first ACCEPTED local `prompt()` (on the RPC success response — acceptance proves the user message is in the host log; a rejected first prompt keeps the session blank and reusable) and by any `running: true` status frame, re-aligned by every list re-pull. List surfaces hide blank rows; the store carries every row. `SessionRuntime.create` accepts an optional caller-preallocated SessionId and throws `SessionCreateError` (carrying `requestedSessionId`) on failure.
|
||||
|
||||
`Session.composerPhase` treats any visible non-command Chat Node as conversation content, so a client plugin can project durable human input without opening a turn while a window containing only generic command rows retains the Host blank posture. List hiding and blank-session reuse still follow the Host blank bit. A history window that lacks the plugin-owned input Node returns to that blank posture until an older page restores it.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象、列表与 scope 状态,以及供已注册 conversation view target 共用的事件窗口与历史分页。WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session 与 Workspace 所有者,并把每个通用 `host/remote-event` 帧交给 `ctx.remote.$dispatch`;各领域包通过 `ctx.remote.$on` 订阅自身 owner 事件,并自行决定使哪些缓存或会话行失效。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent(智能体)和 cwd);客户端不持有任何实体化之前的会话状态——agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。约定:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。
|
||||
客户端 cordis 启动与不依赖 React 的对象服务:SlotRegistry 包装 SlotCore 并提供 renderer 数据源;SessionRuntime 拥有 Session 对象、列表与 scope 状态,以及供已注册 conversation view target 共用的事件窗口与历史分页。WorkspaceRuntime 依赖 SessionRuntime,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session 与 Workspace 所有者,并把每个通用 `host/remote-event` 帧交给 `ctx.remote.$dispatch`;各领域包通过 `ctx.remote.$on` 订阅自身 owner 事件,并自行决定使哪些缓存或会话行失效。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent(智能体)和 cwd);客户端不持有任何实体化之前的会话状态——agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。约定:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。
|
||||
|
||||
对于每条可到达本地根 Agent 或可继续子 Agent 的提示词,运行时都会采样浏览器当前的 `Intl.DateTimeFormat().resolvedOptions().timeZone`,并只把该值附加到这一次 Session 或 subagent 提示词 RPC。该值既不缓存,也不包含在 Session 创建或 fork 状态中,因此旅行与并发标签页都能保留消息本地的来源信息。浏览器若无法提供非空时区,会在本地拒绝该提示词,而不会悄然使用部署状态代替。
|
||||
|
||||
@@ -16,25 +16,25 @@
|
||||
|
||||
## Workspace 与 Session 列表
|
||||
|
||||
Workspace 和 Session 列表各自具有单调的 `pending` → `ready` 基线阶段,也有各自的刷新活动/错误状态。列表请求期间到达的增量插入或更新/移除/顺序帧与一元变更回显会在其响应之上回放。每次成功的 Workspace 基线都会重新建立 Host 持久 Workspace 顺序,因此重连会接纳该客户端离线期间提交的变更。`WorkspacesService.insertBefore` 会立即安装乐观顺序;只有最新一元回声可以替换它,更新的 Host 顺序帧优先于旧回声,而最新请求被拒时会恢复最近一次由 Host 确认的顺序,不会恢复更早且尚未提交的拖拽。已移除的 Workspace id 会保留进程本地删除标记,避免延迟到达的 changed 帧将其复活。Workspace 新近程度只在两条基线都 ready 后派生,且绝不改变 Workspace 列表顺序。
|
||||
Workspace 和 Session 列表各自具有单调的 `pending` → `ready` 基线阶段,也有各自的刷新活动/错误状态。列表请求期间到达的增量插入或更新/移除/顺序帧与一元变更回显会在其响应之上回放。每次成功的 Workspace 基线都会重新建立 Host 持久 Workspace 顺序,因此重连会接纳该客户端离线期间提交的变更。`WorkspaceRuntime.insertBefore` 会立即安装乐观顺序;只有最新一元回声可以替换它,更新的 Host 顺序帧优先于旧回声,而最新请求被拒时会恢复最近一次由 Host 确认的顺序,不会恢复更早且尚未提交的拖拽。已移除的 Workspace id 会保留进程本地删除标记,避免延迟到达的 changed 帧将其复活。Workspace 新近程度只在两条基线都 ready 后派生,且绝不改变 Workspace 列表顺序。
|
||||
|
||||
`SessionSummary.pendingInteraction` 将阻塞 Session 的实时用户操作分类为 `approval`、`plan-review` 或 `question`。`SessionManager` 依据稳定的请求标识跟踪可应答请求的 requested/resolved mux 帧,即使 `Session` 对象尚未实例化也不例外;实例化前的缓冲会保留每个仍有效的请求,替换回放产生的重复项,并移除已解决的请求,因此打开 Session 时,列表状态始终有一个对应的可应答 `PendingWait`。审批与问题并发时,第一个 pending 问题具有更高的呈现优先级,以匹配 composer 路由;只有满足 plan-review composer 二元呈现约束的请求才会保留独立的 `plan-review` 状态。该状态的作用域限定在连接代次内:断连时清除,mux 打开时的回放只恢复仍处于 pending 的请求。
|
||||
|
||||
`WorkspacesService.delete(workspaceId)` 在一元响应成功后从客户端投影中移除注册记录;对应的 `host/workspace-removed` 帧具有幂等性,并负责同步其他标签页。Session 状态与当前 Session selection 相互独立,因此 Workspace 消失后,其已纳入客户端投影的 Session 会立即投影到 Ungrouped 下。
|
||||
`WorkspaceRuntime.delete(workspaceId)` 在一元响应成功后从客户端投影中移除注册记录;对应的 `host/workspace-removed` 帧具有幂等性,并负责同步其他标签页。Session 状态与当前 Session selection 相互独立,因此 Workspace 消失后,其已纳入客户端投影的 Session 会立即投影到 Ungrouped 下。
|
||||
|
||||
`WorkspaceListState.archivedSessionIds` 镜像 Host 的注册表级全局归档集合(一个按 Host 顺序的 `readonly SessionId[]`,仅在成员变化时才替换;需要 O(1) 查询的消费方自建临时 Set)。它是全快照状态:`workspace.list` 基线、`archiveSession` 一元回声和 `host/archived-sessions-changed` 帧各自安装完整集合。`WorkspacesService.archiveSession(sessionId)` 通过 wire 归档;投影层在当前 selection 落入归档集合时统一清空为 New Session 视图状态——一条规则同时覆盖本地回声、其他标签页的帧、以及重连基线恢复出一个离线期间被归档的 selection。在 `workspace.list` 请求进行中安装的集合还会取代该过期基线携带的集合。各分组视图在所有位置隐藏集合成员,而会话行本身仍留在列表 store 中。
|
||||
`WorkspaceListState.archivedSessionIds` 镜像 Host 的注册表级全局归档集合(一个按 Host 顺序的 `readonly SessionId[]`,仅在成员变化时才替换;需要 O(1) 查询的消费方自建临时 Set)。它是全快照状态:`workspace.list` 基线、`archiveSession` 一元回声和 `host/archived-sessions-changed` 帧各自安装完整集合。`WorkspaceRuntime.archiveSession(sessionId)` 通过 wire 归档;投影层在当前 selection 落入归档集合时统一清空为 New Session 视图状态——一条规则同时覆盖本地回声、其他标签页的帧、以及重连基线恢复出一个离线期间被归档的 selection。在 `workspace.list` 请求进行中安装的集合还会取代该过期基线携带的集合。各分组视图在所有位置隐藏集合成员,而会话行本身仍留在列表 store 中。
|
||||
|
||||
SlotsService 分别为 renderer 提供 `useSessions` 与 `useWorkspaces` 的裸 observable;web-react 创建钩子。Workspace 业务状态不会进入 `SessionListState` 或条目 store。
|
||||
SlotRegistry 分别为 renderer 提供 `useSessions` 与 `useWorkspaces` 的裸 observable;web-react 创建钩子。Workspace 业务状态不会进入 `SessionListState` 或条目 store。
|
||||
|
||||
`indexSubagentDescendants()` 从保留的列表镜像中派生每个 parent 的后代总数与运行中后代数。它只沿不间断的 `origin: 'subagent'` 祖先链追踪,因此普通 fork 会开启独立的归属子树;遇到环时,追踪会停止但不会抛出异常,缺失的 parent 则会保留为无害的键,直至其摘要到达。
|
||||
|
||||
`SessionListState.tasksBySession` 按 last-wins 镜像宿主的 `session/tasks` 帧,以会话为键,不需要 Session 实例。被清空的集合存为缺失的键,因此「缺失」与 `[]` 是同一种表示,消费方永远不必检测哨兵值。两处清理让它不至于比它所反映的真相活得更久:`session/subscribed` 丢弃该会话的镜像,因为新一代只为非空集合发送 baseline,被留下的列表会变成幽灵;`host/session-removed` 再丢一次,因为 owner 销毁是在 mux 流上移除记录的,而移除帧走 host 流,两者没有相对顺序。
|
||||
`SessionListState.jobsBySession` 按 last-wins 镜像宿主的 `session/jobs` 帧,以会话为键,不需要 Session 实例。被清空的集合存为缺失的键,因此「缺失」与 `[]` 是同一种表示,消费方永远不必检测哨兵值。两处清理让它不至于比它所反映的真相活得更久:`session/subscribed` 丢弃该会话的镜像,因为新一代只为非空集合发送 baseline,被留下的列表会变成幽灵;`host/session-removed` 再丢一次,因为 owner 销毁是在 mux 流上移除记录的,而移除帧走 host 流,两者没有相对顺序。
|
||||
|
||||
`SessionsService.search(query, signal)` 是基于 `session.search` RPC 的无状态单次操作。它返回经过排序的会话/snippet 对,但不会将查询条件、加载状态或错误状态写入共享 Session 列表,因此每个 UI 所有者都自行负责防抖、取消、抑制陈旧响应和回退呈现。`searchResultLimit` 将 `SESSION_SEARCH_RESULT_LIMIT`——即响应 schema 自身强制执行的上限——作为注入的呈现数据重新公开,使客户端插件无需复制该值。它是协议常量而非逐连接状态,因此连接 handle 不携带它。
|
||||
`SessionRuntime.search(query, signal)` 是基于 `session.search` RPC 的无状态单次操作。它返回经过排序的会话/snippet 对,但不会将查询条件、加载状态或错误状态写入共享 Session 列表,因此每个 UI 所有者都自行负责防抖、取消、抑制陈旧响应和回退呈现。`searchResultLimit` 将 `SESSION_SEARCH_RESULT_LIMIT`——即响应 schema 自身强制执行的上限——作为注入的呈现数据重新公开,使客户端插件无需复制该值。它是协议常量而非逐连接状态,因此连接 handle 不携带它。
|
||||
|
||||
## New Session 与 blank 镜像
|
||||
|
||||
`WorkspacesService.connectWorkspace(workspaceId)` 解析 New Session 流程最终落入的会话:先在列表镜像中复用该 workspace 的既有空会话(`blank && cwd == workspace.path && sessionIds.includes(id)`——host 自己的成员规则,绝不只按 cwd,避免劫持 cwd 匹配但未入账的空白会话),未命中则调用 `session.create({workspaceId})`,返回会话 id 由调用方 open。共享的 `startSession` 操作优先使用明确指定的 Workspace,其次使用当前 Session 所属 Workspace,再其次使用派生的最近活跃 Workspace;一个 Workspace 都没有时则清空选择,进入空白 New Session 页面。`SessionSummary.blank` 镜像主机派生的空日志位,在客户端只降不升:由 `session.list`/`host/session-added` 帧播种,本地首次获 Host 接受的 `prompt()`(RPC 成功响应时——受理即证明用户消息已入主机日志;首讯被拒则会话保持 blank、保持可复用)与任何 `running: true` 状态帧翻为 false,每次列表重拉重新对齐。列表界面隐藏 blank 行;store 保留全部行。`SessionsService.create` 接受可选的、由调用方预先分配的 SessionId,失败时抛出 `SessionCreateError`(携带 `requestedSessionId`)。
|
||||
`WorkspaceRuntime.connectWorkspace(workspaceId)` 解析 New Session 流程最终落入的会话:先在列表镜像中复用该 workspace 的既有空会话(`blank && cwd == workspace.path && sessionIds.includes(id)`——host 自己的成员规则,绝不只按 cwd,避免劫持 cwd 匹配但未入账的空白会话),未命中则调用 `session.create({workspaceId})`,返回会话 id 由调用方 open。共享的 `startSession` 操作优先使用明确指定的 Workspace,其次使用当前 Session 所属 Workspace,再其次使用派生的最近活跃 Workspace;一个 Workspace 都没有时则清空选择,进入空白 New Session 页面。`SessionSummary.blank` 镜像主机派生的空日志位,在客户端只降不升:由 `session.list`/`host/session-added` 帧播种,本地首次获 Host 接受的 `prompt()`(RPC 成功响应时——受理即证明用户消息已入主机日志;首讯被拒则会话保持 blank、保持可复用)与任何 `running: true` 状态帧翻为 false,每次列表重拉重新对齐。列表界面隐藏 blank 行;store 保留全部行。`SessionRuntime.create` 接受可选的、由调用方预先分配的 SessionId,失败时抛出 `SessionCreateError`(携带 `requestedSessionId`)。
|
||||
|
||||
`Session.composerPhase` 把任何可见的非命令 Chat Node 视为对话内容,因此客户端插件可以在不打开轮次的情况下投影持久用户输入,而仅包含通用命令行的窗口仍保持 Host blank 状态。列表隐藏和空白会话复用仍遵循 Host blank 位。缺少插件输入 Node 的历史窗口会恢复该空白状态,直到加载更早页面后该 Node 恢复。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-runtime",
|
||||
"description": "Client core services: SlotsService, SessionsService (scope tree + object layer)",
|
||||
"version": "0.0.1-rc.2",
|
||||
"description": "Client core services: SlotRegistry, SessionRuntime (scope tree + object layer)",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
@@ -62,7 +62,7 @@
|
||||
"@deepseek-ai/cordis": "workspace:^",
|
||||
"@deepseek-ai/dsh-api-remotes": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-type-meta": "workspace:^",
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
|
||||
"@deepseek-ai/dsh-typert-registry": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -70,7 +70,7 @@
|
||||
"@deepseek-ai/dsh-api-remotes": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/dsh-timeout": "workspace:^",
|
||||
"@deepseek-ai/dsh-type-meta": "workspace:^",
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
|
||||
"@deepseek-ai/dsh-typert-registry": "workspace:^",
|
||||
"@types/react": "~18.3.1"
|
||||
},
|
||||
|
||||
@@ -18,11 +18,11 @@
|
||||
import { Context as CordisContext } from '@deepseek-ai/cordis'
|
||||
import type { Context, Fiber } from '@deepseek-ai/cordis'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { TypeRTClientRemote, TypeRTRemoteScopeApi } from '@deepseek-ai/dsh-type-meta'
|
||||
import type { TypertClientRemote, TypertRemoteScopeApi } from '@deepseek-ai/dsh-typert-protocol'
|
||||
|
||||
/** Client Cordis Context carrying one Agent identity and its scoped Remote namespaces. */
|
||||
export type AgentContext = Omit<Context, 'remote'> & {
|
||||
readonly remote: TypeRTClientRemote & TypeRTRemoteScopeApi<'agent'>
|
||||
readonly remote: TypertClientRemote & TypertRemoteScopeApi<'agent'>
|
||||
}
|
||||
|
||||
/** Context tag written by {@link createScope}. */
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { AttachmentIdType, ImageAttachmentRef } from '@deepseek-ai/dsh-atta
|
||||
import type {
|
||||
MessageId, PromptContentPart, QueueAction, RpcResult, SessionId,
|
||||
} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-type-meta'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { ConversationSnapshot } from '../sessions/conversation.ts'
|
||||
import type { ObservableSnapshot } from './store.ts'
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Cross-domain sessions face: the contract surface sibling domains (today:
|
||||
* workspaces) consume instead of the sessions implementation. The sessions
|
||||
* domain satisfies it structurally — SessionsService is assignable, checked
|
||||
* domain satisfies it structurally — SessionRuntime is assignable, checked
|
||||
* wherever the assembly layer or a test injects the real service — so
|
||||
* widening this face is the explicit act of widening the inter-domain
|
||||
* dependency.
|
||||
|
||||
@@ -5,12 +5,12 @@ import type { ConnectionHandle, SessionId } from '@deepseek-ai/dsh-api-remotes/c
|
||||
// than api-remotes': that face imports a Host-tsdown-generated artifact, and this
|
||||
// project sits in the Host build graph.
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type { TypeRTContext } from '@deepseek-ai/dsh-type-meta'
|
||||
import type { TypertContext } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { MaybeSnapshotSelectorHook, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { SlotsService } from './slots.ts'
|
||||
import { SessionsService } from './sessions/service.ts'
|
||||
import { SlotRegistry } from './slots.ts'
|
||||
import { SessionRuntime } from './sessions/service.ts'
|
||||
import type { SessionListState } from './sessions/service.ts'
|
||||
import { WorkspacesService } from './workspaces/service.ts'
|
||||
import { WorkspaceRuntime } from './workspaces/service.ts'
|
||||
import type { ConversationSnapshot } from './sessions/conversation.ts'
|
||||
import type { UseProjection } from './sessions/projection-store.ts'
|
||||
import { ConversationEventRegistry } from './conversation/event-registry.ts'
|
||||
@@ -18,7 +18,7 @@ import { ConversationViewRegistry } from './conversation/view-registry.ts'
|
||||
|
||||
export { isAppendSurfaceEvent, isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface'
|
||||
|
||||
export { SlotsService } from './slots.ts'
|
||||
export { SlotRegistry } from './slots.ts'
|
||||
export { ConversationEventRegistry } from './conversation/event-registry.ts'
|
||||
export { ConversationViewRegistry } from './conversation/view-registry.ts'
|
||||
export { ConversationNodeAssembler } from './sessions/conversation-assembler.ts'
|
||||
@@ -36,7 +36,7 @@ export type {
|
||||
} from './contract/conversation.ts'
|
||||
export type { ConversationRuntime } from './sessions/conversation-assembler.ts'
|
||||
export type { RootOwnerProps } from './slots.ts'
|
||||
export { SessionCreateError, SessionsService, scopeOf, workspaceTitleOf } from './sessions/service.ts'
|
||||
export { SessionCreateError, SessionRuntime, scopeOf, workspaceTitleOf } from './sessions/service.ts'
|
||||
export { indexSubagentDescendants } from './sessions/subagent-lineage.ts'
|
||||
export type { SubagentDescendantSummary } from './sessions/subagent-lineage.ts'
|
||||
// The provide channel is shared with the client test runtime (one
|
||||
@@ -45,7 +45,7 @@ export { SessionProvideChannel } from './sessions/provide.ts'
|
||||
export type { SessionProvideChannelHost } from './sessions/provide.ts'
|
||||
export { createScope } from './agents/scope.ts'
|
||||
export type { AgentScopeHandle } from './agents/scope.ts'
|
||||
export { DirectoryBrowseError, WorkspaceCreateError, WorkspacesService } from './workspaces/service.ts'
|
||||
export { DirectoryBrowseError, WorkspaceCreateError, WorkspaceRuntime } from './workspaces/service.ts'
|
||||
export { resolveWorkspacePath } from './workspaces/path.ts'
|
||||
// Contract only: the scope implementation and its Host transport belong to
|
||||
// dsh-client-ui-settings (see that package's settings-scope.ts).
|
||||
@@ -60,7 +60,7 @@ export type {
|
||||
SessionBinding, SessionListState, SessionProvideContribution, SessionProvideDescriptor, SessionSummary,
|
||||
} from './sessions/service.ts'
|
||||
export type { SessionListPhase, SessionSearchResultItem, SubagentCatalogSnapshot } from './sessions/manager.ts'
|
||||
export type { SubagentAddress, TaskView } from '@deepseek-ai/dsh-client-connection/client'
|
||||
export type { SubagentAddress, JobView } from '@deepseek-ai/dsh-client-connection/client'
|
||||
export type { WorkspaceListPhase } from './workspaces/manager.ts'
|
||||
export type { WorkspaceListState } from './workspaces/service.ts'
|
||||
export type {
|
||||
@@ -111,10 +111,10 @@ export type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
|
||||
/** Client-side Cordis context after declaration merging. */
|
||||
export type ClientContext = Context
|
||||
|
||||
declare module '@deepseek-ai/dsh-type-meta' {
|
||||
interface TypeRTContextMap {
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface TypertContextMap {
|
||||
/** Client Agent scope identity; the agent and session share one wire id. */
|
||||
agent: TypeRTContext<SessionId>
|
||||
agent: TypertContext<SessionId>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ declare module '@deepseek-ai/cordis' {
|
||||
'connection/reset'(): void
|
||||
}
|
||||
interface Context {
|
||||
slots: import('./slots.ts').SlotsService
|
||||
slots: import('./slots.ts').SlotRegistry
|
||||
/** Event-to-business-Context Definition registry. */
|
||||
conversationEvents: import('./conversation/event-registry.ts').ConversationEventRegistry
|
||||
/** Per-target Conversation snapshot builder registry. */
|
||||
@@ -179,24 +179,24 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
/** Required services: the wire handle and Client TypeRT registry. */
|
||||
/** Required services: the wire handle and Client Typert registry. */
|
||||
export const inject = ['connection', 'typert', 'remote', 'remote.commands']
|
||||
|
||||
/** Mounts the browser runtime services and connection stream.
|
||||
* @param ctx - Client Cordis context.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.plugin(SlotsService)
|
||||
ctx.plugin(SlotRegistry)
|
||||
const conversation = {
|
||||
events: new ConversationEventRegistry(ctx),
|
||||
views: new ConversationViewRegistry(ctx),
|
||||
}
|
||||
const connection = ctx.get('connection') as ConnectionHandle
|
||||
const sessions = new SessionsService(ctx, connection.api, ctx.remote, conversation)
|
||||
const sessions = new SessionRuntime(ctx, connection.api, ctx.remote, conversation)
|
||||
ctx.typert.contexts.registerClient('agent', {
|
||||
identity: candidate => sessions.scopeOf(candidate),
|
||||
})
|
||||
const workspaces = new WorkspacesService(ctx, connection.api, sessions)
|
||||
const workspaces = new WorkspaceRuntime(ctx, connection.api, sessions)
|
||||
ctx.effect(
|
||||
() => workspaces.startInitialSelection(),
|
||||
'runtime: initial Workspace selection',
|
||||
|
||||
@@ -79,7 +79,7 @@ export function contextProvenance(source: unknown): ContextProvenanceView {
|
||||
return { role: 'recall', label: joined(collect(record, 'references', 'label')) ?? kind }
|
||||
// Workspace instructions name the files they were reconciled from, which
|
||||
// identifies the producer far better than the plugin id would.
|
||||
case 'workspace-instructions':
|
||||
case 'agent-instructions':
|
||||
return { role: 'inject', label: joined(collect(record, 'changes', 'path')) ?? kind }
|
||||
case 'plugin':
|
||||
return { role: 'inject', label: readString(record, 'plugin') ?? kind }
|
||||
|
||||
@@ -216,10 +216,10 @@ export interface CompactionSummaryNode {
|
||||
seq: number
|
||||
/** Unix epoch ms of the checkpoint event. */
|
||||
time: number
|
||||
/** Summary text from the checkpoint's cited `compact/summary` event; null when
|
||||
/** Summary text from the checkpoint's cited `compaction/summary` event; null when
|
||||
* the window cut left that event outside (the marker is then not expandable). */
|
||||
summary: string | null
|
||||
/** Seq of the loaded `compact/summary` event, or null when that event is outside the window. */
|
||||
/** Seq of the loaded `compaction/summary` event, or null when that event is outside the window. */
|
||||
summaryEventSeq: number | null
|
||||
/** Number of surface items replaced, or null when the summary event is unavailable or malformed. */
|
||||
shadowedItemCount: number | null
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// SessionManager: the instance cluster Map<SessionId, Session> (lazy-built, resident) + the frame
|
||||
// dispatch entry + list state, constructed and held by SessionsService (one per client runtime).
|
||||
// dispatch entry + list state, constructed and held by SessionRuntime (one per client runtime).
|
||||
// List data never enters zustand; React connects via subscribe/getListSnapshot.
|
||||
|
||||
import type {
|
||||
IApiClient, HostFrame, MuxFrame, RpcError, RpcRequest, RpcResult, SessionId,
|
||||
SessionSummary, SubagentAddress, SubagentCatalog, TaskView, WorkspaceId,
|
||||
SessionSummary, SubagentAddress, SubagentCatalog, JobView, WorkspaceId,
|
||||
} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
// Value import from the inline-safe wire layer (not the connection plugin):
|
||||
// plugin-to-plugin value imports are a bundle purity error.
|
||||
@@ -49,8 +49,8 @@ export interface SessionListSnapshot {
|
||||
phase: SessionListPhase
|
||||
error: RpcError | null
|
||||
subagentsByParent: Readonly<Record<SessionId, SubagentCatalogSnapshot>>
|
||||
/** Background tasks per session; an absent key is an empty set. */
|
||||
tasksBySession: Readonly<Record<SessionId, readonly TaskView[]>>
|
||||
/** Background jobs per session; an absent key is an empty set. */
|
||||
jobsBySession: Readonly<Record<SessionId, readonly JobView[]>>
|
||||
currentAddress: SubagentAddress | undefined
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ function bufferedRequestKey(envelope: RpcRequest<MuxFrame>): string | undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Match ui-question's binary plan-review routing at the wire boundary. */
|
||||
/** Match ui-user-questions's binary plan-review routing at the wire boundary. */
|
||||
function questionInteractionStatus(
|
||||
questions: Extract<MuxFrame, { type: 'question/requested' }>['questions'],
|
||||
): PendingInteractionStatus {
|
||||
@@ -143,10 +143,10 @@ export class SessionManager {
|
||||
private readonly openCatalogs = new Set<SessionId>()
|
||||
private readonly catalogDebounce = new Map<SessionId, ReturnType<typeof setTimeout>>()
|
||||
/**
|
||||
* Background tasks per session, last-wins from `session/tasks`. An empty set
|
||||
* Background jobs per session, last-wins from `session/jobs`. An empty set
|
||||
* is stored as an absent key, so absence and `[]` are one representation.
|
||||
*/
|
||||
private readonly tasksBySession = new Map<SessionId, readonly TaskView[]>()
|
||||
private readonly jobsBySession = new Map<SessionId, readonly JobView[]>()
|
||||
|
||||
private selected: SessionId | undefined
|
||||
|
||||
@@ -702,12 +702,12 @@ export class SessionManager {
|
||||
this.notifier.markDirty()
|
||||
return
|
||||
}
|
||||
if (frame.type === 'session/tasks') {
|
||||
if (frame.type === 'session/jobs') {
|
||||
// Whole-set snapshot, so last-wins with no reconciliation. The Host omits
|
||||
// the baseline for an empty set, which is the same fact an emptying change
|
||||
// reports as `[]` — both land as an absent key.
|
||||
if (frame.tasks.length === 0) this.tasksBySession.delete(frame.sessionId)
|
||||
else this.tasksBySession.set(frame.sessionId, frame.tasks)
|
||||
if (frame.jobs.length === 0) this.jobsBySession.delete(frame.sessionId)
|
||||
else this.jobsBySession.set(frame.sessionId, frame.jobs)
|
||||
this.notifier.markDirty()
|
||||
return
|
||||
}
|
||||
@@ -718,7 +718,7 @@ export class SessionManager {
|
||||
// Same re-baseline reasoning as the queue below: this generation sends a
|
||||
// task baseline only when the set is non-empty, so a mirror kept from the
|
||||
// previous generation would survive as a phantom list.
|
||||
this.tasksBySession.delete(frame.sessionId)
|
||||
this.jobsBySession.delete(frame.sessionId)
|
||||
this.notifier.markDirty()
|
||||
// New mux-generation baseline: discard the previous queue snapshot.
|
||||
// The host omits session/queue when the live queue is empty, so retaining
|
||||
@@ -833,7 +833,7 @@ export class SessionManager {
|
||||
// the mux stream while this frame rides the host stream, so the two have
|
||||
// no relative order. Clearing here makes a detached Activation's rows
|
||||
// disappear whichever arrives first.
|
||||
this.tasksBySession.delete(frame.sessionId)
|
||||
this.jobsBySession.delete(frame.sessionId)
|
||||
if (!durableSubagent) this.projectionStores.delete(frame.sessionId)
|
||||
// A pull already in flight was requested before this removal and can
|
||||
// carry the pre-removal parentAvailable:true, which would resurrect
|
||||
@@ -1070,7 +1070,7 @@ export class SessionManager {
|
||||
phase: this.listPhase,
|
||||
error: this.listError,
|
||||
subagentsByParent: Object.fromEntries(this.catalogs),
|
||||
tasksBySession: Object.fromEntries(this.tasksBySession),
|
||||
jobsBySession: Object.fromEntries(this.jobsBySession),
|
||||
currentAddress: current === undefined ? undefined : this.addresses.get(current),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* The session standard-props provide channel: provider roster, bundle
|
||||
* materialization (fail-loud on undeclared/missing/duplicate members), the
|
||||
* static no-session projection, and the atomic current-session projection
|
||||
* observable. One implementation — SessionsService drives it from wire
|
||||
* observable. One implementation — SessionRuntime drives it from wire
|
||||
* truth, the test runtime's sessions double drives it from fixtures — so
|
||||
* the materialization rules and the projection semantics cannot drift
|
||||
* between production and the test bench.
|
||||
@@ -71,7 +71,7 @@ export class SessionProvideChannel {
|
||||
|
||||
/**
|
||||
* Register a per-session standard-props provider (see
|
||||
* SessionsService.provide for the product contract). Live bundles rebuild
|
||||
* SessionRuntime.provide for the product contract). Live bundles rebuild
|
||||
* immediately; misdeclared providers fail loud here, at the registration
|
||||
* edge, and the registration rolls back — the channel never stays on a
|
||||
* roster it cannot materialize.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* SessionsService: root sessions service — list snapshot store (manager
|
||||
* SessionRuntime: root sessions service — list snapshot store (manager
|
||||
* projection; carries `current`, the persisted selection every
|
||||
* session-scoped surface keys off), Agent scope tree (mintScope pattern: no-op plugin
|
||||
* Fiber + ctx.extend scope tag; one scope per session, agent id === session
|
||||
@@ -16,7 +16,7 @@
|
||||
*/
|
||||
import type { Context, Fiber } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
IApiClient, RpcError, RpcResult, SessionId, SubagentAddress, TaskView, WorkspaceId,
|
||||
IApiClient, RpcError, RpcResult, SessionId, SubagentAddress, JobView, WorkspaceId,
|
||||
} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
// Value import from the inline-safe wire layer (not the connection plugin):
|
||||
// plugin-to-plugin value imports are a bundle purity error.
|
||||
@@ -88,11 +88,11 @@ export interface SessionListState {
|
||||
/** Direct durable catalogs keyed by their selected parent address. */
|
||||
subagentsByParent: Readonly<Record<SessionId, SubagentCatalogSnapshot>>
|
||||
/**
|
||||
* Background tasks each session can see, mirrored last-wins from
|
||||
* `session/tasks`. A missing key is an empty set — the Host sends no baseline
|
||||
* Background jobs each session can see, mirrored last-wins from
|
||||
* `session/jobs`. A missing key is an empty set — the Host sends no baseline
|
||||
* for a session without tasks — so consumers read absence, never a sentinel.
|
||||
*/
|
||||
tasksBySession: Readonly<Record<SessionId, readonly TaskView[]>>
|
||||
jobsBySession: Readonly<Record<SessionId, readonly JobView[]>>
|
||||
/** Current session's catalog-derived address, absent on ordinary navigation. */
|
||||
currentAddress: SubagentAddress | undefined
|
||||
}
|
||||
@@ -203,7 +203,7 @@ interface ScopeRecord {
|
||||
provideInfo: SessionProvideInfo
|
||||
}
|
||||
|
||||
/** One plugin's per-session standard-props contribution (see {@link SessionsService.provide}). */
|
||||
/** One plugin's per-session standard-props contribution (see {@link SessionRuntime.provide}). */
|
||||
export interface SessionProvideContribution {
|
||||
/** Bare observable sources, keyed by hook base name ('input' → useInput). */
|
||||
hooks?: Record<string, HostObservable<unknown>>
|
||||
@@ -226,7 +226,7 @@ export interface SessionProvideDescriptor {
|
||||
}
|
||||
|
||||
/** Root sessions service: list store, current selection, object-layer manager, scope tree, bindings, and breadcrumb routes. */
|
||||
export class SessionsService implements ISessions {
|
||||
export class SessionRuntime implements ISessions {
|
||||
/**
|
||||
* The wire schema's own result bound, re-exposed for presentation plugins as
|
||||
* injected data. Not per-connection state: the `session.search` response
|
||||
@@ -249,7 +249,7 @@ export class SessionsService implements ISessions {
|
||||
/**
|
||||
* Persisted selection cell (the durable half of `list.current`). Private on
|
||||
* purpose: reads go through the list snapshot; writes through {@link
|
||||
* SessionsService.open} / {@link SessionsService.clear}. Projection
|
||||
* SessionRuntime.open} / {@link SessionRuntime.clear}. Projection
|
||||
* validates it against the live list instead of destructively pruning, so a
|
||||
* selection survives transient list states (reconnect re-pull) and
|
||||
* resurfaces when its session returns.
|
||||
@@ -301,7 +301,7 @@ export class SessionsService implements ISessions {
|
||||
)
|
||||
this.list = createSnapshotStore<SessionListState>({
|
||||
ids: [], byId: {}, current: undefined, phase: 'pending',
|
||||
subagentsByParent: {}, tasksBySession: {}, currentAddress: undefined,
|
||||
subagentsByParent: {}, jobsBySession: {}, currentAddress: undefined,
|
||||
})
|
||||
// The manager owns wire truth; the store is its projection. Manager
|
||||
// notifications are already microtask-batched.
|
||||
@@ -474,7 +474,7 @@ export class SessionsService implements ISessions {
|
||||
/**
|
||||
* Create a session on the host. Resolution guarantee: by the time the
|
||||
* promise resolves, the created session is in the list store and
|
||||
* {@link SessionsService.binding} resolves it — callers (New Session
|
||||
* {@link SessionRuntime.binding} resolves it — callers (New Session
|
||||
* draft hand-off) may address the scope synchronously, without waiting a
|
||||
* notifier flush. The synchronous projection below makes this structural
|
||||
* rather than an accident of microtask ordering.
|
||||
@@ -491,7 +491,7 @@ export class SessionsService implements ISessions {
|
||||
|
||||
/**
|
||||
* Fork a session from a completed-turn prefix of the source (same
|
||||
* synchronous-addressability guarantee as {@link SessionsService.create}:
|
||||
* synchronous-addressability guarantee as {@link SessionRuntime.create}:
|
||||
* on resolution the child is in the list store and open() can target it).
|
||||
* @param opts - source session id, the optional event seq anchoring the
|
||||
* cut (the boundary is the first turn/end at or after it; an in-log
|
||||
@@ -557,7 +557,7 @@ export class SessionsService implements ISessions {
|
||||
* hop every scoped consumer (event listeners, per-session controllers)
|
||||
* takes from ctx-space into object-space (the client mirror of host
|
||||
* `agent.session`). Same service-method boundary as
|
||||
* {@link SessionsService.scopeOf}.
|
||||
* {@link SessionRuntime.scopeOf}.
|
||||
* @param ctx - an Agent-scoped context.
|
||||
* @returns the session face, or undefined when the ctx is untagged or its scope was pruned.
|
||||
*/
|
||||
@@ -580,7 +580,7 @@ export class SessionsService implements ISessions {
|
||||
/**
|
||||
* Resolve one session's render-layer standard-props bundle (ctx never
|
||||
* enters the render layer; the renderer subscribes to
|
||||
* {@link SessionsService.currentProvideInfo}). Pure resolution — render-safe:
|
||||
* {@link SessionRuntime.currentProvideInfo}). Pure resolution — render-safe:
|
||||
* no staging, no window side effects (StrictMode double-invokes and
|
||||
* concurrent discarded passes must stay free).
|
||||
*/
|
||||
@@ -659,7 +659,7 @@ export class SessionsService implements ISessions {
|
||||
/** Project the manager's list snapshot into the store (title derivation is display-only). */
|
||||
private projectList(): void {
|
||||
const {
|
||||
items, current, phase, subagentsByParent, tasksBySession, currentAddress,
|
||||
items, current, phase, subagentsByParent, jobsBySession, currentAddress,
|
||||
} = this.manager.getListSnapshot()
|
||||
const ids: SessionId[] = []
|
||||
const byId: Record<SessionId, SessionSummary> = {}
|
||||
@@ -729,7 +729,7 @@ export class SessionsService implements ISessions {
|
||||
...(currentAddress === undefined ? {} : { subagentAddress: currentAddress }),
|
||||
})
|
||||
}
|
||||
this.list.set({ ids, byId, current, phase, subagentsByParent, tasksBySession, currentAddress })
|
||||
this.list.set({ ids, byId, current, phase, subagentsByParent, jobsBySession, currentAddress })
|
||||
this.pruneScopes()
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import { EMPTY_CHAT_SNAPSHOT } from './conversation.ts'
|
||||
import type { PendingInteraction } from './pending.ts'
|
||||
import { PendingWait } from './pending.ts'
|
||||
import { Notifier } from './notifier.ts'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-type-meta'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { SessionRemotes } from './remotes.ts'
|
||||
import { ProjectionValueStore } from './projection-store.ts'
|
||||
import type { ProjectionsBaseline } from './projection-store.ts'
|
||||
@@ -125,7 +125,7 @@ export class Session implements SessionFace {
|
||||
private snapshotCache: ConversationSnapshot
|
||||
private readonly notifier: Notifier
|
||||
/**
|
||||
* Agent-scoped cordis context, bound once by SessionsService when it
|
||||
* Agent-scoped cordis context, bound once by SessionRuntime when it
|
||||
* mints the scope (the client mirror of the host Agent's loopCtx). The
|
||||
* Session dispatches its own scoped events through it; undefined means
|
||||
* unbound (bare object-layer construction) or already pruned — both skip
|
||||
@@ -162,7 +162,7 @@ export class Session implements SessionFace {
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the Agent-scoped context minted by SessionsService (single write;
|
||||
* Bind the Agent-scoped context minted by SessionRuntime (single write;
|
||||
* a second bind is a wiring error and throws). Direction stays one-way at
|
||||
* this binding boundary: consumers still reach the Session via `sessions.sessionOf`,
|
||||
* while the Session holds its own dispatch point (host Agent.loopCtx
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* SlotsService: the cordis Service layer of the slot system over the pure
|
||||
* SlotRegistry: the cordis Service layer of the slot system over the pure
|
||||
* SlotCore (ui-slots owns registration semantics, the declaration ledger,
|
||||
* the load-time validations, and the unload cascade). This layer owns what
|
||||
* needs the runtime: the 'slots/changed' event bridge, register and
|
||||
@@ -18,13 +18,26 @@ import { Service } from '@deepseek-ai/cordis'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {
|
||||
LocaleFace, OwnerOf, SlotEntryDef, SlotMap, SlotRenderer, SlotRendererHost,
|
||||
LiveSlotNode, LocaleFace, OwnerOf, SlotEntryDef, SlotMap, SlotRenderer, SlotRendererHost,
|
||||
SlotScope, SlotSpec, StoreDecl, StoreFactory, StoredEntry, StoreInstanceLike,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
/** The built-in render-tree root hole (seeded by SlotCore): rendered only by the shell, occupied by a layout entry. */
|
||||
/**
|
||||
* The built-in render-tree root hole (seeded by SlotCore): the one slot the
|
||||
* shell itself renders, and the ancestor of every other seat. OCCUPIED by
|
||||
* ui-layout's AppFrame, which declares the sidebar, conversation, details,
|
||||
* and shell.overlay seats inside it.
|
||||
*
|
||||
* DO NOT register here. This is a single slot, so a second entry does not
|
||||
* sit beside the frame — it shadows it, and a dynamically registered entry
|
||||
* is assigned a lower priority than the shipped one, which makes it the
|
||||
* winner: the page would render your component alone, with every seat the
|
||||
* frame declares gone. For a surface of your own that floats over the whole
|
||||
* app, register into `shell.overlay` instead (a list slot: additive, and
|
||||
* click-through until your entry opts into pointer events).
|
||||
*/
|
||||
'root': { kind: 'single'; scope: 'root'; owner: RootOwnerProps }
|
||||
}
|
||||
}
|
||||
@@ -77,7 +90,7 @@ interface ErasedCore { register(options: object, component: unknown): () => void
|
||||
type SlotInjectionEffect = (() => void) | Iterable<() => void, void, void>
|
||||
|
||||
/** cordis Service layer of the slot system; see the module doc for the split with SlotCore. */
|
||||
export class SlotsService extends Service {
|
||||
export class SlotRegistry extends Service {
|
||||
private readonly _core = new SlotCore()
|
||||
/** Store-instance axis: handle -> mounted scope, refcount, resolved instances. */
|
||||
private readonly _stores = new Map<EngineStoreHandle, StoreAxisRecord>()
|
||||
@@ -274,6 +287,43 @@ export class SlotsService extends Service {
|
||||
return this._core.entries(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shadowing winners per cell for a key: the first live (non-abdicated)
|
||||
* entry of each cell in priority order — what outlets render; chain keys
|
||||
* pass through unchanged (election consumes every entry). The raw
|
||||
* {@link SlotsService.entries} view stays the inspection surface. Fresh
|
||||
* array per call, not a uSES getSnapshot source.
|
||||
* @param key - SlotMap key.
|
||||
* @returns the winning entry per occupied cell.
|
||||
*/
|
||||
entriesOfSlot(key: keyof SlotMap & string): readonly StoredEntry[] {
|
||||
return this._core.entriesOfSlot(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Export the current JSON-safe Slot declaration tree for read-only inspection.
|
||||
* @param root - exact live Slot root; omitted returns all roots.
|
||||
* @returns selected Slot trees.
|
||||
*/
|
||||
snapshot(root?: string): LiveSlotNode[] {
|
||||
return this._core.snapshot(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe entry boundary crashes (every render-time entry failure the
|
||||
* boundaries contain, abdicating or not) — the supervision seam for
|
||||
* plugins mirroring contribution health. Fires synchronously per report,
|
||||
* after the registry mutated for abdicating crashes. Callers own the
|
||||
* disposer (wire it through ctx.effect for fiber-lifetime cleanup, as with
|
||||
* {@link SlotsService.subscribe}).
|
||||
* @param fn - called with the slot key, the crashed entry, the crash
|
||||
* cause, and `abdicated`: whether the crash retired the entry from its cell.
|
||||
* @returns unsubscribe.
|
||||
*/
|
||||
onEntryError(fn: (key: string, entry: StoredEntry, error: unknown, info: { abdicated: boolean }) => void): () => void {
|
||||
return this._core.onEntryError(fn)
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a declared spec (register-declared or the built-in 'root').
|
||||
* @param key - SlotMap key.
|
||||
@@ -353,6 +403,8 @@ export class SlotsService extends Service {
|
||||
subscribe: (key, fn) => this._core.subscribe(key, fn),
|
||||
getVersion: key => this._core.getVersion(key),
|
||||
entriesOf: key => this._core.entries(key),
|
||||
entriesOfSlot: key => this._core.entriesOfSlot(key),
|
||||
reportEntryError: (key, entry, error, info) => { this._core.reportEntryError(key, entry, error, info) },
|
||||
specOf: key => this._core.specDynamic(key),
|
||||
isLive: entry => this._core.isLive(entry),
|
||||
storeOf: (entry, scopeKey) =>
|
||||
@@ -409,8 +461,8 @@ export class SlotsService extends Service {
|
||||
// inside the class — see its JSDoc for why it must live on the prototype).
|
||||
// Element access reaches the private _register legally and keeps it a
|
||||
// TS-visible read.
|
||||
;(SlotsService.prototype as { register: (options: object, component: unknown) => () => void }).register
|
||||
= function register(this: SlotsService, rawOptions: object, component: unknown): () => void {
|
||||
;(SlotRegistry.prototype as { register: (options: object, component: unknown) => () => void }).register
|
||||
= function register(this: SlotRegistry, rawOptions: object, component: unknown): () => void {
|
||||
// The core's overloads proved the shares; the implementation works on
|
||||
// the erased view (same pattern as the core's own implementation arm).
|
||||
const options = rawOptions as ErasedRegisterOptions
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** WorkspacesService projects the Workspace object manager for UI consumers. */
|
||||
/** WorkspaceRuntime projects the Workspace object manager for UI consumers. */
|
||||
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
@@ -48,7 +48,7 @@ export class DirectoryBrowseError extends Error {
|
||||
}
|
||||
|
||||
/** Real Workspace object layer and Host actions. */
|
||||
export class WorkspacesService implements IWorkspaces {
|
||||
export class WorkspaceRuntime implements IWorkspaces {
|
||||
/** UI-facing immutable projection; the manager remains wire truth. */
|
||||
readonly list: SnapshotStore<WorkspaceListState>
|
||||
/** Workspace baseline and frame owner. */
|
||||
|
||||
@@ -12,8 +12,8 @@ import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
|
||||
import * as RuntimeClient from '../src/client/index.ts'
|
||||
import type { ConversationNodeDefinition } from '../src/client/contract/conversation.ts'
|
||||
import { Session } from '../src/client/sessions/session.ts'
|
||||
import type { SessionsService } from '../src/client/sessions/service.ts'
|
||||
import type { WorkspacesService } from '../src/client/workspaces/service.ts'
|
||||
import type { SessionRuntime } from '../src/client/sessions/service.ts'
|
||||
import type { WorkspaceRuntime } from '../src/client/workspaces/service.ts'
|
||||
import { FakeApiClient, fakeRemote, ok } from './fake-api.client.ts'
|
||||
|
||||
interface Bench {
|
||||
@@ -58,7 +58,7 @@ describe('runtime client apply', () => {
|
||||
it('mounts slots, Sessions, and Workspaces and fans host frames into both managers', async () => {
|
||||
const bench = await mount()
|
||||
expect(bench.ctx.get('slots') !== undefined).toBe(true)
|
||||
// The built-in 'root' declaration ships with this package's SlotsService
|
||||
// The built-in 'root' declaration ships with this package's SlotRegistry
|
||||
// (the SlotMap 'root' merge lives here).
|
||||
expect(bench.ctx.slots.spec('root')).toEqual({ kind: 'single', scope: 'root' })
|
||||
const sessions = bench.ctx.get('sessions')
|
||||
@@ -66,8 +66,8 @@ describe('runtime client apply', () => {
|
||||
expect(sessions !== undefined).toBe(true)
|
||||
expect(workspaces !== undefined).toBe(true)
|
||||
// The bound the wire schema enforces, not a per-connection negotiation.
|
||||
expect((sessions as SessionsService).searchResultLimit).toBe(SESSION_SEARCH_RESULT_LIMIT)
|
||||
if (workspaces === undefined) throw new Error('WorkspacesService missing after runtime apply')
|
||||
expect((sessions as SessionRuntime).searchResultLimit).toBe(SESSION_SEARCH_RESULT_LIMIT)
|
||||
if (workspaces === undefined) throw new Error('WorkspaceRuntime missing after runtime apply')
|
||||
expect(bench.sinks).toBeDefined()
|
||||
|
||||
// Frame sinks reach the object layer: a host session-added lands in the list store.
|
||||
@@ -107,8 +107,8 @@ describe('runtime client apply', () => {
|
||||
bench.sinks?.onConnected?.({ version: '0', cwd: '/f', attachedSessions: 0, canOpenPath: true })
|
||||
await flushMicrotasks()
|
||||
|
||||
const sessions = bench.ctx.get('sessions') as SessionsService
|
||||
const workspaces = bench.ctx.get('workspaces') as WorkspacesService
|
||||
const sessions = bench.ctx.get('sessions') as SessionRuntime
|
||||
const workspaces = bench.ctx.get('workspaces') as WorkspaceRuntime
|
||||
expect(bench.api.callsOf('session.create')).toEqual([{ workspaceId: 'w-recent' }])
|
||||
expect(sessions.list.getSnapshot().current).toBe('fk-new')
|
||||
|
||||
@@ -121,7 +121,7 @@ describe('runtime client apply', () => {
|
||||
|
||||
it('wires registry changes into resident Sessions during the runtime apply pass', async () => {
|
||||
const bench = await mount()
|
||||
const sessions = bench.ctx.get('sessions') as SessionsService
|
||||
const sessions = bench.ctx.get('sessions') as SessionRuntime
|
||||
bench.sinks?.onHostEnvelope?.({
|
||||
rpcId: 'r-registry' as never,
|
||||
payload: { type: 'host/session-added', blank: true, sessionId: 's-registry' } as never,
|
||||
|
||||
Binary file not shown.
@@ -730,7 +730,7 @@ describe('ConversationNodeAssembler', () => {
|
||||
role: 'start',
|
||||
}
|
||||
}
|
||||
if ((event.type as string) === 'compact/start') {
|
||||
if ((event.type as string) === 'compaction/start') {
|
||||
return {
|
||||
id: (event.data as unknown as { compactionId: string }).compactionId,
|
||||
role: 'start',
|
||||
@@ -758,7 +758,7 @@ describe('ConversationNodeAssembler', () => {
|
||||
input(at(2, 'step/start', { turn: 1, step: 1 })),
|
||||
input(at(3, 'turn/start', { turn: 2 })),
|
||||
input(at(4, 'command/run', { commandId: 'command', name: 'x' })),
|
||||
input(at(5, 'compact/start', { compactionId: 'compact', turn: null })),
|
||||
input(at(5, 'compaction/start', { compactionId: 'compact', turn: null })),
|
||||
], false)
|
||||
assembler.flush()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
ConversationNodeDefinition, ConversationViewDefinition, ConversationViewNode,
|
||||
} from '../src/client/contract/conversation.ts'
|
||||
import { Session } from '../src/client/sessions/session.ts'
|
||||
import { SessionsService } from '../src/client/sessions/service.ts'
|
||||
import { SessionRuntime } from '../src/client/sessions/service.ts'
|
||||
import { FakeApiClient, fakeRemote, ok } from './fake-api.client.ts'
|
||||
|
||||
function eventDefinition(kind: string): ConversationNodeDefinition<null> {
|
||||
@@ -145,7 +145,7 @@ describe('Conversation registries', () => {
|
||||
api.onList = () => Promise.resolve(ok({
|
||||
items: [{ sessionId, updatedAt: 1, running: false, blank: true }],
|
||||
}) as never)
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
await sessions.refresh()
|
||||
await Promise.resolve()
|
||||
sessions.scope(sessionId)
|
||||
|
||||
@@ -105,9 +105,9 @@ export const ev = {
|
||||
...text === undefined ? {} : { text },
|
||||
...sourceEventSeq === undefined ? {} : { sourceEventSeq },
|
||||
} }),
|
||||
/** A compaction's log-only `compact/summary` record. */
|
||||
/** A compaction's log-only `compaction/summary` record. */
|
||||
compactSummary: (seq: number, summary: string, start: number, end: number): SessionEvent =>
|
||||
at(seq, { type: 'compact/summary', data: {
|
||||
at(seq, { type: 'compaction/summary', data: {
|
||||
summary: text(summary),
|
||||
shadowedRange: { start, end },
|
||||
shadowedSeqs: [start, end],
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
*/
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
||||
import * as RuntimeInvariant from '../src/invariant.ts'
|
||||
import { SlotsService } from '../src/client/slots.ts'
|
||||
import { SlotRegistry } from '../src/client/slots.ts'
|
||||
|
||||
async function setup(): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(InvariantRegistry, { enabled: true })
|
||||
await ctx.plugin(RuntimeInvariant).await()
|
||||
return ctx
|
||||
}
|
||||
@@ -24,7 +24,7 @@ describe('runtime slots/changed invariant', () => {
|
||||
it('passes foreign events and a legitimate mutation-then-emission sequence', async () => {
|
||||
const ctx = await setup()
|
||||
expect(() => { emit(ctx, 'unrelated/event', 'x') }).not.toThrow()
|
||||
await ctx.plugin(SlotsService).await() // fiber must reach ACTIVE — the audit reads strict ctx.get
|
||||
await ctx.plugin(SlotRegistry).await() // fiber must reach ACTIVE — the audit reads strict ctx.get
|
||||
// A real registration bumps the version first and re-emits through
|
||||
// onMutate — the audit sees version > 0 and stays quiet. (Erased call:
|
||||
// the typed register face rides the wave-1 ui-slots types.)
|
||||
@@ -36,7 +36,7 @@ describe('runtime slots/changed invariant', () => {
|
||||
const ctx = await setup()
|
||||
expect(() => { emit(ctx, 'slots/changed', '') }).toThrow(/without a slot key/)
|
||||
expect(() => { emit(ctx, 'slots/changed', 42) }).toThrow(/without a slot key/)
|
||||
await ctx.plugin(SlotsService).await()
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
// Hand-emitted key that never saw a mutation: version 0 → violation.
|
||||
expect(() => { emit(ctx, 'slots/changed', 'never-mutated') })
|
||||
.toThrow(/before any mutation bumped its version/)
|
||||
|
||||
@@ -1152,32 +1152,32 @@ describe('completed reminder', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('background-task mirror', () => {
|
||||
describe('background-job mirror', () => {
|
||||
const view = (over: Partial<{ id: string; status: string; label: string }> = {}) => ({
|
||||
id: 'bash-1', kind: 'bash', label: 'pnpm run build', status: 'running', startedAt: 5, ...over,
|
||||
})
|
||||
const tasksFrame = (sessionId: SessionId, tasks: unknown[]) =>
|
||||
({ rpcId: 't' as never, payload: { type: 'session/tasks', sessionId, tasks } as never })
|
||||
const tasksFrame = (sessionId: SessionId, jobs: unknown[]) =>
|
||||
({ rpcId: 't' as never, payload: { type: 'session/jobs', sessionId, jobs } as never })
|
||||
|
||||
it('mirrors the whole set last-wins, keyed per session, with no Session instance needed', () => {
|
||||
const manager = new SessionManager(new FakeApiClient(), fakeRemote())
|
||||
manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
|
||||
manager.handleMuxEnvelope(tasksFrame(S2, [view({ id: 'pwsh-1', label: 'other' })]))
|
||||
const first = manager.getListSnapshot().tasksBySession
|
||||
const first = manager.getListSnapshot().jobsBySession
|
||||
expect(first[S1]).toEqual([view()])
|
||||
expect(first[S2]?.[0]?.label).toBe('other')
|
||||
|
||||
// Last-wins: the newer whole set replaces, it does not merge.
|
||||
manager.handleMuxEnvelope(tasksFrame(S1, [view({ status: 'completed' })]))
|
||||
expect(manager.getListSnapshot().tasksBySession[S1]).toEqual([view({ status: 'completed' })])
|
||||
expect(manager.getListSnapshot().jobsBySession[S1]).toEqual([view({ status: 'completed' })])
|
||||
})
|
||||
|
||||
it('stores an emptied set as an absent key so absence and [] read alike', () => {
|
||||
const manager = new SessionManager(new FakeApiClient(), fakeRemote())
|
||||
manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
|
||||
expect(S1 in manager.getListSnapshot().tasksBySession).toBe(true)
|
||||
expect(S1 in manager.getListSnapshot().jobsBySession).toBe(true)
|
||||
manager.handleMuxEnvelope(tasksFrame(S1, []))
|
||||
expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
|
||||
expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the mirror on re-subscribe, because a task-free generation sends no baseline', () => {
|
||||
@@ -1187,7 +1187,7 @@ describe('background-task mirror', () => {
|
||||
rpcId: 's' as never,
|
||||
payload: { type: 'session/subscribed', sessionId: S1, lastSeq: 3 },
|
||||
})
|
||||
expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
|
||||
expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
|
||||
})
|
||||
|
||||
it('drops the rows when the session is removed, whichever stream lands first', () => {
|
||||
@@ -1195,7 +1195,7 @@ describe('background-task mirror', () => {
|
||||
manager.handleHostEnvelope({ rpcId: 'a' as never, payload: { type: 'host/session-added', blank: true, sessionId: S1 } })
|
||||
manager.handleMuxEnvelope(tasksFrame(S1, [view()]))
|
||||
manager.handleHostEnvelope({ rpcId: 'r' as never, payload: { type: 'host/session-removed', sessionId: S1 } })
|
||||
expect(S1 in manager.getListSnapshot().tasksBySession).toBe(false)
|
||||
expect(S1 in manager.getListSnapshot().jobsBySession).toBe(false)
|
||||
})
|
||||
|
||||
it('notifies list subscribers so an open header re-renders without a poll', async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* SessionsService: list store projection (manager → {ids, byId, current}
|
||||
* SessionRuntime: list store projection (manager → {ids, byId, current}
|
||||
* with derived titles), the migrated current-selection account (open
|
||||
* validation, persisted mask semantics, cell resolution), scope-tree
|
||||
* lifecycle (lazy mint / frozen survival / removed teardown with staged
|
||||
@@ -9,7 +9,7 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import { SessionCreateError, SessionsService, scopeOf } from '../src/client/sessions/service.ts'
|
||||
import { SessionCreateError, SessionRuntime, scopeOf } from '../src/client/sessions/service.ts'
|
||||
import { FakeApiClient, deferred, err, fakeRemote, ok } from './fake-api.client.ts'
|
||||
|
||||
const sid = (s: string): SessionId => s as SessionId
|
||||
@@ -17,13 +17,13 @@ const sid = (s: string): SessionId => s as SessionId
|
||||
interface Bench {
|
||||
ctx: Context
|
||||
api: FakeApiClient
|
||||
svc: SessionsService
|
||||
svc: SessionRuntime
|
||||
}
|
||||
|
||||
function bench(): Bench {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const svc = new SessionsService(ctx, api, fakeRemote())
|
||||
const svc = new SessionRuntime(ctx, api, fakeRemote())
|
||||
return { ctx, api, svc }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* SlotsService terminal-design account:
|
||||
* SlotRegistry terminal-design account:
|
||||
* built-in 'root', the three load-time throws (duplicate declaration /
|
||||
* undeclared contribution / cross-scope store handle), the renderer installation
|
||||
* contract (double install / not installed / non-root key), store instance
|
||||
@@ -9,7 +9,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { FC } from 'react'
|
||||
import type { SlotRendererHost } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { SlotsService } from '../src/client/slots.ts'
|
||||
import { SlotRegistry } from '../src/client/slots.ts'
|
||||
|
||||
// Test-only slot keys (merged so the typed entries/spec faces accept them).
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
@@ -36,13 +36,13 @@ interface ErasedService {
|
||||
|
||||
interface Bench {
|
||||
ctx: Context
|
||||
svc: SlotsService
|
||||
svc: SlotRegistry
|
||||
erased: ErasedService
|
||||
}
|
||||
|
||||
async function boot(): Promise<Bench> {
|
||||
const ctx = new Context()
|
||||
const fiber = ctx.plugin(SlotsService)
|
||||
const fiber = ctx.plugin(SlotRegistry)
|
||||
await fiber
|
||||
// Service accessor (ctx.get reads the reflect store, which Service-class
|
||||
// plugins do not write; the accessor is the product path).
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import { SessionsService } from '../src/client/sessions/service.ts'
|
||||
import { SessionRuntime } from '../src/client/sessions/service.ts'
|
||||
import { WorkspaceManager } from '../src/client/workspaces/manager.ts'
|
||||
import { DirectoryBrowseError, WorkspaceCreateError, WorkspacesService } from '../src/client/workspaces/service.ts'
|
||||
import { DirectoryBrowseError, WorkspaceCreateError, WorkspaceRuntime } from '../src/client/workspaces/service.ts'
|
||||
import { FakeApiClient, deferred, err, fakeRemote, ok } from './fake-api.client.ts'
|
||||
|
||||
const sid = (id: string): SessionId => id as SessionId
|
||||
@@ -187,12 +187,12 @@ describe('WorkspaceManager', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('WorkspacesService', () => {
|
||||
describe('WorkspaceRuntime', () => {
|
||||
it('feeds readiness and recent-Workspace targeting without changing Host order', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({
|
||||
items: [
|
||||
workspace('stable-first', [], '2026-01-03T00:00:00.000Z'),
|
||||
@@ -219,8 +219,8 @@ describe('WorkspacesService', () => {
|
||||
it('connectWorkspace reuses the workspace-member blank session and creates otherwise', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({
|
||||
items: [workspace('alpha', [sid('s-blank')]), workspace('beta'), workspace('gamma')] as never[],
|
||||
}))
|
||||
@@ -278,8 +278,8 @@ describe('WorkspacesService', () => {
|
||||
it('a rejected first prompt keeps the blank session eligible for connectWorkspace reuse', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({ items: [workspace('alpha', [sid('s-blank')])] as never[] }))
|
||||
api.onList = () => Promise.resolve(ok({
|
||||
items: [{ sessionId: sid('s-blank'), updatedAt: 2, running: false, blank: true, cwd: '/w/alpha' }] as never[],
|
||||
@@ -298,8 +298,8 @@ describe('WorkspacesService', () => {
|
||||
it('returns created Workspaces and preserves Host business errors', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceCreate = () => Promise.resolve(ok({
|
||||
workspace: { ...workspace('picked'), path: '/w/alpha', title: 'alpha' }, created: true,
|
||||
}))
|
||||
@@ -317,8 +317,8 @@ describe('WorkspacesService', () => {
|
||||
it('passes native directory selection and cancellation through without local state', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onPickDirectory = () => Promise.resolve(ok({ path: '/w/alpha' }))
|
||||
await expect(workspaces.pickDirectory()).resolves.toBe('/w/alpha')
|
||||
api.onPickDirectory = () => Promise.resolve(ok({ path: null }))
|
||||
@@ -331,7 +331,7 @@ describe('WorkspacesService', () => {
|
||||
it('passes listings and creation through the browse wire, wrapping business failures', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const workspaces = new WorkspacesService(ctx, api, new SessionsService(ctx, api, fakeRemote()))
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, new SessionRuntime(ctx, api, fakeRemote()))
|
||||
const listing = { path: '/home/u', home: '/home/u', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [{ name: 'p', path: '/home/u/p', hidden: false }], truncated: false }
|
||||
api.onListDirectory = () => Promise.resolve(ok(listing))
|
||||
await expect(workspaces.listDirectory()).resolves.toEqual(listing)
|
||||
@@ -352,8 +352,8 @@ describe('WorkspacesService', () => {
|
||||
it('opens a filesystem path through the host without local state', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
await expect(workspaces.openPath('/w/alpha/a.ts')).resolves.toBeUndefined()
|
||||
expect(api.callsOf('host.openPath')).toEqual([{ path: '/w/alpha/a.ts' }])
|
||||
api.onOpenPath = () => Promise.resolve(err({ code: 'internal', message: 'boom', details: {} }))
|
||||
@@ -363,8 +363,8 @@ describe('WorkspacesService', () => {
|
||||
it('deletes a Workspace or preserves it when the Host rejects deletion', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({ items: [workspace('alpha')] as never[] }))
|
||||
await workspaces.refresh()
|
||||
await expect(workspaces.delete(wid('alpha'))).resolves.toBeUndefined()
|
||||
@@ -379,7 +379,7 @@ describe('WorkspacesService', () => {
|
||||
it('moves a Workspace through the durable order RPC and surfaces Host rejection', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const workspaces = new WorkspacesService(ctx, api, new SessionsService(ctx, api, fakeRemote()))
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, new SessionRuntime(ctx, api, fakeRemote()))
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({
|
||||
items: [workspace('one'), workspace('two')] as never[],
|
||||
}))
|
||||
@@ -402,8 +402,8 @@ describe('WorkspacesService', () => {
|
||||
it('targets New Session at explicit, current-session, then recent Workspaces and clears with none', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onWorkspaceList = () => Promise.resolve(ok({
|
||||
items: [
|
||||
workspace('current-home', [sid('current')]),
|
||||
@@ -435,8 +435,8 @@ describe('WorkspacesService', () => {
|
||||
|
||||
const emptyCtx = new Context()
|
||||
const emptyApi = new FakeApiClient()
|
||||
const emptySessions = new SessionsService(emptyCtx, emptyApi, fakeRemote())
|
||||
const emptyWorkspaces = new WorkspacesService(emptyCtx, emptyApi, emptySessions)
|
||||
const emptySessions = new SessionRuntime(emptyCtx, emptyApi, fakeRemote())
|
||||
const emptyWorkspaces = new WorkspaceRuntime(emptyCtx, emptyApi, emptySessions)
|
||||
const clear = vi.spyOn(emptySessions, 'clear')
|
||||
emptyWorkspaces.startSession()
|
||||
expect(clear).toHaveBeenCalledOnce()
|
||||
@@ -445,8 +445,8 @@ describe('WorkspacesService', () => {
|
||||
it('archives a session, projects the set from the response, list, and frame, and clears only the current one', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onList = () => Promise.resolve(ok({
|
||||
items: [
|
||||
{ sessionId: sid('s-open'), updatedAt: 2, running: false, blank: false },
|
||||
@@ -491,8 +491,8 @@ describe('WorkspacesService', () => {
|
||||
it('clears a current archived by a remote frame and shields the set from a stale in-flight baseline', async () => {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
api.onList = () => Promise.resolve(ok({
|
||||
items: [{ sessionId: sid('s-open'), updatedAt: 1, running: false, blank: false }],
|
||||
}) as never)
|
||||
@@ -525,8 +525,8 @@ describe('startInitialSelection', () => {
|
||||
function bench() {
|
||||
const ctx = new Context()
|
||||
const api = new FakeApiClient()
|
||||
const sessions = new SessionsService(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspacesService(ctx, api, sessions)
|
||||
const sessions = new SessionRuntime(ctx, api, fakeRemote())
|
||||
const workspaces = new WorkspaceRuntime(ctx, api, sessions)
|
||||
return { api, sessions, workspaces }
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
"path": "../../core/tools"
|
||||
},
|
||||
{
|
||||
"path": "../../compact/compact"
|
||||
"path": "../../compaction/compaction"
|
||||
},
|
||||
{
|
||||
"path": "../../session/session-projection"
|
||||
@@ -48,10 +48,10 @@
|
||||
"path": "../../llm/llm-retry"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../typert/type-meta"
|
||||
"path": "../../typert/protocol"
|
||||
},
|
||||
{
|
||||
"path": "../../typert/registry"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-schema-form",
|
||||
"description": "Schema/draft model layer for settings editors: rehydrates a serialized schemastery schema, validates drafts, and edits them immutably by path",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as SchemaFormInvariant from '@deepseek-ai/dsh-client-schema-form/invariant'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
describe('invariant companion', () => {
|
||||
it('registers under the package name with an empty installer', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(InvariantRegistry, { enabled: true })
|
||||
await expect(ctx.plugin(SchemaFormInvariant).await()).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -12,7 +12,7 @@
|
||||
"path": "../../../vendor/schemastery"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
# @deepseek-ai/dsh-client-test-runtime
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
jsdom slot test runtime for client feature specs: a real Cordis `Context`, the production `SlotsService` and web-react renderer, assembled around typed session/workspace doubles. Feature suites exercise declaration, registration, scope, store, inject, rendering, updates, and disposal without hand-building the machinery per suite — and without a second implementation of any production logic.
|
||||
|
||||
The doubles implement the same outward faces features receive through ctx (`TestSessions implements ISessions`, `TestWorkspaces implements IWorkspaces`; each fixture session is a `FixtureSession implements SessionFace`; `stubSettingsScope` is a `SettingsScope` with test-driven publications and a write spy), so a production face change breaks the bench at compile time instead of silently drifting. Provide-bundle materialization runs the production `SessionProvideChannel` — the one implementation shared with `SessionsService`. Fixtures feed plain data: list rows, conversation snapshots (immer-patched via `updateSnapshot`), projection values, and `ISession`-typed behavior stubs that fail loud when a spec calls an unstubbed verb. The typed `provide()` constrains fakes for declared service names to `Partial` of that service's outward face.
|
||||
|
||||
Local DOM snapshots: `declare(children)` registers an auto frame whose per-key `<div data-slot>` wrappers are snapshot roots; `renderSlot(key, owner)` returns the slot-local view (container, scoped Testing Library queries, in-place `update(owner)`); a registered snapshot serializer folds CSS-module class hashes (`_frame_a1b2c3` → `frame`) to keep `.snap` files structural and collapses `<svg>` internals to a `data-content` fingerprint. Suites needing a custom page frame use `root.declare(children, Frame)` instead; `mount(plugin)` runs a real fiber with fail-loud service prechecks, and `dispose()` tears down views, feature fibers, minted scopes, and persisted store state on one axis.
|
||||
|
||||
Not part of the product plugin graph (no `dsh.client`); feature packages depend on it in `devDependencies` only.
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as this package is browser-side test infrastructure; nothing here reaches a model request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends a provider request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Consumed through repository source aliases only.** Specs resolve the package through tsconfig `paths` to `src`; the built `lib/` artifact re-exports `@deepseek-ai/dsh-client-runtime/client`, whose bundle is a browser loader script with no Node ESM exports, so `lib/index.js` is not importable under plain Node. Every consumer is an in-repository Vitest suite; there is no Node-compatible runtime entry.
|
||||
- **Conversation snapshots are fixture data, not replayed history.** `updateSnapshot` writes the snapshot store directly; the wire-to-snapshot computation stays covered by the runtime package's own tests and the replay e2e. A fixture can therefore express states the production projection would never produce.
|
||||
@@ -1,24 +0,0 @@
|
||||
# @deepseek-ai/dsh-client-test-runtime
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
面向客户端功能测试的 jsdom slot 测试运行时:真实 Cordis `Context`、生产 `SlotsService` 与 web-react 渲染器,围绕带类型的 session/workspace 测试替身组装。功能套件无需逐套件手搭机器即可测遍声明、注册、scope、store、inject、渲染、更新与销毁——且不存在任何生产逻辑的第二份实现。
|
||||
|
||||
替身实现的正是功能通过 ctx 获得的对外接口(`TestSessions implements ISessions`、`TestWorkspaces implements IWorkspaces`;每个 fixture session 是 `FixtureSession implements SessionFace`;`stubSettingsScope` 是发布由测试驱动、带写入 spy 的 `SettingsScope`),生产面一旦改形,测试台在编译期即断,而非静默漂移。provide bundle 材料化直接运行生产 `SessionProvideChannel`——与 `SessionsService` 共用同一份实现。fixture 灌入的是普通数据:列表行、会话快照(经 `updateSnapshot` 以 immer 补丁改写)、projection 值,以及按 `ISession` 取型的行为桩——spec 调用未打桩的动词时报错自明。带类型的 `provide()` 将已声明服务名的 fake 约束为该服务对外面的 `Partial` 子集。
|
||||
|
||||
局部 DOM 快照:`declare(children)` 注册自动 frame,逐 key 的 `<div data-slot>` 包裹层即快照根;`renderSlot(key, owner)` 返回该 slot 的局部视图(container、限定范围的 Testing Library 查询、原位 `update(owner)`);注册的快照序列化器把 CSS-module 哈希类名折回语义名(`_frame_a1b2c3` → `frame`)保持 `.snap` 只含结构,并把 `<svg>` 内部折叠为 `data-content` 指纹。需要自定义页面 frame 的套件改用 `root.declare(children, Frame)`;`mount(plugin)` 在真实 fiber 上运行并对缺失服务先行报错;`dispose()` 沿单一轴拆除视图、feature fiber、已铸 scope 与持久化 store 状态。
|
||||
|
||||
不属于产品插件图(无 `dsh.client`);feature 包仅以 `devDependencies` 依赖之。
|
||||
|
||||
## 模型体验
|
||||
|
||||
无;本包是浏览器侧测试基础设施,无一物到达模型请求。
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
无;本包既不组装也不发送提供方请求。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
- **仅可经仓内源码别名消费。** spec 通过 tsconfig `paths` 解析到 `src`;构建产物 `lib/` 再导出 `@deepseek-ai/dsh-client-runtime/client`,而该 bundle 是无 Node ESM 导出的浏览器 loader 脚本,故 `lib/index.js` 在纯 Node 下不可导入。所有消费方都是仓内 Vitest 套件;不存在 Node 兼容的运行时入口。
|
||||
- **会话快照是 fixture 数据,不是重放历史。** `updateSnapshot` 直写快照 store;wire 到快照的运算仍由 runtime 包自身测试与 replay e2e 把守。因此 fixture 可以表达生产投影永不产出的状态。
|
||||
@@ -1,61 +0,0 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-test-runtime",
|
||||
"description": "jsdom slot test runtime: real Cordis Context + SlotsService + web-react renderer with test-owned session/workspace doubles for feature specs",
|
||||
"version": "0.0.1-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/client/test-runtime"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"vitest": "^4.1.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-web-react": "workspace:^",
|
||||
"@deepseek-ai/dsh-host-apiproxy": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@deepseek-ai/cordis": "workspace:^",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-web-react": "workspace:^",
|
||||
"@deepseek-ai/dsh-host-apiproxy": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@types/react": "~18.3.1",
|
||||
"@types/react-dom": "~18.3.0",
|
||||
"@deepseek-ai/cordis": "workspace:^",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/** Session/workspace fixture shapes and snapshot defaults for the test runtime. */
|
||||
import type {
|
||||
ConversationSnapshot, ISession, SessionId, SessionSummary, WorkspaceListState,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import {
|
||||
EMPTY_CHAT_SNAPSHOT, EMPTY_CONVERSATION_VIEWS,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
/**
|
||||
* Fixture overrides for the session behavior face: any subset of the
|
||||
* production ISession verbs (typed against it, so a face change surfaces
|
||||
* here at compile time), plus extra members feature-specific casts consume.
|
||||
* The open Record tail means a misnamed EXTRA member is not caught by the
|
||||
* compiler (it grafts as dead weight); the ISession verbs stay safe — a
|
||||
* misnamed verb leaves the fail-loud stub in place, which names itself at
|
||||
* the first call.
|
||||
*/
|
||||
export type SessionBehaviorOverrides = Partial<ISession> & Record<string, unknown>
|
||||
|
||||
/**
|
||||
* act-wrapped mutation runner shared by every runtime object: public mutators
|
||||
* funnel through it so tests never handle SlotCore microtask batching or
|
||||
* React act themselves.
|
||||
*/
|
||||
export type Stabilizer = (fn: () => void | Promise<void>) => Promise<void>
|
||||
|
||||
/**
|
||||
* Session fixture accepted by {@link TestSessions.add}: identity plus optional
|
||||
* snapshot/list-row overrides and the session behavior face the feature under
|
||||
* test actually calls (kept open — the runtime never fakes methods a test did
|
||||
* not supply, so an unstubbed call fails loud at the call site).
|
||||
*/
|
||||
export interface SessionFixture {
|
||||
id: string
|
||||
/** Overrides merged over {@link conversationSnapshot} (sessionId comes from `id`). */
|
||||
snapshot?: Partial<Omit<ConversationSnapshot, 'sessionId'>>
|
||||
/** List-row overrides merged over the defaults derived from `id`. */
|
||||
summary?: Partial<Omit<SessionSummary, 'id'>>
|
||||
/** Session behavior face: exactly the methods the feature under test calls (ISession subset + extras). */
|
||||
session?: SessionBehaviorOverrides
|
||||
}
|
||||
|
||||
/**
|
||||
* A complete quiescent conversation snapshot (open window, no traffic).
|
||||
* @param sessionId - owning session id.
|
||||
* @returns the snapshot; spread fixture overrides on top.
|
||||
*/
|
||||
export function conversationSnapshot(sessionId: SessionId): ConversationSnapshot {
|
||||
return {
|
||||
sessionId,
|
||||
views: EMPTY_CONVERSATION_VIEWS,
|
||||
chat: EMPTY_CHAT_SNAPSHOT,
|
||||
nodes: [],
|
||||
turnTimings: new Map(),
|
||||
turnEnds: new Map(),
|
||||
partial: null,
|
||||
runningCalls: [],
|
||||
pending: [],
|
||||
queue: [],
|
||||
running: false,
|
||||
subagent: null,
|
||||
composerPhase: 'active',
|
||||
removed: false,
|
||||
openState: 'open',
|
||||
openError: null,
|
||||
hasMore: false,
|
||||
loadingOlder: false,
|
||||
promptError: null,
|
||||
blank: false,
|
||||
lastAgentError: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A ready workspace list with no workspaces (the shape WorkspacesService
|
||||
* projects after both baselines land).
|
||||
* @returns the initial state of the test workspaces store.
|
||||
*/
|
||||
export function workspaceListState(): WorkspaceListState {
|
||||
return {
|
||||
items: [],
|
||||
archivedSessionIds: [],
|
||||
state: 'idle',
|
||||
phase: 'ready',
|
||||
error: null,
|
||||
baselinesReady: true,
|
||||
recentWorkspaceId: undefined,
|
||||
}
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
/**
|
||||
* jsdom slot test runtime: a real small runtime — Cordis `Context`, the
|
||||
* runtime `SlotsService`, and the web-react renderer — assembled around
|
||||
* test-owned session/workspace doubles, so feature specs exercise
|
||||
* declaration, registration, scope, store, inject, rendering, updates, and
|
||||
* disposal without hand-building the machinery per suite.
|
||||
*
|
||||
* Not part of the product plugin graph (no `dsh.client`); feature packages
|
||||
* depend on it in devDependencies only. It copies no SlotCore/renderer/store
|
||||
* machinery — everything mounts the production implementations.
|
||||
* @module @deepseek-ai/dsh-client-test-runtime
|
||||
*/
|
||||
/* oxlint-disable typescript/no-redundant-type-constituents --
|
||||
* `keyof SlotMap & string` is the declare-merge key pattern (see ui-slots):
|
||||
* this compilation unit sees only the runtime's 'root' row, but consumer
|
||||
* programs merge their own keys in; the rule fires on the narrow-map view. */
|
||||
import { Context, Inject } from '@deepseek-ai/cordis'
|
||||
import type { Fiber, Plugin } from '@deepseek-ai/cordis'
|
||||
import { createElement, Fragment, useSyncExternalStore } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { act, render, within } from '@testing-library/react'
|
||||
import type { RenderResult } from '@testing-library/react'
|
||||
import type { queries } from '@testing-library/dom'
|
||||
import type { BoundFunctions } from '@testing-library/dom'
|
||||
import {
|
||||
ConversationEventRegistry, ConversationViewRegistry, SlotsService,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { createSlotRenderer } from '@deepseek-ai/dsh-client-web-react'
|
||||
import type {
|
||||
ChildrenDecl, ComposedProps, OwnerOf, SlotComponent, SlotMap, SlotRendererHost, StoreInstanceLike,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { registerDomSnapshotSerializer } from './snapshot.ts'
|
||||
import { TestSessions } from './sessions.ts'
|
||||
import { TestWorkspaces } from './workspaces.ts'
|
||||
import type { Stabilizer } from './fixtures.ts'
|
||||
|
||||
export { domSnapshotSerializer, registerDomSnapshotSerializer } from './snapshot.ts'
|
||||
export { FixtureSession, TestSessions } from './sessions.ts'
|
||||
export { stubSettingsScope } from './settings-scope.ts'
|
||||
export type { StubSettingsScope } from './settings-scope.ts'
|
||||
export { TestWorkspaces } from './workspaces.ts'
|
||||
export { TestRemote } from './remote.ts'
|
||||
export { conversationSnapshot, workspaceListState } from './fixtures.ts'
|
||||
export type { SessionBehaviorOverrides, SessionFixture, Stabilizer } from './fixtures.ts'
|
||||
export { makeTranslate } from './translate.ts'
|
||||
export { usePinnedBrowserLanguages } from './locale-env.ts'
|
||||
|
||||
/** Erased register face for the internal root call (the public declaration contract holds the typing). */
|
||||
type ErasedRegister = (options: object, component: unknown) => () => void
|
||||
|
||||
/**
|
||||
* One rendered slot's local view, from {@link SlotTestRuntime.renderSlot}:
|
||||
* the `data-slot` wrapper is the snapshot root (`expect(view.container)
|
||||
* .toMatchSnapshot()` captures exactly this slot's output), Testing Library
|
||||
* queries are bound inside it, and `update` re-renders with new owner props.
|
||||
*/
|
||||
export interface SlotView<K extends keyof SlotMap & string> {
|
||||
/** The `<div data-slot="<key>">` wrapper around the slot's rendered output. */
|
||||
readonly container: HTMLElement
|
||||
/** Testing Library queries scoped to {@link SlotView.container}. */
|
||||
readonly view: BoundFunctions<typeof queries>
|
||||
/**
|
||||
* Replace the owner props and flush the re-render (the render-site update:
|
||||
* in production the owner recomputes the share and React re-renders).
|
||||
* @param owner - the next owner props share.
|
||||
*/
|
||||
update(owner: OwnerOf<K>): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounted feature plugin handle: the live fiber plus an act-wrapped,
|
||||
* idempotent dispose (unload cascade: entries, declared child slots, store
|
||||
* instances, and provided services all fall together).
|
||||
*/
|
||||
export interface FeatureHandle {
|
||||
/** The plugin's live Cordis fiber (state assertions, escape hatch). */
|
||||
readonly fiber: Fiber
|
||||
/**
|
||||
* Dispose the plugin fiber inside React act; repeated calls no-op.
|
||||
* @returns completion of the unload cascade.
|
||||
*/
|
||||
dispose(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner-props cell behind the auto frame: one external store the frame
|
||||
* subscribes to, so {@link SlotTestRuntime.renderSlot} and
|
||||
* {@link SlotView.update} drive React through the standard uSES boundary.
|
||||
*/
|
||||
class OwnerPropsCell {
|
||||
private readonly owners = new Map<string, object>()
|
||||
private readonly listeners = new Set<() => void>()
|
||||
private version = 0
|
||||
|
||||
/** Snapshot version for uSES pairing (bumped on every set). */
|
||||
readonly getVersion = (): number => this.version
|
||||
|
||||
/**
|
||||
* Subscribe to owner-props changes.
|
||||
* @param fn - change callback.
|
||||
* @returns unsubscribe.
|
||||
*/
|
||||
readonly subscribe = (fn: () => void): (() => void) => {
|
||||
this.listeners.add(fn)
|
||||
return () => { this.listeners.delete(fn) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Install or replace one key's owner props and notify (synchronous; the
|
||||
* caller wraps in act).
|
||||
* @param key - slot key.
|
||||
* @param owner - owner props share.
|
||||
*/
|
||||
set(key: string, owner: object): void {
|
||||
this.owners.set(key, owner)
|
||||
this.version += 1
|
||||
for (const fn of [...this.listeners]) fn()
|
||||
}
|
||||
|
||||
/** Keys with supplied owner props, in first-supply order. */
|
||||
entries(): readonly (readonly [string, object])[] {
|
||||
return [...this.owners.entries()]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The test-owned 'root' occupant: declares the child slots a suite needs
|
||||
* through the REAL `slots.register`, with a caller-supplied minimal frame —
|
||||
* the runtime never guesses a feature's page structure.
|
||||
*/
|
||||
export class TestRoot {
|
||||
private disposeEntry: (() => void) | undefined
|
||||
|
||||
/**
|
||||
* @param slots - the runtime SlotsService.
|
||||
* @param stabilize - the owning runtime's act wrapper.
|
||||
*/
|
||||
constructor(private readonly slots: SlotsService, private readonly stabilize: Stabilizer) {}
|
||||
|
||||
/**
|
||||
* Register the root frame, declaring (and thereby claiming) the child
|
||||
* slots. One declaration per runtime — a second call fails loud in the
|
||||
* core ('root' is a single slot).
|
||||
* @param children - child-slot declaration table (declaration + render authorization + runtime spec).
|
||||
* @param frame - minimal frame component; its props derive from the declared keys (composed-props contract).
|
||||
* @returns completion of the act-wrapped registration.
|
||||
*/
|
||||
async declare<const D extends ChildrenDecl>(
|
||||
children: D,
|
||||
frame: SlotComponent<ComposedProps<'root', never, keyof NoInfer<D> & keyof SlotMap & string, undefined, object>>,
|
||||
): Promise<void> {
|
||||
await this.stabilize(() => {
|
||||
// Erased hop (same pattern as SlotsService's own implementation arm);
|
||||
// the declaration signature above is the typed contract.
|
||||
this.disposeEntry = (this.slots.register as unknown as ErasedRegister)({ name: 'root', children }, frame)
|
||||
})
|
||||
}
|
||||
|
||||
/** Remove the root registration and collapse its declarations (runtime dispose path). */
|
||||
release(): void {
|
||||
this.disposeEntry?.()
|
||||
this.disposeEntry = undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assembled test runtime. Obtain via {@link SlotTestRuntime.create};
|
||||
* dispose with {@link SlotTestRuntime.dispose} (afterEach). Public mutators
|
||||
* are act-wrapped throughout — tests never handle SlotCore microtask
|
||||
* batching or React act themselves.
|
||||
*/
|
||||
export class SlotTestRuntime {
|
||||
/** The runtime's Cordis root (escape hatch: extra services via `ctx.provide`, raw `ctx.plugin` mounts). */
|
||||
readonly ctx: Context
|
||||
/** The production SlotsService mounted on {@link SlotTestRuntime.ctx}. */
|
||||
readonly slots: SlotsService
|
||||
/** The test-owned 'root' occupant. */
|
||||
readonly root: TestRoot
|
||||
/** Sessions double (list/current observable, cells, scopes, behavior faces). */
|
||||
readonly sessions: TestSessions
|
||||
/** Workspaces double (list observable, recorded intent actions). */
|
||||
readonly workspaces: TestWorkspaces
|
||||
|
||||
private readonly stabilizer: Stabilizer = async (fn) => {
|
||||
await act(async () => { await fn() })
|
||||
}
|
||||
|
||||
private host: SlotRendererHost | undefined
|
||||
private readonly views: RenderResult[] = []
|
||||
private readonly handles: FeatureHandle[] = []
|
||||
private disposed = false
|
||||
/** Auto-frame state ({@link SlotTestRuntime.declare} / {@link SlotTestRuntime.renderSlot}). */
|
||||
private readonly ownerCell = new OwnerPropsCell()
|
||||
private readonly autoDeclared = new Set<string>()
|
||||
private autoRootView: RenderResult | undefined
|
||||
|
||||
private constructor(ctx: Context, slots: SlotsService) {
|
||||
this.ctx = ctx
|
||||
this.slots = slots
|
||||
this.root = new TestRoot(slots, this.stabilizer)
|
||||
this.sessions = new TestSessions(this.stabilizer, ctx)
|
||||
this.workspaces = new TestWorkspaces(this.stabilizer)
|
||||
ctx.provide('sessions', this.sessions)
|
||||
ctx.provide('workspaces', this.workspaces)
|
||||
// Capturing install: the production renderer does the rendering; the
|
||||
// wrapper only takes the host face for storeOf (no machinery copied).
|
||||
const renderer = createSlotRenderer()
|
||||
slots.install({
|
||||
renderRoot: (host, ownerProps) => {
|
||||
this.host = host
|
||||
return renderer.renderRoot(host, ownerProps)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble a runtime: real Context, mounted SlotsService, installed
|
||||
* renderer, and the session/workspace doubles provided as services.
|
||||
* @returns the ready runtime.
|
||||
*/
|
||||
static async create(): Promise<SlotTestRuntime> {
|
||||
registerDomSnapshotSerializer()
|
||||
const ctx = new Context()
|
||||
const fiber = ctx.plugin(SlotsService)
|
||||
await fiber.await()
|
||||
await ctx.plugin(ConversationEventRegistry).await()
|
||||
await ctx.plugin(ConversationViewRegistry).await()
|
||||
return new SlotTestRuntime(ctx, ctx.get('slots') as SlotsService)
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide an extra service the feature under test injects (e.g. a layout
|
||||
* fake). Sugar over `ctx.provide`, typed against the Context declaration
|
||||
* merge: for a declared service name the fake must be a subset of that
|
||||
* service's outward face (Partial — supply only what the feature calls),
|
||||
* so a production face change breaks the fake at compile time. Undeclared
|
||||
* names stay unchecked (ad-hoc test services).
|
||||
* @param name - service name.
|
||||
* @param value - service implementation (test double).
|
||||
*/
|
||||
provide<K extends string>(name: K, value: K extends keyof Context ? Partial<Context[K]> : unknown): void {
|
||||
this.ctx.provide(name, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount a feature plugin on a real fiber. Required services are prechecked
|
||||
* 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).
|
||||
* @returns handle owning the fiber's explicit disposal.
|
||||
*/
|
||||
async mount(plugin: Plugin): Promise<FeatureHandle> {
|
||||
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)
|
||||
await this.stabilizer(async () => {
|
||||
await fiber.await()
|
||||
})
|
||||
let disposed = false
|
||||
const handle: FeatureHandle = {
|
||||
fiber,
|
||||
dispose: async () => {
|
||||
if (disposed) return
|
||||
disposed = true
|
||||
await this.stabilizer(() => fiber.dispose())
|
||||
},
|
||||
}
|
||||
this.handles.push(handle)
|
||||
return handle
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the root slot tree through the ctx-level entry (the shell's own
|
||||
* entry point): `ctx.slots.renderSlot('root', {})` under Testing Library.
|
||||
* @returns the Testing Library view.
|
||||
*/
|
||||
renderRoot(): RenderResult {
|
||||
const view = render(createElement(Fragment, null, this.slots.renderSlot('root', {})))
|
||||
this.views.push(view)
|
||||
return view
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare child slots under an auto-generated root frame — the single-slot
|
||||
* mounting path for local DOM snapshots. Each key later supplied through
|
||||
* {@link SlotTestRuntime.renderSlot} renders inside its own
|
||||
* `<div data-slot="<key>">` wrapper (the snapshot root). Mutually exclusive
|
||||
* with {@link TestRoot.declare} ('root' is a single slot); one call per
|
||||
* runtime.
|
||||
* @param children - child-slot declaration table (same contract as TestRoot.declare).
|
||||
* @returns completion of the act-wrapped registration.
|
||||
*/
|
||||
async declare(children: ChildrenDecl): Promise<void> {
|
||||
for (const key of Object.keys(children)) this.autoDeclared.add(key)
|
||||
const cell = this.ownerCell
|
||||
const AutoFrame = (props: { renderSlot: (key: string, owner: object) => ReactNode }) => {
|
||||
useSyncExternalStore(cell.subscribe, cell.getVersion)
|
||||
return createElement(Fragment, null, cell.entries().map(([key, owner]) =>
|
||||
createElement('div', { 'data-slot': key, key }, props.renderSlot(key, owner))))
|
||||
}
|
||||
await this.root.declare(children as never, AutoFrame as never)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one declared slot with its owner props and return the local view.
|
||||
* The whole root tree mounts through the production assembly path
|
||||
* (renderer, scope providers, store axis); only this key's output lands in
|
||||
* the returned container. Call again with another key to view a sibling
|
||||
* slot of the same tree.
|
||||
* @param key - a key declared through {@link SlotTestRuntime.declare}.
|
||||
* @param owner - owner props share for the render site.
|
||||
* @returns the slot-local view (snapshot container, scoped queries, owner updates).
|
||||
*/
|
||||
renderSlot<K extends keyof SlotMap & string>(key: K, owner: OwnerOf<K>): SlotView<K> {
|
||||
if (!this.autoDeclared.has(key)) {
|
||||
throw new Error(`renderSlot('${key}') without declare() — declare the key first (or use root.declare for a custom frame)`)
|
||||
}
|
||||
const install = (next: object): void => {
|
||||
// Synchronous cell write inside act: the frame re-renders through uSES.
|
||||
act(() => {
|
||||
this.ownerCell.set(key, next)
|
||||
})
|
||||
}
|
||||
install(owner)
|
||||
this.autoRootView ??= this.renderRoot()
|
||||
const container = this.autoRootView.container.querySelector(`[data-slot="${key}"]`)
|
||||
if (!(container instanceof HTMLElement)) {
|
||||
throw new Error(`renderSlot('${key}'): the auto frame rendered no wrapper — was the runtime already disposed?`)
|
||||
}
|
||||
return { container, view: within(container), update: install }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the store instance the renderer would hand a slot's component
|
||||
* (identity assertions, action-driven writes). Requires a prior
|
||||
* {@link SlotTestRuntime.renderRoot} — the host face exists only inside the
|
||||
* installed renderer, exactly as in production.
|
||||
* @param key - slot key whose first entry declares the store.
|
||||
* @param scopeKey - session id for session-scope slots; omit for root scope.
|
||||
* @returns the live store instance.
|
||||
*/
|
||||
storeOf(key: keyof SlotMap & string, scopeKey?: string): StoreInstanceLike {
|
||||
if (this.host === undefined) {
|
||||
throw new Error('storeOf before renderRoot() — the host face exists only inside the installed renderer')
|
||||
}
|
||||
const entry = this.host.entriesOf(key)[0]
|
||||
if (entry === undefined) throw new Error(`storeOf('${key}'): no registration on the ledger`)
|
||||
const instance = this.host.storeOf(entry, scopeKey)
|
||||
if (instance === undefined) throw new Error(`storeOf('${key}'): the entry declares no store`)
|
||||
return instance
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush pending ledger/store notifications inside act — for mutations made
|
||||
* outside the runtime's own methods (e.g. a direct `slots.register`).
|
||||
* @returns completion of the act pass.
|
||||
*/
|
||||
async flush(): Promise<void> {
|
||||
await this.stabilizer(() => {})
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear down: unmount React trees first, then dispose feature fibers, the
|
||||
* root registration, minted session scopes, and persisted test state.
|
||||
* Idempotent.
|
||||
* @returns completion of the teardown.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) return
|
||||
this.disposed = true
|
||||
this.autoRootView = undefined
|
||||
for (const view of this.views.splice(0)) view.unmount()
|
||||
for (const handle of this.handles.splice(0)) await handle.dispose()
|
||||
this.root.release()
|
||||
await this.sessions.disposeScopes()
|
||||
localStorage.clear()
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-client-test-runtime`.
|
||||
* @module @deepseek-ai/dsh-client-test-runtime/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-client-test-runtime'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'client-test-runtime-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this test-support package owns no production event
|
||||
* stream or mutable data — it assembles the runtime SlotsService and renderer
|
||||
* (whose packages own their invariants) around test doubles; its own behavior
|
||||
* is exercised by its package tests.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* Browser-language pin for specs that assert localized copy. A fresh
|
||||
* LocaleService with no stored preference opens in the language `navigator`
|
||||
* asks for, and jsdom reports the runner's own (`en-US`) — so a spec asserting
|
||||
* the product's Chinese copy states the browser it assumes instead of
|
||||
* inheriting the machine's.
|
||||
*/
|
||||
import { afterEach, beforeEach } from 'vitest'
|
||||
|
||||
/**
|
||||
* Pin `navigator.languages`/`navigator.language` for every test in the
|
||||
* calling file (or describe block), restoring the environment's own values
|
||||
* afterwards. Call at suite level, like the other vitest hooks.
|
||||
* @param primary - most preferred BCP 47 tag; also becomes `navigator.language`.
|
||||
* @param rest - further tags in preference order.
|
||||
*/
|
||||
export function usePinnedBrowserLanguages(primary: string, ...rest: string[]): void {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(navigator, 'languages', { value: [primary, ...rest], configurable: true })
|
||||
Object.defineProperty(navigator, 'language', { value: primary, configurable: true })
|
||||
})
|
||||
afterEach(() => {
|
||||
// Deleting the own properties uncovers the environment's own accessors
|
||||
// again (Navigator declares both readonly, hence the erased receiver).
|
||||
const own = navigator as unknown as Record<string, unknown>
|
||||
delete own.languages
|
||||
delete own.language
|
||||
})
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
/** Test-owned Remote face: `$on` subscriptions driven by the internal forwarded-event plumbing. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
|
||||
/**
|
||||
* Remote service test double for the forwarded-event path. Feature specs need
|
||||
* `ctx.remote.$on` to exist (their plugins inject `remote`) and need forwarded
|
||||
* host events to reach those subscribers, but not the generated namespaces or
|
||||
* the wire — so this double implements subscription and dispatch only.
|
||||
*
|
||||
* Dispatch is driven the same way production drives it: `client/runtime` owns the
|
||||
* host frame sink and hands each decoded `host/remote-event` frame to
|
||||
* `$dispatch`. A spec therefore exercises its refresh chains by calling
|
||||
* `$dispatch(name, args)` on this double.
|
||||
*
|
||||
* `$mount` rejects: a spec that reaches a generated namespace through this
|
||||
* double has outgrown it and needs the real Client Remote service.
|
||||
*
|
||||
* One deliberate asymmetry with production: a throwing listener propagates out
|
||||
* of the emit instead of being contained and logged, so a spec cannot lean on
|
||||
* this double for the containment guarantee `$on` documents — assert that
|
||||
* against the real service.
|
||||
*/
|
||||
export class TestRemote {
|
||||
private readonly subscriptions = new Map<string, Set<(...args: never[]) => void>>()
|
||||
|
||||
/**
|
||||
* Register the double as `ctx.remote`.
|
||||
* @param ctx - the spec's root Context.
|
||||
*/
|
||||
constructor(ctx: Context) {
|
||||
ctx.provide('remote', this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliver one forwarded host event to its subscribers, standing in for the
|
||||
* carrier that owns the frame sink.
|
||||
* @param event - forwarded host event name.
|
||||
* @param args - the Host argument list, verbatim.
|
||||
*/
|
||||
$dispatch(event: string, args: readonly unknown[]): void {
|
||||
const listeners = this.subscriptions.get(event)
|
||||
if (listeners === undefined) return
|
||||
for (const listener of [...listeners]) listener(...args as never[])
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to one forwarded host event.
|
||||
* @param event - forwarded host event name.
|
||||
* @param listener - receives the Host argument list verbatim.
|
||||
* @returns disposer removing this subscription.
|
||||
*/
|
||||
$on(event: string, listener: (...args: never[]) => void): () => void {
|
||||
const listeners = this.subscriptions.get(event) ?? new Set()
|
||||
this.subscriptions.set(event, listeners)
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Generated-namespace mount, unsupported by this double.
|
||||
* @returns never; always rejects.
|
||||
*/
|
||||
$mount(): Promise<() => Promise<void>> {
|
||||
return Promise.reject(new Error('TestRemote: $mount needs the real Client Remote service'))
|
||||
}
|
||||
}
|
||||
@@ -1,526 +0,0 @@
|
||||
/** Test-owned sessions face: the SlotsService host contract over declarative fixtures. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { AttachmentIdType } from '@deepseek-ai/dsh-attachment'
|
||||
import { createScope, scopeOf, SessionProvideChannel } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type {
|
||||
AgentContext, ConversationSnapshot, ISessions, ObservableSnapshot, ProjectionsFace, SessionFace, SessionId,
|
||||
SessionListState, SessionProvideDescriptor, SessionSearchResultItem, SessionSummary, SnapshotStore,
|
||||
SubagentAddress,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
// The double reports the wire schema's own search bound, like the production
|
||||
// service — a transport-varying limit would be a fiction no client can see.
|
||||
import { SESSION_SEARCH_RESULT_LIMIT } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import type { HostObservable, SessionMaybeProvideInfo, SessionProvideInfo } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { conversationSnapshot } from './fixtures.ts'
|
||||
import type { SessionFixture, Stabilizer } from './fixtures.ts'
|
||||
|
||||
/**
|
||||
* The fixture-backed session face: conversation reads delegate to the
|
||||
* fixture's snapshot store; ISession verbs are fail-loud stubs unless the
|
||||
* fixture supplies them (the runtime never fakes behavior a test did not
|
||||
* declare — an unstubbed call names itself instead of half-working). Extra
|
||||
* fixture methods are grafted verbatim for feature-side casts.
|
||||
*/
|
||||
export class FixtureSession implements SessionFace {
|
||||
/**
|
||||
* The useProjection seat: identity-stable per-key faces over the fixture's
|
||||
* projection values (set via {@link TestSessions.setProjection}).
|
||||
*/
|
||||
readonly projections: ProjectionsFace & { set(key: string, value: unknown): void }
|
||||
|
||||
/**
|
||||
* @param sessionId - host identity (branded view of the fixture id).
|
||||
* @param store - conversation snapshot store (updateSnapshot writes it).
|
||||
* @param overrides - fixture-declared behavior face, grafted over the stubs.
|
||||
*/
|
||||
constructor(
|
||||
readonly sessionId: SessionId,
|
||||
private readonly store: SnapshotStore<ConversationSnapshot>,
|
||||
overrides: Record<string, unknown>,
|
||||
) {
|
||||
const values = new Map<string, unknown>()
|
||||
const listeners = new Map<string, Set<() => void>>()
|
||||
const faces = new Map<string, ObservableSnapshot<unknown>>()
|
||||
this.projections = {
|
||||
faceOf: (key: string) => {
|
||||
let face = faces.get(key)
|
||||
if (face === undefined) {
|
||||
face = {
|
||||
getSnapshot: () => values.get(key),
|
||||
subscribe: (fn: () => void) => {
|
||||
const set = listeners.get(key) ?? new Set()
|
||||
set.add(fn)
|
||||
listeners.set(key, set)
|
||||
return () => { set.delete(fn) }
|
||||
},
|
||||
}
|
||||
faces.set(key, face)
|
||||
}
|
||||
return face
|
||||
},
|
||||
set: (key: string, value: unknown) => {
|
||||
values.set(key, value)
|
||||
for (const fn of [...(listeners.get(key) ?? [])]) fn()
|
||||
},
|
||||
}
|
||||
Object.assign(this, overrides)
|
||||
}
|
||||
|
||||
/** @returns the fixture conversation snapshot (useSession read side). */
|
||||
getSnapshot(): ConversationSnapshot {
|
||||
return this.store.getSnapshot()
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to fixture snapshot changes.
|
||||
* @param fn - change callback.
|
||||
* @returns unsubscribe.
|
||||
*/
|
||||
subscribe(fn: () => void): () => void {
|
||||
return this.store.subscribe(fn)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `prompt` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
prompt(): never {
|
||||
throw new Error(`test session "${this.sessionId}": prompt is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `readAttachment` on the fixture's session face to exercise it.
|
||||
* @param _attachmentId - opaque durable attachment id.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
readAttachment(_attachmentId: AttachmentIdType): never {
|
||||
throw new Error(`test session "${this.sessionId}": readAttachment is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `updateQueue` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
updateQueue(): never {
|
||||
throw new Error(`test session "${this.sessionId}": updateQueue is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `cancel` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
cancel(): never {
|
||||
throw new Error(`test session "${this.sessionId}": cancel is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `command` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
command(): never {
|
||||
throw new Error(`test session "${this.sessionId}": command is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `loadOlder` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
loadOlder(): never {
|
||||
throw new Error(`test session "${this.sessionId}": loadOlder is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail-loud stub; supply `rename` on the fixture's session face to exercise it.
|
||||
* @returns never — always throws.
|
||||
*/
|
||||
rename(): never {
|
||||
throw new Error(`test session "${this.sessionId}": rename is not stubbed — supply it on the fixture's session face`)
|
||||
}
|
||||
}
|
||||
|
||||
/** One live test session: fixture-derived stores plus its minted scope state. */
|
||||
interface SessionRecord {
|
||||
summary: SessionSummary
|
||||
snapshot: SnapshotStore<ConversationSnapshot>
|
||||
session: FixtureSession
|
||||
scope: AgentContext | undefined
|
||||
scopeFiber: { dispose(): Promise<void> } | undefined
|
||||
/** Materialized standard-props bundle (identity-stable per session; invalidated on roster change). */
|
||||
provideInfo: SessionProvideInfo | undefined
|
||||
}
|
||||
|
||||
/** Test binding shape handed to provider resolvers and feature injects (a SessionBinding whose session is the fixture face). */
|
||||
export interface TestSessionBinding {
|
||||
readonly sessionId: SessionId
|
||||
readonly session: FixtureSession
|
||||
readonly ctx: AgentContext
|
||||
}
|
||||
|
||||
/**
|
||||
* Sessions test double behind the renderer host and feature injects: owns the
|
||||
* list/current observable, the standard-props provide channel (the runtime's
|
||||
* `useSession` contribution included), scope minting through the production
|
||||
* `createScope`, and the session behavior face supplied per fixture.
|
||||
*
|
||||
* Implements the same ISessions face features receive as `ctx.sessions`, so
|
||||
* a production face change breaks this double at compile time; the extra
|
||||
* members (add/updateSnapshot/setCurrent/remove/behavior/calls/stubSearch and
|
||||
* the legacy provideInfo/maybeProvideInfo lookups) are bench-only surface.
|
||||
*/
|
||||
export class TestSessions implements ISessions {
|
||||
/** The useSessions standard feed (list rows + current selection). */
|
||||
readonly list: SnapshotStore<SessionListState>
|
||||
/**
|
||||
* Atomic current-session provide projection (production SessionsService
|
||||
* mirror): selection changes and provider-roster changes publish through
|
||||
* this one source — the member the SlotsService host face hands the
|
||||
* renderer's SessionProvider.
|
||||
*/
|
||||
readonly currentProvideInfo: HostObservable<SessionMaybeProvideInfo>
|
||||
private readonly records = new Map<SessionId, SessionRecord>()
|
||||
/** The production provide channel (roster, materialization rules, current projection) — no test-side mirror. */
|
||||
private readonly channel: SessionProvideChannel
|
||||
|
||||
/** Calls observed on the service-level face, newest last. */
|
||||
readonly calls: {
|
||||
method: 'open' | 'openSubagent' | 'setSubagentCatalogOpen' | 'refreshSubagents'
|
||||
| 'clear' | 'search' | 'fork'
|
||||
args: unknown[]
|
||||
}[] = []
|
||||
|
||||
/** The wire schema's `session.search` result bound (production parity). */
|
||||
readonly searchResultLimit = SESSION_SEARCH_RESULT_LIMIT
|
||||
|
||||
/** Replaceable search behavior (see {@link TestSessions.stubSearch}). */
|
||||
private searchStub: ((query: string, signal: AbortSignal) => { items: SessionSearchResultItem[]; hasMore: boolean }) | undefined
|
||||
|
||||
/**
|
||||
* @param stabilize - the owning runtime's act wrapper.
|
||||
* @param rootCtx - the runtime's Cordis root; scope fibers mount under it.
|
||||
*/
|
||||
constructor(private readonly stabilize: Stabilizer, private readonly rootCtx: Context) {
|
||||
this.list = createSnapshotStore<SessionListState>({
|
||||
ids: [], byId: {}, current: undefined, phase: 'ready',
|
||||
subagentsByParent: {}, tasksBySession: {}, currentAddress: undefined,
|
||||
})
|
||||
this.channel = new SessionProvideChannel({
|
||||
rebuildBundles: () => {
|
||||
for (const record of this.records.values()) {
|
||||
if (record.provideInfo !== undefined) {
|
||||
record.provideInfo = this.channel.materializeInfo(this.bindingOf(record.session.sessionId, record))
|
||||
}
|
||||
}
|
||||
},
|
||||
resolveCurrent: () => this.maybeProvideInfo(this.list.getSnapshot().current),
|
||||
})
|
||||
this.currentProvideInfo = this.channel.currentProvideInfo
|
||||
// The projection follows every current write, as in production.
|
||||
this.list.subscribe(() => { this.channel.publishCurrent() })
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a session from a fixture and (by default) make it current.
|
||||
* @param fixture - identity + snapshot/summary overrides + behavior face.
|
||||
* @param opts - pass `current: false` to add without selecting.
|
||||
* @returns the stable session id (branded view of `fixture.id`).
|
||||
*/
|
||||
async add(fixture: SessionFixture, opts?: { current?: boolean }): Promise<SessionId> {
|
||||
const id = fixture.id as SessionId
|
||||
if (this.records.has(id)) throw new Error(`test session "${id}" already added`)
|
||||
const summary: SessionSummary = {
|
||||
id,
|
||||
displayTitle: fixture.id,
|
||||
running: false,
|
||||
blank: false,
|
||||
updatedAt: this.records.size + 1,
|
||||
...fixture.summary,
|
||||
}
|
||||
const snapshot = createSnapshotStore<ConversationSnapshot>({
|
||||
...conversationSnapshot(id),
|
||||
...fixture.snapshot,
|
||||
})
|
||||
this.records.set(id, {
|
||||
summary,
|
||||
snapshot,
|
||||
session: new FixtureSession(id, snapshot, fixture.session ?? {}),
|
||||
scope: undefined,
|
||||
scopeFiber: undefined,
|
||||
provideInfo: undefined,
|
||||
})
|
||||
await this.stabilize(() => {
|
||||
this.list.update((draft) => {
|
||||
draft.ids.push(id)
|
||||
draft.byId[id] = summary
|
||||
if (opts?.current !== false) draft.current = id
|
||||
})
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a session's conversation snapshot through an immer draft (the
|
||||
* live-stream stand-in: components subscribed via useSession re-render).
|
||||
* @param id - session id.
|
||||
* @param mutate - draft mutator.
|
||||
*/
|
||||
async updateSnapshot(id: string, mutate: (draft: ConversationSnapshot) => void): Promise<void> {
|
||||
const record = this.require(id)
|
||||
await this.stabilize(() => { record.snapshot.update(mutate) })
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a session's list row (the wire-echo stand-in: title settles,
|
||||
* running flips — components subscribed via useSessions re-render).
|
||||
* @param id - session id.
|
||||
* @param patch - summary fields to merge over the row.
|
||||
*/
|
||||
async updateSummary(id: string, patch: Partial<Omit<SessionSummary, 'id'>>): Promise<void> {
|
||||
const record = this.require(id)
|
||||
record.summary = { ...record.summary, ...patch }
|
||||
await this.stabilize(() => {
|
||||
this.list.update((draft) => { draft.byId[id as SessionId] = record.summary })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the current selection (undefined = the no-session empty state).
|
||||
* @param id - session id to select, or undefined to clear.
|
||||
*/
|
||||
async setCurrent(id: string | undefined): Promise<void> {
|
||||
if (id !== undefined) this.require(id)
|
||||
await this.stabilize(() => {
|
||||
this.list.update((draft) => { draft.current = id as SessionId | undefined })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a session: list row, scope fiber, and per-session store instances
|
||||
* (with persisted state) die together — the same single lifecycle axis the
|
||||
* production SessionsService drives on session death, minus staging.
|
||||
* @param id - session id.
|
||||
*/
|
||||
async remove(id: string): Promise<void> {
|
||||
const record = this.require(id)
|
||||
this.records.delete(id as SessionId)
|
||||
await this.stabilize(async () => {
|
||||
this.list.update((draft) => {
|
||||
draft.ids = draft.ids.filter(existing => existing !== id)
|
||||
const { [id as SessionId]: _dead, ...rest } = draft.byId
|
||||
draft.byId = rest
|
||||
if (draft.current === id) draft.current = undefined
|
||||
})
|
||||
if (record.scopeFiber !== undefined) await record.scopeFiber.dispose()
|
||||
this.rootCtx.get('slots')?.pruneStoreScope(id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a per-session standard-props provider (production `provide`
|
||||
* contract: hooks become `use<Name>` selector hooks on the render side,
|
||||
* props spread verbatim; duplicate names fail loud at materialization).
|
||||
* @param descriptor - static member roster plus per-session resolver.
|
||||
* @returns disposer removing the provider.
|
||||
*/
|
||||
provide(descriptor: SessionProvideDescriptor): () => void {
|
||||
return this.channel.provide(descriptor)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the definite per-session standard-props bundle (host face member).
|
||||
* @param id - session id.
|
||||
* @returns the identity-stable bundle, or undefined for unknown sessions.
|
||||
*/
|
||||
provideInfo(id: string): SessionProvideInfo | undefined {
|
||||
const record = this.records.get(id as SessionId)
|
||||
if (record === undefined) return undefined
|
||||
record.provideInfo ??= this.channel.materializeInfo(this.bindingOf(id as SessionId, record))
|
||||
return record.provideInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current-session-optional standard kit (host face member):
|
||||
* unknown or absent ids return the static no-session projection.
|
||||
* @param id - current session id, when selected.
|
||||
* @returns a definite or no-session provide bundle.
|
||||
*/
|
||||
maybeProvideInfo(id: string | undefined): SessionMaybeProvideInfo {
|
||||
return (id === undefined ? undefined : this.provideInfo(id)) ?? this.channel.maybeInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve (mint on first touch) the session-scoped Cordis context through
|
||||
* the production `createScope`, so real `scopeOf`/scope-addressed services
|
||||
* resolve it.
|
||||
* @param id - session id.
|
||||
* @returns the scoped context, or undefined for unknown sessions.
|
||||
*/
|
||||
scope(id: string): AgentContext | undefined {
|
||||
const record = this.records.get(id as SessionId)
|
||||
if (record === undefined) return undefined
|
||||
if (record.scope === undefined) {
|
||||
const handle = createScope(this.rootCtx, id as SessionId)
|
||||
record.scope = handle.ctx
|
||||
record.scopeFiber = handle.fiber
|
||||
}
|
||||
return record.scope
|
||||
}
|
||||
|
||||
/**
|
||||
* Session assembly binding (inject factories and provide resolvers receive it).
|
||||
* @param id - session id.
|
||||
* @returns sessionId + behavior face + scoped ctx, or undefined when unknown.
|
||||
*/
|
||||
binding(id: string): TestSessionBinding | undefined {
|
||||
const record = this.records.get(id as SessionId)
|
||||
if (record === undefined) return undefined
|
||||
return this.bindingOf(id as SessionId, record)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the session scope tag off a context (service-method boundary mirror).
|
||||
* @param ctx - any client context.
|
||||
* @returns the session id, or undefined on root contexts.
|
||||
*/
|
||||
scopeOf(ctx: Context): SessionId | undefined {
|
||||
return scopeOf(ctx)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the scoped session face off a context (production `sessionOf`
|
||||
* mirror).
|
||||
* @param ctx - any client context.
|
||||
* @returns the fixture session face, or undefined off-scope.
|
||||
*/
|
||||
sessionOf(ctx: Context): SessionFace | undefined {
|
||||
const id = scopeOf(ctx)
|
||||
if (id === undefined) return undefined
|
||||
return this.records.get(id)?.session
|
||||
}
|
||||
|
||||
/**
|
||||
* Service-level selection call (recorded, then applied to the list store
|
||||
* synchronously — inject callbacks call this outside any act window; the
|
||||
* store notify is microtask-batched so the next stabilized step observes it).
|
||||
* @param id - session id.
|
||||
*/
|
||||
open(id: SessionId): void {
|
||||
this.calls.push({ method: 'open', args: [id] })
|
||||
this.require(id)
|
||||
this.list.update((draft) => {
|
||||
draft.current = id
|
||||
draft.currentAddress = undefined
|
||||
})
|
||||
}
|
||||
|
||||
/** Open an existing fixture through its catalog address. */
|
||||
openSubagent(address: SubagentAddress): void {
|
||||
this.calls.push({ method: 'openSubagent', args: [address] })
|
||||
this.require(address.childSessionId)
|
||||
this.list.update((draft) => {
|
||||
draft.current = address.childSessionId
|
||||
draft.currentAddress = address
|
||||
})
|
||||
}
|
||||
|
||||
/** Resolve the current fixture's retained catalog address. */
|
||||
subagentAddress(id: SessionId): SubagentAddress | undefined {
|
||||
const address = this.list.getSnapshot().currentAddress
|
||||
return address?.childSessionId === id ? address : undefined
|
||||
}
|
||||
|
||||
/** Record catalog consumption; fixture callers drive snapshots explicitly. */
|
||||
setSubagentCatalogOpen(parentSessionId: SessionId, open: boolean): void {
|
||||
this.calls.push({ method: 'setSubagentCatalogOpen', args: [parentSessionId, open] })
|
||||
}
|
||||
|
||||
/** Record a catalog refresh; fixture callers drive snapshots explicitly. */
|
||||
refreshSubagents(parentSessionId: SessionId): Promise<void> {
|
||||
this.calls.push({ method: 'refreshSubagents', args: [parentSessionId] })
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
/** Apply a confirmed preset switch into the fixture list, as production does. */
|
||||
noteAgentPreset(sessionId: SessionId, agentPreset: string): void {
|
||||
this.list.update((draft) => {
|
||||
const summary = draft.byId[sessionId]
|
||||
if (summary !== undefined) draft.byId[sessionId] = { ...summary, agentPreset }
|
||||
})
|
||||
}
|
||||
|
||||
/** Clear the current selection (recorded; the production no-session flow). */
|
||||
clear(): void {
|
||||
this.calls.push({ method: 'clear', args: [] })
|
||||
this.list.update((draft) => {
|
||||
draft.current = undefined
|
||||
draft.currentAddress = undefined
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the sidebar-search result page (the call is still recorded).
|
||||
* @param impl - hits for a query, as the Host would rank them.
|
||||
*/
|
||||
stubSearch(impl: (query: string, signal: AbortSignal) => { items: SessionSearchResultItem[]; hasMore: boolean }): void {
|
||||
this.searchStub = impl
|
||||
}
|
||||
|
||||
/**
|
||||
* Content search over the fixture corpus (recorded). The default answers an
|
||||
* empty page: content ranking is Host behavior, so a scenario that asserts
|
||||
* hits declares them through {@link TestSessions.stubSearch}.
|
||||
* @param query - non-blank literal phrase.
|
||||
* @param signal - cancellation for a superseded search (recorded and forwarded).
|
||||
* @returns the stubbed or empty result page.
|
||||
*/
|
||||
search(query: string, signal: AbortSignal): ReturnType<ISessions['search']> {
|
||||
this.calls.push({ method: 'search', args: [query, signal] })
|
||||
return Promise.resolve({ ok: true, value: this.searchStub?.(query, signal) ?? { items: [], hasMore: false } })
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded fork stub: no child materializes (benches asserting the full
|
||||
* fork flow drive the production service; this face only proves the call).
|
||||
* @param opts - source session id, optional cut anchor, and client title policy.
|
||||
* @returns the source id (no child record is created).
|
||||
*/
|
||||
fork(opts: { sessionId: SessionId; atSeq?: number; increaseTitle?: boolean }): Promise<SessionId> {
|
||||
this.calls.push({ method: 'fork', args: [opts] })
|
||||
return Promise.resolve(opts.sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* The session face of a fixture (typed view for assertions; fixture
|
||||
* behavior methods are grafted onto it).
|
||||
* @param id - session id.
|
||||
* @returns the FixtureSession the binding and provide channel carry.
|
||||
*/
|
||||
behavior(id: string): FixtureSession {
|
||||
return this.require(id).session
|
||||
}
|
||||
|
||||
/** Dispose minted scope fibers (runtime dispose path). */
|
||||
async disposeScopes(): Promise<void> {
|
||||
for (const record of this.records.values()) {
|
||||
if (record.scopeFiber !== undefined) {
|
||||
await record.scopeFiber.dispose()
|
||||
record.scope = undefined
|
||||
record.scopeFiber = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bindingOf(id: SessionId, record: SessionRecord): TestSessionBinding {
|
||||
const ctx = this.scope(id)
|
||||
/* v8 ignore next 2 -- bindingOf only runs for a live record, whose scope
|
||||
* always resolves; kept so a future caller cannot mint a ctx-less binding. */
|
||||
if (ctx === undefined) throw new Error(`test session "${id}" resolved no scope`)
|
||||
return { sessionId: id, session: record.session, ctx }
|
||||
}
|
||||
|
||||
private require(id: string): SessionRecord {
|
||||
const record = this.records.get(id as SessionId)
|
||||
if (record === undefined) throw new Error(`test session "${id}" is not added`)
|
||||
return record
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/** Test double for the client settings-scope seam. */
|
||||
import { vi } from 'vitest'
|
||||
import type { SettingsScope, SettingsScopeSnapshot } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
|
||||
/** Handle over one stubbed scope: the scope, its write spy, and publication controls. */
|
||||
export interface StubSettingsScope<T> {
|
||||
/** The scope face handed to the service under test. */
|
||||
scope: SettingsScope<T>
|
||||
/** Spy behind `scope.set`; resolves immediately. */
|
||||
set: ReturnType<typeof vi.fn>
|
||||
/** Spy behind `scope.unset`; resolves immediately. */
|
||||
unset: ReturnType<typeof vi.fn>
|
||||
/** @returns how many listeners are currently subscribed (disposal assertions). */
|
||||
listenerCount(): number
|
||||
/**
|
||||
* Replace part of the snapshot and notify subscribers, as a Host
|
||||
* acceptance would.
|
||||
* @param next - snapshot fields to replace.
|
||||
*/
|
||||
publish(next: Partial<SettingsScopeSnapshot<T>>): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an in-memory settings scope for service specs: starts in the host
|
||||
* loading state, records writes, and lets the test publish Host acceptances.
|
||||
* @returns the stub handle.
|
||||
*/
|
||||
export function stubSettingsScope<T>(): StubSettingsScope<T> {
|
||||
let snapshot: SettingsScopeSnapshot<T> = {
|
||||
status: 'loading', value: undefined, base: undefined, user: undefined,
|
||||
revision: undefined, writable: false, mode: 'host',
|
||||
}
|
||||
const listeners = new Set<() => void>()
|
||||
const set = vi.fn(() => Promise.resolve())
|
||||
const unset = vi.fn(() => Promise.resolve())
|
||||
return {
|
||||
scope: {
|
||||
getSnapshot: () => snapshot,
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
},
|
||||
set,
|
||||
unset,
|
||||
},
|
||||
set,
|
||||
unset,
|
||||
listenerCount: () => listeners.size,
|
||||
publish: (next) => {
|
||||
snapshot = { ...snapshot, ...next }
|
||||
for (const listener of [...listeners]) listener()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* DOM snapshot hygiene: a vitest snapshot serializer that keeps `.snap`
|
||||
* files structural. Two normalizations, both on a clone (the live DOM is
|
||||
* untouched, so class/tag queries keep working):
|
||||
*
|
||||
* - CSS-module scoped class names (`_frame_334d2d`, this repo's
|
||||
* `_[local]_[hash]` shape) fold back to their semantic local (`frame`), so
|
||||
* CSS edits do not churn snapshots.
|
||||
* - `<svg>` internals collapse to a `data-content` fingerprint on the svg
|
||||
* element: path geometry is print noise, but the fingerprint still flips
|
||||
* when an icon's artwork actually changes.
|
||||
*/
|
||||
import { expect } from 'vitest'
|
||||
import type { SnapshotSerializer } from 'vitest'
|
||||
|
||||
/** One scoped class token: `_<local>_<hash>` (local may itself contain underscores). */
|
||||
const SCOPED_CLASS = /^_(.+)_[a-z0-9]+$/
|
||||
|
||||
/** Fold scoped tokens in one class attribute value; foreign tokens pass through. */
|
||||
function normalizeClassValue(value: string): string {
|
||||
return value
|
||||
.split(/\s+/)
|
||||
.filter(token => token !== '')
|
||||
.map(token => token.replace(SCOPED_CLASS, '$1'))
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
/** FNV-1a 32-bit over the svg markup: deterministic, dependency-free fingerprint. */
|
||||
function fingerprint(markup: string): string {
|
||||
let hash = 0x811c9dc5
|
||||
for (let i = 0; i < markup.length; i++) {
|
||||
hash ^= markup.charCodeAt(i)
|
||||
hash = Math.imul(hash, 0x01000193)
|
||||
}
|
||||
return (hash >>> 0).toString(16).padStart(8, '0')
|
||||
}
|
||||
|
||||
/** svg elements of a subtree, the root included when it is one. */
|
||||
function svgsOf(root: Element): Element[] {
|
||||
const svgs: Element[] = [...root.querySelectorAll('svg')]
|
||||
if (root.tagName.toLowerCase() === 'svg') svgs.unshift(root)
|
||||
return svgs
|
||||
}
|
||||
|
||||
/** Whether serializing this subtree needs a normalized clone. */
|
||||
function needsNormalization(root: Element): boolean {
|
||||
const scoped = [root, ...root.querySelectorAll('[class]')].some((el) => {
|
||||
const value = el.getAttribute('class')
|
||||
return value !== null && value.split(/\s+/).some(token => SCOPED_CLASS.test(token))
|
||||
})
|
||||
return scoped || svgsOf(root).some(svg => svg.childNodes.length > 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* The serializer plugin. Matches DOM elements whose subtree carries a scoped
|
||||
* class or svg internals; serializes a normalized clone, which no longer
|
||||
* matches, so printing falls through to the built-in DOM element serializer.
|
||||
*/
|
||||
export const domSnapshotSerializer: SnapshotSerializer = {
|
||||
test(value: unknown): boolean {
|
||||
return typeof Element !== 'undefined' && value instanceof Element && needsNormalization(value)
|
||||
},
|
||||
serialize(value, config, indentation, depth, refs, printer): string {
|
||||
const clone = (value as Element).cloneNode(true) as Element
|
||||
for (const el of [clone, ...clone.querySelectorAll('[class]')]) {
|
||||
const raw = el.getAttribute('class')
|
||||
if (raw !== null) el.setAttribute('class', normalizeClassValue(raw))
|
||||
}
|
||||
for (const svg of svgsOf(clone)) {
|
||||
if (svg.childNodes.length === 0) continue
|
||||
svg.setAttribute('data-content', fingerprint(svg.innerHTML))
|
||||
svg.replaceChildren()
|
||||
}
|
||||
return printer(clone, config, indentation, depth, refs)
|
||||
},
|
||||
}
|
||||
|
||||
let registered = false
|
||||
|
||||
/**
|
||||
* Register {@link domSnapshotSerializer} with vitest's expect (idempotent).
|
||||
* SlotTestRuntime.create() calls this; specs that snapshot DOM outside the
|
||||
* runtime import and call it themselves.
|
||||
*/
|
||||
export function registerDomSnapshotSerializer(): void {
|
||||
if (registered) return
|
||||
registered = true
|
||||
expect.addSnapshotSerializer(domSnapshotSerializer)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* Test double of the locale lookup chain: a translate stub over plain
|
||||
* dictionaries, mirroring LocaleService's resolution order (first dictionary
|
||||
* that owns the key wins, then the key itself stays visible) and its
|
||||
* `{name}` template interpolation. Specs stub the framework-injected `t`
|
||||
* seat with `makeTranslate(zh, commonZh)` instead of re-implementing the
|
||||
* chain per suite.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Build a translate stub resolving through `dicts` in order (namespace
|
||||
* first, then the shared common vocabulary), falling back to the key.
|
||||
* @param dicts - dictionaries consulted in order.
|
||||
* @returns the translate function (assignable to any `XxxProps['t']` seat).
|
||||
*/
|
||||
export function makeTranslate(
|
||||
...dicts: readonly Record<string, string>[]
|
||||
): (key: string, params?: Record<string, unknown>) => string {
|
||||
return (key, params) => {
|
||||
let template = key
|
||||
for (const dict of dicts) {
|
||||
const hit = dict[key]
|
||||
if (hit !== undefined) {
|
||||
template = hit
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!params) return template
|
||||
return template.replace(/\{(\w+)\}/g, (match, name: string) =>
|
||||
name in params ? String(params[name]) : match)
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
/** Test-owned workspaces face: the renderer standard-kit observable plus recorded actions. */
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type {
|
||||
DirectoryListing, IWorkspaces, SessionId, SnapshotStore, WorkspaceId, WorkspaceListState, WorkspaceView,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { workspaceListState } from './fixtures.ts'
|
||||
import type { Stabilizer } from './fixtures.ts'
|
||||
|
||||
/**
|
||||
* Workspaces test double. Implements the same IWorkspaces face features
|
||||
* receive as `ctx.workspaces`, so a production face change breaks this
|
||||
* double at compile time. Every action records into {@link
|
||||
* TestWorkspaces.calls}; defaults are inert echoes — feature tests needing
|
||||
* richer behavior replace them via {@link TestWorkspaces.stub}.
|
||||
*/
|
||||
export class TestWorkspaces implements IWorkspaces {
|
||||
/** The useWorkspaces standard feed. */
|
||||
readonly list: SnapshotStore<WorkspaceListState>
|
||||
|
||||
/** Calls observed on the action face, newest last. */
|
||||
readonly calls: { method: string; args: unknown[] }[] = []
|
||||
|
||||
/** Replaceable action seat: feature tests may stub richer behavior. */
|
||||
private readonly stubs = new Map<string, (...args: unknown[]) => unknown>()
|
||||
|
||||
/**
|
||||
* @param stabilize - the owning runtime's act wrapper.
|
||||
*/
|
||||
constructor(private readonly stabilize: Stabilizer) {
|
||||
this.list = createSnapshotStore<WorkspaceListState>(workspaceListState())
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the workspace list state through an immer draft.
|
||||
* @param mutate - draft mutator.
|
||||
*/
|
||||
async update(mutate: (draft: WorkspaceListState) => void): Promise<void> {
|
||||
await this.stabilize(() => { this.list.update(mutate) })
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace an action's behavior (the recorded call is still appended first).
|
||||
* @param method - action name (e.g. 'connectWorkspace').
|
||||
* @param impl - replacement behavior.
|
||||
*/
|
||||
stub(method: string, impl: (...args: unknown[]) => unknown): void {
|
||||
this.stubs.set(method, impl)
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect a workspace to its reusable/new blank session (recorded). The
|
||||
* default resolves the workspace id back as the session id; stub for
|
||||
* cross-session flows.
|
||||
* @param workspaceId - target workspace.
|
||||
* @returns the connected session id.
|
||||
*/
|
||||
async connectWorkspace(workspaceId: WorkspaceId): Promise<SessionId> {
|
||||
this.calls.push({ method: 'connectWorkspace', args: [workspaceId] })
|
||||
const stub = this.stubs.get('connectWorkspace')
|
||||
if (stub !== undefined) return await (stub(workspaceId) as Promise<SessionId>)
|
||||
return `session-of-${workspaceId}` as SessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* New-session flow (recorded; stubbed behavior runs when installed).
|
||||
* @param workspaceId - optional explicit workspace target.
|
||||
*/
|
||||
startSession(workspaceId?: WorkspaceId): void {
|
||||
this.calls.push({ method: 'startSession', args: [workspaceId] })
|
||||
this.stubs.get('startSession')?.(workspaceId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Workspace (recorded). The default echoes a view derived from
|
||||
* the input; stub for failure or list-coupled flows.
|
||||
* @param input - the Host create payload.
|
||||
* @returns the created Workspace view.
|
||||
*/
|
||||
async create(input: { path: string }): Promise<WorkspaceView> {
|
||||
this.calls.push({ method: 'create', args: [input] })
|
||||
const stub = this.stubs.get('create')
|
||||
if (stub !== undefined) return await (stub(input) as Promise<WorkspaceView>)
|
||||
return {
|
||||
workspaceId: `ws-${input.path}` as WorkspaceId,
|
||||
title: input.path,
|
||||
path: input.path,
|
||||
sessionIds: [],
|
||||
} as unknown as WorkspaceView
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a path with the host OS default application (recorded; default no-op).
|
||||
* @param path - host-resolvable path.
|
||||
*/
|
||||
async openPath(path: string): Promise<void> {
|
||||
this.calls.push({ method: 'openPath', args: [path] })
|
||||
await (this.stubs.get('openPath')?.(path) as Promise<void> | undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory picker (recorded). The default cancels (null); stub to select.
|
||||
* @returns the picked path, or null.
|
||||
*/
|
||||
async pickDirectory(): Promise<string | null> {
|
||||
this.calls.push({ method: 'pickDirectory', args: [] })
|
||||
const stub = this.stubs.get('pickDirectory')
|
||||
if (stub !== undefined) return await (stub() as Promise<string | null>)
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Browse listing (recorded). The default serves an empty home level; stub
|
||||
* to shape a tree.
|
||||
* @param path - absolute directory to list; absent lists the home level.
|
||||
* @returns the level's listing.
|
||||
*/
|
||||
async listDirectory(path?: string, signal?: AbortSignal): Promise<DirectoryListing> {
|
||||
// The signal is recorded and forwarded like the production face passes
|
||||
// it to the wire, so cancellation integration tests can observe or
|
||||
// reject on a superseded scan.
|
||||
this.calls.push({ method: 'listDirectory', args: [path, signal] })
|
||||
const stub = this.stubs.get('listDirectory')
|
||||
if (stub !== undefined) return await (stub(path, signal) as Promise<DirectoryListing>)
|
||||
// The chain runs root-to-target inclusive, per the DirectoryListing
|
||||
// contract — a bare root crumb would mislabel the level in browsers
|
||||
// driven by this double.
|
||||
return {
|
||||
path: '/home/test',
|
||||
home: '/home/test',
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'home', path: '/home', hidden: false },
|
||||
{ name: 'test', path: '/home/test', hidden: false },
|
||||
],
|
||||
entries: [],
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Browse child creation (recorded). The default joins parent and name.
|
||||
* @param path - absolute existing parent directory.
|
||||
* @param name - single path segment.
|
||||
* @returns the created directory's absolute path.
|
||||
*/
|
||||
async createDirectory(path: string, name: string): Promise<string> {
|
||||
this.calls.push({ method: 'createDirectory', args: [path, name] })
|
||||
const stub = this.stubs.get('createDirectory')
|
||||
if (stub !== undefined) return await (stub(path, name) as Promise<string>)
|
||||
return `${path}/${name}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a Workspace (recorded). The default echoes a minimal view.
|
||||
* @param workspaceId - target workspace.
|
||||
* @param title - new title.
|
||||
* @returns the updated view.
|
||||
*/
|
||||
async rename(workspaceId: WorkspaceId, title: string): Promise<WorkspaceView> {
|
||||
this.calls.push({ method: 'rename', args: [workspaceId, title] })
|
||||
const stub = this.stubs.get('rename')
|
||||
if (stub !== undefined) return await (stub(workspaceId, title) as Promise<WorkspaceView>)
|
||||
return { workspaceId, title, path: `/${title}`, sessionIds: [] } as unknown as WorkspaceView
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a Workspace (recorded; default no-op).
|
||||
* @param workspaceId - target workspace.
|
||||
*/
|
||||
async delete(workspaceId: WorkspaceId): Promise<void> {
|
||||
this.calls.push({ method: 'delete', args: [workspaceId] })
|
||||
await (this.stubs.get('delete')?.(workspaceId) as Promise<void> | undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a Workspace in display order (recorded; default no-op).
|
||||
* @param workspaceId - Workspace to move.
|
||||
* @param beforeWorkspaceId - Anchor; omitted appends.
|
||||
*/
|
||||
async insertBefore(workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId): Promise<void> {
|
||||
this.calls.push({ method: 'insertBefore', args: [workspaceId, beforeWorkspaceId] })
|
||||
await (this.stubs.get('insertBefore')?.(workspaceId, beforeWorkspaceId) as Promise<void> | undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move an accounted session (recorded). The default echoes a minimal view.
|
||||
* @param workspaceId - target workspace.
|
||||
* @param sessionId - session to move.
|
||||
* @param beforeSessionId - anchor; omitted appends.
|
||||
* @returns the updated view.
|
||||
*/
|
||||
async insertSessionBefore(workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId): Promise<WorkspaceView> {
|
||||
this.calls.push({ method: 'insertSessionBefore', args: [workspaceId, sessionId, beforeSessionId] })
|
||||
const stub = this.stubs.get('insertSessionBefore')
|
||||
if (stub !== undefined) return await (stub(workspaceId, sessionId, beforeSessionId) as Promise<WorkspaceView>)
|
||||
return { workspaceId, title: '', path: '', sessionIds: [sessionId] } as unknown as WorkspaceView
|
||||
}
|
||||
|
||||
/**
|
||||
* Archive a session (recorded). The default mirrors the production face's
|
||||
* observable effect: the id joins the list state's archive set.
|
||||
* @param sessionId - session to archive.
|
||||
*/
|
||||
async archiveSession(sessionId: SessionId): Promise<void> {
|
||||
this.calls.push({ method: 'archiveSession', args: [sessionId] })
|
||||
const stub = this.stubs.get('archiveSession')
|
||||
if (stub !== undefined) {
|
||||
await (stub(sessionId) as Promise<void>)
|
||||
return
|
||||
}
|
||||
await this.update((draft) => {
|
||||
draft.archivedSessionIds = [...draft.archivedSessionIds, sessionId]
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`single-slot mounting (declare + renderSlot) > folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone 1`] = `
|
||||
<div
|
||||
data-slot="trt.panel"
|
||||
>
|
||||
<div
|
||||
class="frame plain"
|
||||
>
|
||||
<span
|
||||
class="label"
|
||||
>
|
||||
styled
|
||||
</span>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-content="2bfa09dc"
|
||||
viewBox="0 0 16 16"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`single-slot mounting edge arms > serializes childless svg untouched next to scoped classes 1`] = `
|
||||
<div
|
||||
data-slot="trt.panel"
|
||||
>
|
||||
<div
|
||||
class="frame"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
viewBox="0 0 1 1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as TestRuntimeInvariant from '@deepseek-ai/dsh-client-test-runtime/invariant'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
describe('invariant companion', () => {
|
||||
it('registers under the package name with an empty installer', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await expect(ctx.plugin(TestRuntimeInvariant).await()).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
/**
|
||||
* TestRemote's own contract: subscription and disposal, dispatch driven by the
|
||||
* internal plumbing event, the silent drop for an unsubscribed name, and the
|
||||
* `$mount` refusal that sends a spec to the real Client Remote service.
|
||||
*/
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { TestRemote } from '../src/remote.ts'
|
||||
|
||||
describe('TestRemote', () => {
|
||||
it('delivers a forwarded event to its subscribers and stops after disposal', async () => {
|
||||
const ctx = new Context()
|
||||
const remote = new TestRemote(ctx)
|
||||
const seen: string[] = []
|
||||
const off = remote.$on('settings/document-updated', (ns: string) => {
|
||||
seen.push(ns)
|
||||
})
|
||||
|
||||
ctx.remote.$dispatch('settings/document-updated', ['ui-theme', 1])
|
||||
expect(seen).toEqual(['ui-theme'])
|
||||
|
||||
off()
|
||||
ctx.remote.$dispatch('settings/document-updated', ['ui-theme', 2])
|
||||
expect(seen).toEqual(['ui-theme'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('drops a forwarded event nobody subscribed to', async () => {
|
||||
const ctx = new Context()
|
||||
new TestRemote(ctx)
|
||||
// No subscriber for this name: the emit must be inert rather than throwing,
|
||||
// because the wire carries whatever the Host allowlist selected.
|
||||
expect(() => { ctx.remote.$dispatch('credentials/updated', ['DEEPSEEK_API_KEY']) }).not.toThrow()
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('refuses $mount, which needs the real Client Remote service', async () => {
|
||||
const ctx = new Context()
|
||||
const remote = new TestRemote(ctx)
|
||||
await expect(remote.$mount()).rejects.toThrow('needs the real Client Remote service')
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
})
|
||||
@@ -1,672 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* SlotTestRuntime behavior: root declaration + rendering, session
|
||||
* add/update/switch/remove through the real renderer, shared store identity
|
||||
* and scope pruning, feature mount/dispose cascade, and runtime disposal
|
||||
* idempotence. All through the production SlotsService + createSlotRenderer
|
||||
* stack — this suite is the fixture the migrated feature specs rely on.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { stubSettingsScope } from '../src/settings-scope.ts'
|
||||
import { cleanup } from '@testing-library/react'
|
||||
import { defineStore } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { PropsRenderSlots, SessionStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
'trt.panel': { kind: 'single'; scope: 'root'; owner: { label?: string } }
|
||||
'trt.chat': { kind: 'single'; scope: 'session' }
|
||||
'trt.rows': { kind: 'list'; scope: 'root' }
|
||||
'trt.rows.hole': { kind: 'single'; scope: 'root' }
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
type FrameProps = PropsRenderSlots<'trt.panel' | 'trt.chat' | 'trt.rows'>
|
||||
|
||||
/** Root frame declaring all three suite slots (render sites for each kind). */
|
||||
function Frame({ renderSlot, SessionProvider }: FrameProps) {
|
||||
return (
|
||||
<>
|
||||
{renderSlot('trt.panel', { label: 'from-owner' }, { fallback: <i>no panel</i> })}
|
||||
<SessionProvider empty={() => <i>no session</i>}>
|
||||
{() => renderSlot('trt.chat', {})}
|
||||
</SessionProvider>
|
||||
{renderSlot('trt.rows', {})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const CHILDREN = {
|
||||
'trt.panel': { kind: 'single', scope: 'root' },
|
||||
'trt.chat': { kind: 'single', scope: 'session' },
|
||||
'trt.rows': { kind: 'list', scope: 'root' },
|
||||
} as const
|
||||
|
||||
async function runtimeWithFrame() {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.root.declare(CHILDREN, Frame)
|
||||
return runtime
|
||||
}
|
||||
|
||||
describe('root declaration and rendering', () => {
|
||||
it('renders declared slots through the real renderer: fallback, then a live registration, then unload', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
const view = runtime.renderRoot()
|
||||
expect(view.container.textContent).toContain('no panel')
|
||||
|
||||
let dispose = (): void => {}
|
||||
await runtime.flush() // no-op guard: flush outside mutations is safe
|
||||
await (async () => {
|
||||
dispose = runtime.slots.register(
|
||||
{ name: 'trt.panel' },
|
||||
({ label }: { label?: string }) => <b>panel:{label}</b>)
|
||||
await runtime.flush()
|
||||
})()
|
||||
expect(view.container.textContent).toContain('panel:from-owner')
|
||||
dispose()
|
||||
await runtime.flush()
|
||||
expect(view.container.textContent).toContain('no panel')
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('fails loud when rendering with no root declaration (production boot-order check)', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
expect(() => runtime.renderRoot()).toThrow(/'root' has no registration/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('sessions', () => {
|
||||
it('drives SessionProvider: empty state, current session, switch, live snapshot updates', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
runtime.slots.register({ name: 'trt.chat' }, (props: SessionStandardProps) => {
|
||||
const running = props.useSession(s => s.running)
|
||||
return <span>chat:{props.sessionId}:{String(running)}</span>
|
||||
})
|
||||
const view = runtime.renderRoot()
|
||||
expect(view.container.textContent).toContain('no session')
|
||||
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
expect(view.container.textContent).toContain('chat:s1:false')
|
||||
|
||||
await runtime.sessions.updateSnapshot('s1', (draft) => { draft.running = true })
|
||||
expect(view.container.textContent).toContain('chat:s1:true')
|
||||
|
||||
await runtime.sessions.add({ id: 's2' }) // becomes current by default
|
||||
expect(view.container.textContent).toContain('chat:s2:false')
|
||||
|
||||
await runtime.sessions.setCurrent(undefined)
|
||||
expect(view.container.textContent).toContain('no session')
|
||||
await runtime.sessions.setCurrent('s1')
|
||||
expect(view.container.textContent).toContain('chat:s1:true')
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('add with current:false keeps the selection; unknown ids fail loud on the mutators', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
await runtime.sessions.add({ id: 's2' }, { current: false })
|
||||
expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
|
||||
expect(runtime.sessions.list.getSnapshot().ids).toEqual(['s1', 's2'])
|
||||
await expect(runtime.sessions.add({ id: 's1' })).rejects.toThrow(/already added/)
|
||||
await expect(runtime.sessions.setCurrent('ghost')).rejects.toThrow(/not added/)
|
||||
await expect(runtime.sessions.updateSnapshot('ghost', () => {})).rejects.toThrow(/not added/)
|
||||
await expect(runtime.sessions.remove('ghost')).rejects.toThrow(/not added/)
|
||||
expect(() => runtime.sessions.behavior('ghost')).toThrow(/not added/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('mints REAL-tag scopes lazily and resolves them through the production scopeOf; bindings expose the behavior face', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
const prompt = vi.fn()
|
||||
await runtime.sessions.add({ id: 's1', session: { prompt } })
|
||||
|
||||
expect(runtime.sessions.provideInfo('ghost')).toBeUndefined()
|
||||
expect(runtime.sessions.scope('ghost')).toBeUndefined()
|
||||
expect(runtime.sessions.binding('ghost')).toBeUndefined()
|
||||
|
||||
const scope = runtime.sessions.scope('s1')!
|
||||
expect(runtime.sessions.scope('s1')).toBe(scope) // stable per session
|
||||
expect(runtime.sessions.scopeOf(scope)).toBe('s1')
|
||||
expect(runtime.sessions.scopeOf(runtime.ctx)).toBeUndefined()
|
||||
// sessionOf resolves the behavior face off the scope tag.
|
||||
expect(runtime.sessions.sessionOf(scope)).toBe(runtime.sessions.behavior('s1'))
|
||||
expect(runtime.sessions.sessionOf(runtime.ctx)).toBeUndefined()
|
||||
|
||||
const binding = runtime.sessions.binding('s1')!
|
||||
expect(binding.sessionId).toBe('s1')
|
||||
expect(binding.ctx).toBe(scope)
|
||||
;(binding.session as { prompt: () => void }).prompt()
|
||||
expect(prompt).toHaveBeenCalledOnce()
|
||||
expect(runtime.sessions.behavior('s1')).toBe(binding.session)
|
||||
// The binding's session doubles as the conversation observable face.
|
||||
expect((binding.session as { getSnapshot(): { sessionId: string } }).getSnapshot().sessionId).toBe('s1')
|
||||
|
||||
// A scoped service resolves through the scope ctx (scope-addressed pattern).
|
||||
runtime.provide('probe', { hello: 'world' })
|
||||
expect(scope.get('probe')).toEqual({ hello: 'world' })
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('materializes provide bundles: built-in session hook, custom providers, no-session projection', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
|
||||
const info = runtime.sessions.provideInfo('s1')!
|
||||
expect(info.sessionId).toBe('s1')
|
||||
expect(info.hooks['session']).toBeDefined() // the built-in useSession source
|
||||
expect(runtime.sessions.provideInfo('s1')).toBe(info) // identity-stable
|
||||
|
||||
// A feature provider (the ui-conversation input pattern): declared names
|
||||
// materialize per session and land in the no-session roster as undefined.
|
||||
const off = runtime.sessions.provide({
|
||||
hooks: ['probe'],
|
||||
props: ['probeActions'],
|
||||
resolve: binding => ({
|
||||
hooks: { probe: { getSnapshot: () => binding.sessionId, subscribe: () => () => {} } },
|
||||
props: { probeActions: { poke: () => {} } },
|
||||
}),
|
||||
})
|
||||
const enriched = runtime.sessions.provideInfo('s1')!
|
||||
expect(enriched.hooks['probe']?.getSnapshot()).toBe('s1')
|
||||
expect(enriched.props['probeActions']).toBeDefined()
|
||||
const maybe = runtime.sessions.maybeProvideInfo(undefined)
|
||||
expect(maybe.sessionId).toBeUndefined()
|
||||
expect(Object.keys(maybe.hooks)).toEqual(['session', 'probe'])
|
||||
expect(runtime.sessions.maybeProvideInfo('s1')).toBe(runtime.sessions.provideInfo('s1'))
|
||||
expect(runtime.sessions.maybeProvideInfo('ghost').sessionId).toBeUndefined()
|
||||
|
||||
// Misdeclared providers fail loud AT REGISTRATION (the production
|
||||
// channel rebuilds live bundles eagerly and rolls the roster back):
|
||||
// missing hook, missing prop, duplicate hook, duplicate prop.
|
||||
expect(() => runtime.sessions.provide({ hooks: ['void'], resolve: () => ({}) }))
|
||||
.toThrow(/missing hook "void"/)
|
||||
expect(() => runtime.sessions.provide({ props: ['void'], resolve: () => ({}) }))
|
||||
.toThrow(/missing prop "void"/)
|
||||
expect(() => runtime.sessions.provide({
|
||||
hooks: ['session'],
|
||||
resolve: () => ({ hooks: { session: { getSnapshot: () => 0, subscribe: () => () => {} } } }),
|
||||
})).toThrow(/duplicate hook "session"/)
|
||||
const propA = runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 1 } }) })
|
||||
expect(() => runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 2 } }) }))
|
||||
.toThrow(/duplicate prop "twice"/)
|
||||
propA()
|
||||
// The rejected registrations rolled back: the roster still materializes.
|
||||
expect(runtime.sessions.provideInfo('s1')).toBeDefined()
|
||||
off()
|
||||
off() // disposer is idempotent
|
||||
expect(Object.keys(runtime.sessions.maybeProvideInfo(undefined).hooks)).toEqual(['session'])
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('records service-face calls and retains catalog addresses only for addressed selection', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
await runtime.sessions.add({ id: 's2' })
|
||||
const address = {
|
||||
parentSessionId: 's2' as SessionId,
|
||||
childSessionId: 's1' as SessionId,
|
||||
mode: 'continuable' as const,
|
||||
}
|
||||
runtime.sessions.openSubagent(address)
|
||||
await runtime.flush()
|
||||
expect(runtime.sessions.list.getSnapshot()).toMatchObject({ current: 's1', currentAddress: address })
|
||||
expect(runtime.sessions.subagentAddress('s1' as SessionId)).toEqual(address)
|
||||
expect(runtime.sessions.subagentAddress('s2' as SessionId)).toBeUndefined()
|
||||
await runtime.sessions.updateSummary('s1', { displayTitle: 'renamed', running: true })
|
||||
expect(runtime.sessions.list.getSnapshot().byId['s1' as SessionId])
|
||||
.toMatchObject({ displayTitle: 'renamed', running: true })
|
||||
runtime.sessions.setSubagentCatalogOpen('s2' as SessionId, true)
|
||||
await runtime.sessions.refreshSubagents('s2' as SessionId)
|
||||
// The confirmed-switch write-back lands on the row it names and ignores
|
||||
// one the fixture never added, exactly as production's list upsert does.
|
||||
runtime.sessions.noteAgentPreset('s1' as SessionId, 'minimal')
|
||||
runtime.sessions.noteAgentPreset('missing' as SessionId, 'minimal')
|
||||
await runtime.flush()
|
||||
expect(runtime.sessions.list.getSnapshot().byId['s1' as SessionId])
|
||||
.toMatchObject({ agentPreset: 'minimal' })
|
||||
runtime.sessions.open('s1' as SessionId)
|
||||
await runtime.flush()
|
||||
expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
|
||||
expect(runtime.sessions.list.getSnapshot().currentAddress).toBeUndefined()
|
||||
runtime.sessions.clear()
|
||||
await runtime.flush()
|
||||
expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
|
||||
await expect(runtime.sessions.fork({
|
||||
sessionId: 's1' as SessionId, atSeq: 7, increaseTitle: true,
|
||||
})).resolves.toBe('s1')
|
||||
expect(runtime.sessions.calls).toEqual([
|
||||
{ method: 'openSubagent', args: [address] },
|
||||
{ method: 'setSubagentCatalogOpen', args: ['s2', true] },
|
||||
{ method: 'refreshSubagents', args: ['s2'] },
|
||||
{ method: 'open', args: ['s1'] },
|
||||
{ method: 'clear', args: [] },
|
||||
{ method: 'fork', args: [{ sessionId: 's1', atSeq: 7, increaseTitle: true }] },
|
||||
])
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('answers search with an empty page until a scenario declares hits, recording every call', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
const signal = new AbortController().signal
|
||||
expect(runtime.sessions.searchResultLimit).toBeGreaterThan(0)
|
||||
await expect(runtime.sessions.search('marker', signal))
|
||||
.resolves.toEqual({ ok: true, value: { items: [], hasMore: false } })
|
||||
runtime.sessions.stubSearch(query => ({
|
||||
items: [{ sessionId: 's1' as SessionId, snippet: `hit: ${query}` }],
|
||||
hasMore: true,
|
||||
}))
|
||||
await expect(runtime.sessions.search('marker', signal)).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { items: [{ sessionId: 's1', snippet: 'hit: marker' }], hasMore: true },
|
||||
})
|
||||
expect(runtime.sessions.calls).toEqual([
|
||||
{ method: 'search', args: ['marker', signal] },
|
||||
{ method: 'search', args: ['marker', signal] },
|
||||
])
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('stores', () => {
|
||||
const createSuiteStore = () => defineStore({
|
||||
init: () => ({ note: '' }),
|
||||
persist: 'trt.store',
|
||||
actions: { setNote: (d, note: string) => { d.note = note } },
|
||||
})
|
||||
|
||||
it('resolves per-session instances via the host face: shared identity, isolation, action-driven re-render', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
const handle = createSuiteStore()
|
||||
runtime.slots.register(
|
||||
{ name: 'trt.chat', store: handle },
|
||||
(props: SessionStandardProps & { useStore: <S>(sel: (s: { note: string }) => S) => S }) =>
|
||||
<span>note:{props.useStore(s => s.note)}</span>)
|
||||
const view = runtime.renderRoot()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
|
||||
expect(() => runtime.storeOf('trt.panel')).toThrow(/no registration/)
|
||||
const store = runtime.storeOf('trt.chat', 's1')
|
||||
await runtime.flush()
|
||||
;(store.actions['setNote'] as (note: string) => void)('hello')
|
||||
await runtime.flush()
|
||||
expect(view.container.textContent).toContain('note:hello')
|
||||
expect(runtime.storeOf('trt.chat', 's1')).toBe(store) // cached per scope key
|
||||
|
||||
await runtime.sessions.add({ id: 's2' })
|
||||
const other = runtime.storeOf('trt.chat', 's2')
|
||||
expect(other).not.toBe(store)
|
||||
expect(other.getSnapshot()).toEqual({ note: '' })
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('storeOf guards: before renderRoot, and for storeless entries', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
runtime.slots.register({ name: 'trt.panel' }, () => null)
|
||||
expect(() => runtime.storeOf('trt.panel')).toThrow(/before renderRoot/)
|
||||
runtime.renderRoot()
|
||||
expect(() => runtime.storeOf('trt.panel')).toThrow(/declares no store/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('remove() prunes the session store scope: persisted state clears, a re-added session starts fresh', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
const handle = createSuiteStore()
|
||||
runtime.slots.register({ name: 'trt.chat', store: handle }, () => null)
|
||||
runtime.renderRoot()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
|
||||
const doomed = runtime.storeOf('trt.chat', 's1')
|
||||
;(doomed.actions['setNote'] as (note: string) => void)('buried')
|
||||
expect(localStorage.getItem('trt.store.s1')).not.toBeNull()
|
||||
|
||||
await runtime.sessions.remove('s1')
|
||||
expect(localStorage.getItem('trt.store.s1')).toBeNull()
|
||||
expect(runtime.sessions.list.getSnapshot().ids).toEqual([])
|
||||
expect(runtime.sessions.provideInfo('s1')).toBeUndefined()
|
||||
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
const reborn = runtime.storeOf('trt.chat', 's1')
|
||||
expect(reborn).not.toBe(doomed)
|
||||
expect(reborn.getSnapshot()).toEqual({ note: '' })
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('remove() also disposes a minted scope fiber; removing a non-current session keeps the selection', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
await runtime.sessions.add({ id: 's2' }, { current: false })
|
||||
const scope = runtime.sessions.scope('s1')!
|
||||
await runtime.sessions.remove('s2')
|
||||
expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
|
||||
await runtime.sessions.remove('s1')
|
||||
expect(scope.fiber.uid).toBeNull() // disposed fiber loses its uid
|
||||
expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspaces', () => {
|
||||
it('feeds useWorkspaces and records/stubs intent actions', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
runtime.slots.register(
|
||||
{ name: 'trt.panel' },
|
||||
(props: { useWorkspaces: <S>(sel: (s: { phase: string }) => S) => S }) =>
|
||||
<span>ws:{props.useWorkspaces(s => s.phase)}</span>)
|
||||
const view = runtime.renderRoot()
|
||||
expect(view.container.textContent).toContain('ws:ready')
|
||||
|
||||
await runtime.workspaces.update((draft) => { draft.phase = 'pending' })
|
||||
expect(view.container.textContent).toContain('ws:pending')
|
||||
|
||||
runtime.workspaces.startSession('w1' as WorkspaceId)
|
||||
await expect(runtime.workspaces.connectWorkspace('w2' as WorkspaceId)).resolves.toBe('session-of-w2')
|
||||
expect(runtime.workspaces.calls).toEqual([
|
||||
{ method: 'startSession', args: ['w1'] },
|
||||
{ method: 'connectWorkspace', args: ['w2'] },
|
||||
])
|
||||
const stub = vi.fn(() => Promise.resolve('other' as never))
|
||||
runtime.workspaces.stub('connectWorkspace', stub)
|
||||
await expect(runtime.workspaces.connectWorkspace('w3' as WorkspaceId)).resolves.toBe('other')
|
||||
expect(stub).toHaveBeenCalledOnce()
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('records the browse calls: listDirectory serves an empty home, createDirectory joins, stubs override', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
// Defaults: an empty home level and parent/name joining.
|
||||
await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] })
|
||||
await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' })
|
||||
await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh')
|
||||
// The recorded signal seat mirrors the production face (undefined here;
|
||||
// cancellation tests pass and observe a real one).
|
||||
expect(runtime.workspaces.calls).toEqual([
|
||||
{ method: 'listDirectory', args: [undefined, undefined] },
|
||||
{ method: 'listDirectory', args: ['/home/test', undefined] },
|
||||
{ method: 'createDirectory', args: ['/home/test', 'fresh'] },
|
||||
])
|
||||
// Stubs replace the defaults like every sibling method.
|
||||
const listing = { path: '/x', home: '/x', crumbs: [], entries: [] }
|
||||
const listStub = vi.fn(() => Promise.resolve(listing as never))
|
||||
runtime.workspaces.stub('listDirectory', listStub)
|
||||
runtime.workspaces.stub('createDirectory', vi.fn(() => Promise.resolve('/x/made' as never)))
|
||||
const scan = new AbortController()
|
||||
await expect(runtime.workspaces.listDirectory('/x', scan.signal)).resolves.toBe(listing)
|
||||
// The stub receives the signal too, like the production face gives the wire.
|
||||
expect(listStub).toHaveBeenLastCalledWith('/x', scan.signal)
|
||||
await expect(runtime.workspaces.createDirectory('/x', 'made')).resolves.toBe('/x/made')
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('feature mount and disposal', () => {
|
||||
it('mounts a plugin on a real fiber; dispose() cascades entries, declared children, and services', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
runtime.provide('layout', { openDetails: vi.fn() })
|
||||
const feature = await runtime.mount({
|
||||
inject: ['slots', 'layout'],
|
||||
apply: (ctx: typeof runtime.ctx) => {
|
||||
ctx.provide('feature-service', { ok: true })
|
||||
ctx.slots.register({
|
||||
name: 'trt.rows',
|
||||
id: 'row-1',
|
||||
children: { 'trt.rows.hole': { kind: 'single', scope: 'root' } },
|
||||
} as never, ((props: { renderSlot: (key: string, owner: object) => unknown }) =>
|
||||
<div data-testid="row">{props.renderSlot('trt.rows.hole', {}) as React.ReactNode}</div>) as never)
|
||||
},
|
||||
})
|
||||
const view = runtime.renderRoot()
|
||||
expect(view.getByTestId('row')).toBeTruthy()
|
||||
expect(runtime.ctx.get('feature-service')).toEqual({ ok: true })
|
||||
expect(runtime.slots.entries('trt.rows')).toHaveLength(1)
|
||||
|
||||
await feature.dispose()
|
||||
await feature.dispose() // idempotent
|
||||
expect(runtime.slots.entries('trt.rows')).toHaveLength(0)
|
||||
expect(runtime.slots.spec('trt.rows.hole')).toBeUndefined()
|
||||
expect(runtime.ctx.get('feature-service')).toBeUndefined()
|
||||
expect(view.queryByTestId('row')).toBeNull()
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('mount fails loud on missing services instead of suspending forever', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
await expect(runtime.mount({ inject: ['slots', 'absent-service'], apply: () => {} }))
|
||||
.rejects.toThrow(/missing service\(s\) absent-service/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('runtime dispose is idempotent, unmounts views, disposes mounted features, and clears persisted state', async () => {
|
||||
const runtime = await runtimeWithFrame()
|
||||
const feature = await runtime.mount({
|
||||
inject: ['slots'],
|
||||
apply: (ctx: typeof runtime.ctx) => { ctx.slots.register({ name: 'trt.panel' }, () => <b>p</b>) },
|
||||
})
|
||||
const view = runtime.renderRoot()
|
||||
expect(view.container.textContent).toContain('p')
|
||||
localStorage.setItem('trt.leftover', 'x')
|
||||
|
||||
await runtime.dispose()
|
||||
expect(view.container.innerHTML).toBe('')
|
||||
expect(feature.fiber.uid).toBeNull()
|
||||
expect(localStorage.getItem('trt.leftover')).toBeNull()
|
||||
await runtime.dispose() // idempotent
|
||||
await expect(runtime.dispose()).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('single-slot mounting (declare + renderSlot)', () => {
|
||||
it('renders one slot inside its data-slot wrapper and updates owner props in place', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
|
||||
runtime.slots.register(
|
||||
{ name: 'trt.panel' },
|
||||
({ label }: { label?: string }) => <b data-testid="panel">{label ?? 'none'}</b>)
|
||||
const slot = runtime.renderSlot('trt.panel', { label: 'first' })
|
||||
expect(slot.container.getAttribute('data-slot')).toBe('trt.panel')
|
||||
expect(slot.view.getByTestId('panel').textContent).toBe('first')
|
||||
|
||||
const panel = slot.view.getByTestId('panel')
|
||||
slot.update({ label: 'second' })
|
||||
expect(slot.view.getByTestId('panel').textContent).toBe('second')
|
||||
// In-place re-render: the element identity survived the owner flip.
|
||||
expect(slot.view.getByTestId('panel')).toBe(panel)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('views sibling slots of one tree separately and rejects undeclared keys', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.declare({
|
||||
'trt.panel': { kind: 'single', scope: 'root' },
|
||||
'trt.rows': { kind: 'list', scope: 'root' },
|
||||
})
|
||||
runtime.slots.register({ name: 'trt.panel' }, () => <b>panel</b>)
|
||||
runtime.slots.register({ name: 'trt.rows', id: 'r1' }, () => <i>row</i>)
|
||||
const panel = runtime.renderSlot('trt.panel', {})
|
||||
const rows = runtime.renderSlot('trt.rows', {})
|
||||
expect(panel.container.textContent).toBe('panel')
|
||||
expect(rows.container.textContent).toBe('row')
|
||||
expect(() => runtime.renderSlot('trt.chat', {})).toThrow(/without declare\(\)/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
|
||||
runtime.slots.register({ name: 'trt.panel' }, () => (
|
||||
<div className="_frame_a1b2c3 plain">
|
||||
<span className="_label_ff00aa">styled</span>
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true">
|
||||
<path d="M0 0L16 16" fill="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
))
|
||||
const slot = runtime.renderSlot('trt.panel', {})
|
||||
expect(slot.container).toMatchSnapshot()
|
||||
// The serializer works on a clone: the live DOM keeps hashes and paths.
|
||||
expect(slot.container.querySelector('div')!.className).toBe('_frame_a1b2c3 plain')
|
||||
expect(slot.container.querySelector('svg path')).not.toBeNull()
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('fixture session face', () => {
|
||||
it('fail-loud stubs name the missing verb; supplied overrides run instead', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
const bare = runtime.sessions.behavior('s1')
|
||||
expect(() => bare.prompt()).toThrow(/prompt is not stubbed/)
|
||||
expect(() => bare.readAttachment('att-1' as Parameters<typeof bare.readAttachment>[0])).toThrow(/readAttachment is not stubbed/)
|
||||
expect(() => bare.updateQueue()).toThrow(/updateQueue is not stubbed/)
|
||||
expect(() => bare.cancel()).toThrow(/cancel is not stubbed/)
|
||||
expect(() => bare.command()).toThrow(/command is not stubbed/)
|
||||
expect(() => bare.loadOlder()).toThrow(/loadOlder is not stubbed/)
|
||||
expect(() => bare.rename()).toThrow(/rename is not stubbed/)
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
it('projections faces are identity-stable per key, read absent, and notify on set', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.sessions.add({ id: 's1' })
|
||||
const session = runtime.sessions.behavior('s1')
|
||||
const face = session.projections.faceOf('todos')
|
||||
expect(session.projections.faceOf('todos')).toBe(face)
|
||||
expect(face.getSnapshot()).toBeUndefined()
|
||||
const seen: unknown[] = []
|
||||
const off = face.subscribe(() => { seen.push(face.getSnapshot()) })
|
||||
session.projections.set('todos', [1, 2])
|
||||
expect(seen).toEqual([[1, 2]])
|
||||
off()
|
||||
session.projections.set('todos', [3])
|
||||
expect(seen).toEqual([[1, 2]]) // unsubscribed
|
||||
// A never-subscribed key sets without listeners (the empty-notify arm).
|
||||
session.projections.set('untouched', 1)
|
||||
// The provide bundle hands the same store to the render side.
|
||||
const info = runtime.sessions.provideInfo('s1')!
|
||||
expect(info.projections?.faceOf('todos').getSnapshot()).toEqual([3])
|
||||
// A roster change rebuilds the ALREADY-materialized bundle eagerly
|
||||
// (production channel semantics: mounted entries must see the provider)
|
||||
// and skips never-materialized records (they pick the roster up lazily).
|
||||
await runtime.sessions.add({ id: 's-lazy' }, { current: false })
|
||||
const offProbe = runtime.sessions.provide({
|
||||
hooks: ['probe2'],
|
||||
resolve: () => ({ hooks: { probe2: { getSnapshot: () => 1, subscribe: () => () => {} } } }),
|
||||
})
|
||||
const rebuilt = runtime.sessions.provideInfo('s1')!
|
||||
expect(rebuilt).not.toBe(info)
|
||||
expect(rebuilt.hooks['probe2']).toBeDefined()
|
||||
offProbe()
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspaces action face', () => {
|
||||
it('records every IWorkspaces verb with inert defaults and honors stubs', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
const ws = runtime.workspaces
|
||||
const created = await ws.create({ path: '/tmp/alpha' })
|
||||
expect(created.title).toBe('/tmp/alpha')
|
||||
const registered = await ws.create({ path: '/tmp/beta' })
|
||||
expect(registered.path).toBe('/tmp/beta')
|
||||
await expect(ws.pickDirectory()).resolves.toBeNull()
|
||||
const renamed = await ws.rename('w1' as WorkspaceId, 'Renamed')
|
||||
expect(renamed.title).toBe('Renamed')
|
||||
await ws.delete('w1' as WorkspaceId)
|
||||
await ws.openPath('/proj/file.ts')
|
||||
await ws.insertBefore('w1' as WorkspaceId, 'w2' as WorkspaceId)
|
||||
const moved = await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId, 's2' as SessionId)
|
||||
expect(moved.sessionIds).toEqual(['s1'])
|
||||
// Default archive mirrors the production effect: the id joins the list
|
||||
// state's archive set (features render against the same snapshot).
|
||||
await ws.archiveSession('s1' as SessionId)
|
||||
expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
|
||||
expect(ws.calls.map(c => c.method)).toEqual(
|
||||
['create', 'create', 'pickDirectory', 'rename', 'delete', 'openPath', 'insertBefore', 'insertSessionBefore', 'archiveSession'])
|
||||
|
||||
ws.stub('create', () => Promise.resolve({ workspaceId: 'ws-x', title: 'X', path: '/x', sessionIds: [] } as never))
|
||||
ws.stub('pickDirectory', () => Promise.resolve('/picked'))
|
||||
ws.stub('rename', () => Promise.resolve({ workspaceId: 'w1', title: 'S', path: '/s', sessionIds: [] } as never))
|
||||
ws.stub('delete', () => Promise.resolve())
|
||||
ws.stub('openPath', () => Promise.resolve())
|
||||
const insertBefore = vi.fn(() => Promise.resolve())
|
||||
ws.stub('insertBefore', insertBefore)
|
||||
ws.stub('insertSessionBefore', () => Promise.resolve({ workspaceId: 'w1', title: '', path: '', sessionIds: [] } as never))
|
||||
ws.stub('archiveSession', () => Promise.resolve())
|
||||
expect((await ws.create({ path: '/y' })).title).toBe('X')
|
||||
await expect(ws.pickDirectory()).resolves.toBe('/picked')
|
||||
expect((await ws.rename('w1' as WorkspaceId, 'z')).title).toBe('S')
|
||||
await ws.delete('w1' as WorkspaceId)
|
||||
await ws.openPath('/other')
|
||||
await ws.insertBefore('w2' as WorkspaceId)
|
||||
expect(insertBefore).toHaveBeenCalledWith('w2', undefined)
|
||||
expect((await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId)).sessionIds).toEqual([])
|
||||
// The stub replaces the default set mutation: the set stays as-is.
|
||||
await ws.archiveSession('s2' as SessionId)
|
||||
expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('single-slot mounting edge arms', () => {
|
||||
it('renderSlot fails loud after dispose and after an external unmount', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
|
||||
runtime.slots.register({ name: 'trt.panel' }, () => <b>p</b>)
|
||||
runtime.renderSlot('trt.panel', {})
|
||||
// RTL cleanup empties the mounted tree behind the runtime's back: the
|
||||
// wrapper lookup names the state instead of returning a dead container.
|
||||
cleanup()
|
||||
expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/rendered no wrapper/)
|
||||
await runtime.dispose()
|
||||
// After dispose the root registration is gone: the production boot-order
|
||||
// check fires before any wrapper lookup.
|
||||
expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/'root' has no registration/)
|
||||
})
|
||||
|
||||
it('serializes childless svg untouched next to scoped classes', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
|
||||
runtime.slots.register({ name: 'trt.panel' }, () => (
|
||||
<div className="_frame_a1b2c3">
|
||||
<svg viewBox="0 0 1 1" aria-hidden="true" />
|
||||
</div>
|
||||
))
|
||||
const slot = runtime.renderSlot('trt.panel', {})
|
||||
expect(slot.container).toMatchSnapshot()
|
||||
await runtime.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
describe('stubbed settings scope', () => {
|
||||
it('records both write kinds and publishes a Host acceptance to its listeners', async () => {
|
||||
const host = stubSettingsScope<{ preference: string }>()
|
||||
let notified = 0
|
||||
const stop = host.scope.subscribe(() => { notified += 1 })
|
||||
expect(host.listenerCount()).toBe(1)
|
||||
expect(host.scope.getSnapshot()).toMatchObject({
|
||||
status: 'loading', base: undefined, user: undefined,
|
||||
})
|
||||
|
||||
await host.scope.set('preference', 'dark')
|
||||
await host.scope.unset('preference')
|
||||
host.publish({
|
||||
status: 'ready',
|
||||
value: { preference: 'system' },
|
||||
base: { preference: 'system' },
|
||||
revision: 2,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
expect(host.set).toHaveBeenCalledWith('preference', 'dark')
|
||||
expect(host.unset).toHaveBeenCalledWith('preference')
|
||||
expect(notified).toBe(1)
|
||||
expect(host.scope.getSnapshot()).toMatchObject({ status: 'ready', revision: 2, writable: true })
|
||||
stop()
|
||||
expect(host.listenerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../web-react"
|
||||
},
|
||||
{
|
||||
"path": "../runtime"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../host/apiproxy"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { clientLibrary } from '../tsdown.client.ts'
|
||||
|
||||
export default clientLibrary(
|
||||
'@deepseek-ai/dsh-client-test-runtime',
|
||||
['lib/types/index.js', 'lib/types/invariant.js'],
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-agent-preset",
|
||||
"description": "Agent-preset surfaces: the default for later sessions, this session's seat, and the composition editor",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -100,7 +100,7 @@ export const zh: Record<AgentPresetSettingsKey, string> = {
|
||||
view: '查看',
|
||||
presetStandardName: '标准模式',
|
||||
presetStandardDescription: '功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。',
|
||||
presetCodeName: '代码模式',
|
||||
presetCodeName: 'PTC 模式',
|
||||
presetCodeDescription: '具备标准模式的全部能力,并通过 Code Mode SDK 呈现工具,让模型用一个 TypeScript 程序组合多步操作。',
|
||||
presetMinimalName: '极简模式',
|
||||
presetMinimalDescription: '仅提供持久 bash 与 str_replace_editor 的双工具编码 Agent。',
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { apply, inject } from '@deepseek-ai/dsh-client-ui-agent-preset/client'
|
||||
import { AgentPresetLabel } from '../src/client/AgentPresetLabel.tsx'
|
||||
@@ -75,8 +75,8 @@ async function bench() {
|
||||
// settings surface does and watch who re-reads it.
|
||||
let ROSTER: typeof ROSTER_ONE | typeof ROSTER_MOVED | typeof ROSTER_AUTHORED = ROSTER_ONE
|
||||
const moveDefault = (): void => { ROSTER = ROSTER_MOVED }
|
||||
await ctx.plugin(SlotsService).await()
|
||||
const locale = new LocaleService(ctx)
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
const locale = new LocaleRuntime(ctx)
|
||||
ctx.provide('locale', locale)
|
||||
// The plugins inject `remote`; forwarded events reach them through the
|
||||
// same `$dispatch` handoff the connection sink makes.
|
||||
@@ -117,10 +117,10 @@ async function bench() {
|
||||
},
|
||||
},
|
||||
} as never)
|
||||
return { ctx, slots: ctx.get('slots') as SlotsService, calls, moveDefault }
|
||||
return { ctx, slots: ctx.get('slots') as SlotRegistry, calls, moveDefault }
|
||||
}
|
||||
|
||||
function declareRoot(slots: SlotsService): () => void {
|
||||
function declareRoot(slots: SlotRegistry): () => void {
|
||||
return slots.register({
|
||||
name: 'root',
|
||||
children: {
|
||||
@@ -132,7 +132,7 @@ function declareRoot(slots: SlotsService): () => void {
|
||||
}
|
||||
|
||||
/** The conversation's own declarations, which the chip and label wait for. */
|
||||
function declareConversation(slots: SlotsService): () => void {
|
||||
function declareConversation(slots: SlotRegistry): () => void {
|
||||
return slots.register({
|
||||
name: 'conversation',
|
||||
children: {
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
||||
import * as AgentPresetInvariant from '@deepseek-ai/dsh-client-ui-agent-preset/invariant'
|
||||
|
||||
describe('invariant companion', () => {
|
||||
it('reserves package ownership with an empty installer', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(InvariantRegistry, { enabled: true })
|
||||
|
||||
await expect(ctx.plugin(AgentPresetInvariant).await()).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"path": "../runtime"
|
||||
},
|
||||
{
|
||||
"path": "../test-runtime"
|
||||
"path": "../../test-support/client-runtime"
|
||||
},
|
||||
{
|
||||
"path": "../ui-conversation"
|
||||
@@ -36,7 +36,7 @@
|
||||
"path": "../web-react"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../api/remotes/tsconfig.client.json"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-attachment",
|
||||
"description": "Pure React attachment atoms for the dsh web UI: draft-image rail, message image gallery, and original-image lightbox (zero cordis)",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as AttachmentInvariant from '@deepseek-ai/dsh-client-ui-attachment/invariant'
|
||||
import InvariantService from '@deepseek-ai/dsh-invariants'
|
||||
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
describe('invariant companion', () => {
|
||||
it('registers under the package name with an empty installer', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(InvariantService, { enabled: true })
|
||||
await ctx.plugin(InvariantRegistry, { enabled: true })
|
||||
await expect(ctx.plugin(AttachmentInvariant).await()).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -12,7 +12,7 @@
|
||||
"path": "../../attachment/attachment"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
"path": "../../runtime-diagnostics/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../ui-primitives"
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import { clientBundle } from '../tsdown.client.ts'
|
||||
|
||||
export default clientBundle('@deepseek-ai/dsh-client-ui-command', ['lib/types/index.js', 'lib/types/invariant.js'])
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-models/README.md
|
||||
README.md: a8d030b7676e87709fb36b87a6599decc43e0b4b
|
||||
README.zh.md: a01b5a6f25fc881b2a9bc7a3799214550d0fc7d3
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-commands/README.md
|
||||
README.md: 67110ffd8c1ad11e56ca9293a9064c66dd08c81d
|
||||
README.zh.md: 40fe21850dd289d2a5c91bd88d4f22c087731b80
|
||||
@@ -1,10 +1,10 @@
|
||||
# @deepseek-ai/dsh-client-ui-command
|
||||
# @deepseek-ai/dsh-client-ui-commands
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Client command API (`ctx.command`): the session-keyed command-directory cache, the `/` command source with `matchSpace`/`matchEnter` decision hooks, three-kind dispatch (`execute` / `popupSelect` / `leadingInput`), and popupSelect registration for business packages. The [web command Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-command-surfaces-and-assembly.zh.md) records the decision.
|
||||
Client command API (`ctx.commandUi`): the session-keyed command-directory cache, the `/` command source with `matchSpace`/`matchEnter` decision hooks, three-kind dispatch (`execute` / `popupSelect` / `leadingInput`), and popupSelect registration for business packages. The [web command Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-command-surfaces-and-assembly.zh.md) records the decision.
|
||||
|
||||
`src/client/contract.ts` is the fixed business contract: `CommandServiceContract.register(name, spec)` and `decorate(name, spec)` are everything a business package consumes; `CommandUiSpec{options, onSelect}` keeps popup data self-contained — the shell component belongs to this package and business packages never see it. A contribution is a client-owned command (a host-name collision fails loud); a decoration adds a bare-invocation popup to an EXISTING host command. The host keeps its catalog row, argument claim (space / argued Enter), and lifecycle logging, and a decorated name with no host row in the session's directory never fires. Command kinds derive per dispatch, never per registration: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is `popupSelect`, and everything else is `execute`.
|
||||
`src/client/contract.ts` is the fixed business contract: `CommandUiContract.register(name, spec)` and `decorate(name, spec)` are everything a business package consumes; `CommandUiSpec{options, onSelect}` keeps popup data self-contained — the shell component belongs to this package and business packages never see it. A contribution is a client-owned command (a host-name collision fails loud); a decoration adds a bare-invocation popup to an EXISTING host command. The host keeps its catalog row, argument claim (space / argued Enter), and lifecycle logging, and a decorated name with no host row in the session's directory never fires. Command kinds derive per dispatch, never per registration: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is `popupSelect`, and everything else is `execute`.
|
||||
|
||||
`CommandDirectory` (`src/client/directory.ts`) is the one wire-derived cache, keyed by session. Ordinary sessions fetch through `command.list({sessionId})`, and the source's scope-birth `warm` hook prewarms the session's entry. Catalog-addressed continuable children resolve an empty command directory locally: `command.list` is Agent-bound, so prewarming it would activate a child merely to view persisted history. Entries are soft-invalidated by the forwarded `commands/change` owner event (old snapshots serve while the repull flies) and by forwarded `agent-preset/selected` for that one session (recomposing an agent registers nothing, so the registry-wide signal never fires for it), hard-invalidated by `connection/reset`, and epoch-guarded so a superseded pull can never overwrite a newer one. `matchSpace` answers synchronously from this cache only; `matchEnter` strong-waits it on the SubmitAttempt signal and rejects on warmup failure — a `/` line is never silently downgraded to a plain prompt.
|
||||
|
||||
@@ -14,7 +14,7 @@ Menu queries fuzzy-match ordered, case-insensitive subsequences of command names
|
||||
|
||||
`PopupSelectController` (`src/client/popup.ts`) is the headless shell state: `PopupSelectView` self-registers into `conversation.input.overlay` (the SlotMap key is ui-conversation's; this package pulls the declaration in with a type-only import — no runtime edge). The shell is a transient layer holding focus while open; token-segment consumption after onSelect runs both branches through `consumeTokenSegment` (menu-path span CAS, enter-path bare-token equality) against the draft face the wiring layer binds via `bindDraft`.
|
||||
|
||||
The `/client` entrypoint exports the plugin body (`apply`/`inject`), `CommandService`, the directory and popup classes with their state types, and the fixed contract types; the shell component itself is internal to the overlay registration.
|
||||
The `/client` entrypoint exports the plugin body (`apply`/`inject`), `CommandUiRuntime`, the directory and popup classes with their state types, and the fixed contract types; the shell component itself is internal to the overlay registration.
|
||||
|
||||
## Model Experience
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# @deepseek-ai/dsh-client-ui-command
|
||||
# @deepseek-ai/dsh-client-ui-commands
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
客户端命令 API(`ctx.command`):以会话为 key 的命令目录缓存、带 `matchSpace`/`matchEnter` 决策钩子的 `/` 命令 source、三类派发(`execute`/`popupSelect`/`leadingInput`),以及面向业务包的 popupSelect 注册。[Web 命令 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-command-surfaces-and-assembly.zh.md) 记录了这项决策。
|
||||
客户端命令 API(`ctx.commandUi`):以会话为 key 的命令目录缓存、带 `matchSpace`/`matchEnter` 决策钩子的 `/` 命令 source、三类派发(`execute`/`popupSelect`/`leadingInput`),以及面向业务包的 popupSelect 注册。[Web 命令 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-25-web-command-surfaces-and-assembly.zh.md) 记录了这项决策。
|
||||
|
||||
`src/client/contract.ts` 是固定的业务 API 约定:`CommandServiceContract.register(name, spec)` 与 `decorate(name, spec)` 是业务包消费的全部内容;`CommandUiSpec{options, onSelect}` 自己提供 popup 数据——外层组件归本包所有,业务包永远见不到它。贡献项是客户端自有命令(与 host 命令同名时会明确报错);装饰项则为**已存在的** host 命令添加裸调用 popup。host 保留目录行、带参 claim(空格/带参数的 Enter)与生命周期记账,被装饰的名字若在会话目录中无 host 行,则永不触发。命令类型按每次派发派生,绝不在注册时定型:带 `input` 的 host descriptor 是 `leadingInput`,注册了 `CommandUiSpec` 的是 `popupSelect`,其余全部是 `execute`。
|
||||
`src/client/contract.ts` 是固定的业务 API 约定:`CommandUiContract.register(name, spec)` 与 `decorate(name, spec)` 是业务包消费的全部内容;`CommandUiSpec{options, onSelect}` 自己提供 popup 数据——外层组件归本包所有,业务包永远见不到它。贡献项是客户端自有命令(与 host 命令同名时会明确报错);装饰项则为**已存在的** host 命令添加裸调用 popup。host 保留目录行、带参 claim(空格/带参数的 Enter)与生命周期记账,被装饰的名字若在会话目录中无 host 行,则永不触发。命令类型按每次派发派生,绝不在注册时定型:带 `input` 的 host descriptor 是 `leadingInput`,注册了 `CommandUiSpec` 的是 `popupSelect`,其余全部是 `execute`。
|
||||
|
||||
`CommandDirectory`(`src/client/directory.ts`)是唯一的 wire 派生缓存,以会话为 key。普通会话通过 `command.list({sessionId})` 拉取,source 的 scope 出生 `warm` 钩子会预热该会话的缓存项。由目录寻址的可继续子代理会在客户端解析为空命令目录:`command.list` 绑定 Agent,若预热它,就会仅因查看持久化历史而激活子代理。缓存项由转发的 owner 事件 `commands/change` 软失效(重拉在途期间旧快照继续服务),也由转发的 `agent-preset/selected` 对该会话单独软失效(重组 agent 不产生任何注册,注册表级信号不会为它触发),由 `connection/reset` 硬失效,并以 epoch 把关,被取代的旧拉取永远无法覆盖更新的结果。`matchSpace` 只凭该缓存同步应答;`matchEnter` 在 SubmitAttempt 信号上强等缓存,预热失败即拒绝——`/` 开头的一行绝不会被静默降级为普通提示词。
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
`PopupSelectController`(`src/client/popup.ts`)是不含界面的外壳状态:`PopupSelectView` 自行注册进 `conversation.input.overlay`(SlotMap key 归 ui-conversation 所有;本包只以 type-only 导入引入该声明——没有运行时依赖边)。壳是打开期间持有焦点的瞬态层;onSelect 之后的 token 片段消费在两条分支上都经 `consumeTokenSegment` 执行(菜单路径做 span CAS,回车路径做裸 token 相等比较),作用于接线层经 `bindDraft` 绑定的草稿表层。
|
||||
|
||||
`/client` 入口导出插件主体(`apply`/`inject`)、`CommandService`、目录类和 popup 类及其状态类型,以及固定的约定类型;外层组件本身是 overlay 注册的内部实现。
|
||||
`/client` 入口导出插件主体(`apply`/`inject`)、`CommandUiRuntime`、目录类和 popup 类及其状态类型,以及固定的约定类型;外层组件本身是 overlay 注册的内部实现。
|
||||
|
||||
## 模型体验
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-command",
|
||||
"name": "@deepseek-ai/dsh-client-ui-commands",
|
||||
"description": "Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry",
|
||||
"version": "0.0.1-rc.2",
|
||||
"version": "0.0.1-rc.3",
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/client/ui-command"
|
||||
"directory": "packages/client/ui-commands"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
@@ -35,7 +35,7 @@
|
||||
"@deepseek-ai/dsh-api-remotes",
|
||||
"@deepseek-ai/dsh-client-runtime",
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-slash",
|
||||
"@deepseek-ai/dsh-client-ui-input-trigger",
|
||||
"@deepseek-ai/dsh-client-ui-conversation"
|
||||
],
|
||||
"platform": "web"
|
||||
@@ -55,7 +55,7 @@
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slash": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-input-trigger": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-commands": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
@@ -70,7 +70,7 @@
|
||||
"@deepseek-ai/dsh-client-test-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slash": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-input-trigger": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-commands": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user