diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index e4b4714af1..cccd955846 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -15,8 +15,8 @@ en: 0e1399cad4151f87 zh: 960fa0ccbe0f8fea /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/cancellation-codes-record-whether-dispatch-occurred: - en: c787fba8731ac147 - zh: 21b5968ae6f8cd59 + en: 86c5566581c1d3d6 + zh: 3cb71fbb97bdb291 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/decision/pre-aborted-entry-short-circuits-after-materialization: en: 53362db6a0c71698 zh: 311de45ca26d3fdc diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 8ad0af1d21..3f4fbcc597 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -32,7 +32,7 @@ An around-dispatch wrapper may replace `exec.signal` for its delegated lifetime `ABORTED_BEFORE_DISPATCH` carries `{ name: 'AbortError' }` and model text `Error: tool call aborted before dispatch`. It applies whenever cancellation prevents body invocation, including pre-aborted entry, cancellation during pre-policy or approval, an aborted wrapper signal, a wrapper success overtaken by caller cancellation before delegation, and agent-loop siblings skipped after turn cancellation. -`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A denial, wrapper failure, tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. +`ABORTED` carries model text `Error: tool call aborted` and applies only after the body was invoked, including cancellation while an around wrapper or post-policy listener waits after body completion. A started body that throws the signal's reason or an `Error` named `AbortError` without `HarnessError` identity keeps that message and carries `{ name: 'AbortError', code: 'ABORTED' }`. A denial, wrapper failure, other tool failure, or post-policy failure remains more specific than generic cancellation. A timeout owned by timeout-policy remains `TOOL_TIMEOUT`, and contexts deferred before a successful outcome is replaced remain attached. ### Pre-aborted entry short-circuits after materialization diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index 613db6dacd..15856a1cce 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -32,7 +32,7 @@ Status: implemented `ABORTED_BEFORE_DISPATCH` 携带 `{ name: 'AbortError' }` 和模型可见文本 `Error: tool call aborted before dispatch`。凡取消阻止工具主体调用时都使用该结果,包括进入时已中止、前置策略或审批期间取消、包装层信号已中止、包装层在委托前返回的成功结果被调用方取消抢先,以及轮次取消后 agent loop(智能体循环)跳过的同批调用。 -`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。拒绝、包装层失败、工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 +`ABORTED` 携带模型可见文本 `Error: tool call aborted`,并且只在工具主体已经调用后使用,包括工具主体完成后环绕包装层或后置策略监听器等待期间发生的取消。已开始的工具主体抛出 signal 的 reason,或不具备 `HarnessError` 身份、name 为 `AbortError` 的 `Error` 时,结果保留该 message,并携带 `{ name: 'AbortError', code: 'ABORTED' }`。拒绝、包装层失败、其他工具失败或后置策略失败比通用取消更具体。timeout-policy 自身拥有的超时仍为 `TOOL_TIMEOUT`,成功结果被取消替换前延后附加的上下文仍会保留。 ### 进入时已中止会在物化后短路 diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml index 35d2cdc77b..d4ee6089be 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml @@ -9,8 +9,8 @@ en: a22ddcfb339e503d zh: a1f4fadb46fce1e7 /agent-note-native-cua-objects-independent-of-evaluator-ownership/decision: - en: 2780d1b0f5ce9ea8 - zh: ff986f8c1c90300f + en: 176a9c2f6040f2a1 + zh: 2617ec13d25de998 /agent-note-native-cua-objects-independent-of-evaluator-ownership/alternatives-considered: en: 3d0bc77e3c432cb9 zh: 50a20eda1811f16c diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md index f7ee24f6bc..38b074818f 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md @@ -16,13 +16,13 @@ The experimental CUA package owns a native-app subset of the Codex-style object The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. CUA defines no persistence directive, worker or run_code replacement. -Native process ownership follows the [shared helper decision](2026-10-09-cua-shared-native-helper.md), with isolated Agent connections. App handles bind process identity and kernel start time; replacing the process or helper never revives old handles. AX snapshots are scoped to an app and optional window, so independent window observations remain usable. Coordinate actions select an owned window; the Host maps [screenshot coordinates](2026-10-13-cua-hover-routes-and-coordinates.md) to native window-local points. Keyboard input remains app-scoped because macOS delivers it to the app's current focus. +Native process ownership follows the [shared helper decision](2026-10-09-cua-shared-native-helper.md), with isolated Agent connections. App handles bind process identity and kernel start time; replacing the process or helper never revives old handles. The native helper retains per-app and per-window snapshots. The [object API](2026-11-05-cua-scoped-surfaces-and-input.md) keeps the latest successful observation per application handle. Coordinate actions select an owned window; the Host maps [screenshot coordinates](2026-10-13-cua-hover-routes-and-coordinates.md) to native window-local points. Providers declare keyboard scopes in `keyboard`. macOS supports keyboard input at the application's current focus. The operation schema owns shared data declarations. Host-only limits and launch continuations remain separate from model parameters, and generated native field/enum tables preserve independent native admission without hand-maintained copies. Native code continues to own system calls, permissions and cancellation. AX formatting consumes immutable observations; the walker retains sole ownership of indices and AX references. Clipboard paste is distinct from Unicode key input: Return and Tab key events can trigger actions instead of inserting clipboard content. Pasteboard access runs on the AppKit main actor and retains promised data until a reader requests it. AX command completion alone does not establish that the application has fetched the data. Restoration checks ownership before replacing contents; the caller still verifies the application result. After successful command dispatch, `pasteReadTimeoutMs` bounds waiting for a data request, with a default of 1000 ms. Expiry returns `PASTE_NOT_CONSUMED`, closes the data provider against late delivery, and restores the clipboard only while still owned. The failure reports no read within that interval; it does not prove the application will never process its queued Paste command. A delayed command may read restored clipboard contents, so callers inspect the target and never retry automatically. Foreground-dependent consumption was observed in the installed ChatGPT/Codex application (`com.openai.codex`); other applications need their own validation. Guidance presents this as an example and applies recovery instructions to any `PASTE_NOT_CONSUMED` result. -CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The tool admits each screenshot once and renders its durable image reference; the object API, combined observation and image sink retain the same `CuaScreenshot` containing encoded `bytes`, `mimeType`, `pixelWidth`, `pixelHeight` and `windowId` from the validated screenshot result. The bridge preserves this metadata without another upload or image emission. Callers use the reported format and dimensions when saving or declaring images. +CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The tool admits each screenshot once and renders its durable image reference; the window object and image sink retain the same `CuaScreenshot` containing encoded `bytes`, `mimeType`, `pixelWidth`, `pixelHeight` and `windowId` from the validated screenshot result. The bridge preserves this metadata without another upload or image emission. Callers use the reported format and dimensions when saving or declaring images. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md index c9ac90817d..7cd542b0f7 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md @@ -16,13 +16,13 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA 对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。CUA 不定义持久化指令、执行 worker 或 run_code 替代实现。 -原生进程归属遵循[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md),Agent 连接保持隔离。应用句柄绑定进程身份及内核启动时间,替换进程或辅助进程不会使旧句柄重新有效。AX 快照按应用和可选窗口保存,不同窗口的观察可以分别使用。坐标操作选择属于该应用的窗口;Host 按[截图坐标规则](2026-10-13-cua-hover-routes-and-coordinates.zh.md)换算为原生窗口内 point。键盘输入保持应用范围,因为 macOS 将其送往应用的当前焦点。 +原生进程归属遵循[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md),Agent 连接保持隔离。应用句柄绑定进程身份及内核启动时间,替换进程或辅助进程不会使旧句柄重新有效。原生 helper 按应用和可选窗口保存快照。[对象 API](2026-11-05-cua-scoped-surfaces-and-input.zh.md) 为每个应用句柄保留最近一次成功读取的快照。坐标操作选择属于该应用的窗口;Host 按[截图坐标规则](2026-10-13-cua-hover-routes-and-coordinates.zh.md)换算为原生窗口内 point。提供方通过 `keyboard` 声明可用范围。macOS 仅支持向应用当前焦点发送键盘输入。 操作 schema 负责共享数据声明。Host 专属限制和启动续接与模型参数分开,生成的原生字段、枚举表保留独立原生校验,同时避免手工维护副本。系统调用、权限和取消仍由原生代码负责。AX 格式化只消费不可变观察数据,遍历器独自负责索引与 AX 引用。 剪贴板粘贴与 Unicode 按键输入分别实现,因为 Return 和 Tab 按键可能触发动作,而不是插入剪贴板内容。剪贴板访问使用 AppKit 主线程,保留延迟提供的数据直到读取方请求。AX 命令完成本身不能证明应用已取得数据。恢复前检查剪贴板归属;调用方仍需验证应用中的结果。 命令成功分派后,`pasteReadTimeoutMs` 限制等待数据请求的时间,默认 1000 毫秒。到期返回 `PASTE_NOT_CONSUMED`,关闭数据提供方以阻止迟到的数据交付,并仅在仍持有剪贴板时恢复原内容。该失败只说明这段时间内没有读取,不证明应用以后不会处理已排队的 Paste 命令。迟到的命令可能读取恢复后的剪贴板内容,因此调用方必须检查目标,不能自动重试。已安装的 ChatGPT/Codex 应用(`com.openai.codex`)已观察到依赖前台才能读取的行为,其他应用需要分别验证。指引将其写为例子,并对任何 `PASTE_NOT_CONSUMED` 结果提供恢复步骤。 -CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。工具只接入一次截图,再渲染持久图片引用;对象 API、组合观察和图片输出回调保留同一个 `CuaScreenshot`,其中的编码 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 来自已校验的截图结果。桥接保留这些元数据,不再次上传或输出图片。调用方落盘或声明图片时使用返回的格式和尺寸。 +CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。工具只接入一次截图,再渲染持久图片引用;窗口对象和图片输出回调保留同一个 `CuaScreenshot`,其中的编码 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 来自已校验的截图结果。桥接保留这些元数据,不再次上传或输出图片。调用方落盘或声明图片时使用返回的格式和尺寸。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml index eec374ca8a..dba92660c8 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml @@ -9,8 +9,8 @@ en: cdc04139c8d69415 zh: a3fe3e78ada08d95 /agent-note-continuous-cua-hover-without-cross-call-ownership/decision: - en: a25e8c472c084852 - zh: 12250574113e110a + en: d1ea8fdc05927896 + zh: d3039bbb82bc949c /agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered: en: 18d917ee2e909b93 zh: 5b5ad0530f138cda diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md index 37aa44d3ac..1cc8db5f81 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md @@ -10,7 +10,7 @@ Hover interactions span movement, delayed content, observation and input inside ## Decision -App and Window expose `hover` for an observed AX element or an explicit coordinate target. It never presses a mouse button; disabled controls can use system-pointer movement. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before falling back to system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check. +An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before falling back to system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check. The [shared helper](2026-10-09-cua-shared-native-helper.md) serializes complete individual operations. It grants no application ownership across calls. Earlier arrival, a retained app object and Session lifetime do not establish task priority. Waiting for the model does not reserve the application. Explicit task coordination determines any required execution order. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md index 14cac31a4f..2f5ef0ce36 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -App 和 Window 提供 `hover`,接受已观察的 AX 元素或显式坐标目标。悬停不按下鼠标按钮,禁用控件可使用系统鼠标移动路径。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,再回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。 +显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,禁用控件可使用系统鼠标移动路径。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,再回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。 [共享 helper](2026-10-09-cua-shared-native-helper.zh.md)串行执行完整的单次操作,不分配跨调用的应用所有权。先发起请求、持有 app 对象和 Session 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml index 85cccf7afa..8259c024fb 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml @@ -9,8 +9,8 @@ en: f96bf1ebc0719fb0 zh: e9a1144f0e76572d /agent-note-background-hover-and-screenshot-coordinates/decision: - en: 0f45528ea6c5988c - zh: 9bde9df417ddb1ce + en: 6ac0b77bea25fcf7 + zh: e50fec9049926fdc /agent-note-background-hover-and-screenshot-coordinates/alternatives-considered: en: 5fc4beaf79761c50 zh: 4948333b0020be28 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md index d81d964f8a..1091fcaf5e 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md @@ -12,7 +12,7 @@ Hover-only controls can sometimes be revealed without moving the user's pointer. Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route falls back to the real system pointer. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md). -Model-facing coordinate input defaults to pixels in the returned screenshot. `relative: true` accepts integer thousandths from 0 to 999 for click, hover, scroll and drag; it does not apply to AX indices. The Host owns the mapping to native window points. An application-wide observation refreshes its inventory; a scoped observation preserves other windows' image mappings. Window resizing invalidates the old image, while movement preserves local coordinates. Relative endpoints remain inside the window and do not depend on screenshot resolution. +Model-facing coordinate input defaults to pixels in the returned screenshot. `relative: true` accepts integer thousandths from 0 to 999 for `click`, `mouseMove`, `scroll` and `drag`; it does not apply to opaque element IDs. The Host owns the mapping to native window points. An application-wide observation refreshes its inventory; a scoped observation preserves other windows' image mappings. Window resizing invalidates the old image, while movement preserves local coordinates. Relative endpoints remain inside the window and do not depend on screenshot resolution. `LlmAdapter.imageRequestTarget` exposes the same dimensions and byte target used by image serialization. DeepSeek and pi-ai share their existing projection functions with this method. Other adapters preserve normalized images unless they declare resizing. Screenshot bytes returned to programs match the request image; its durable source is admitted and stored once. The native PNG metadata is checked against decoded source dimensions before any input mapping is published. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md index 2ef7ac9e44..2344d61c95 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md @@ -12,7 +12,7 @@ Status: implemented 原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时回退到真实系统鼠标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。 -面向模型的坐标默认使用返回截图中的像素。click、hover、scroll 和 drag 传入 `relative: true` 时接受 0~999 的千分比整数,不适用于 AX 索引。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。 +面向模型的坐标默认使用返回截图中的像素。`click`、`mouseMove`、`scroll` 和 `drag` 传入 `relative: true` 时接受 0~999 的千分比整数,仅用于坐标目标。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。 `LlmAdapter.imageRequestTarget` 提供与图片序列化相同的尺寸和字节目标。DeepSeek 和 pi-ai 在该方法中复用已有投影函数。其他适配器除非声明缩放,否则保留归一化图片。返回程序的截图字节与模型请求图片一致,持久原图只接入并保存一次。发布输入映射前,原生 PNG 元数据必须与解码后的原图尺寸一致。 diff --git a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.i18n.yaml deleted file mode 100644 index 5e56cbef74..0000000000 --- a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.i18n.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# Bilingual-pair consistency record for 2026-11-02-mcp-account-host-registry.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.md -/agent-note-host-registry-for-mcp-connector-accounts: - en: 6410b73bca8ec67f - zh: 458ad8ac28bb6f65 -/agent-note-host-registry-for-mcp-connector-accounts/problem: - en: 6ddb656d7fed5c6b - zh: 1215584848f5214c -/agent-note-host-registry-for-mcp-connector-accounts/decision: - en: 2652049b45deb426 - zh: 1e870763b05fffa2 -/agent-note-host-registry-for-mcp-connector-accounts/alternatives-considered: - en: b6fe7cc1b6c30770 - zh: 3c524be7ad8d0195 -/agent-note-host-registry-for-mcp-connector-accounts/consequences: - en: deb811e5c448772b - zh: ba746cfafa0ff1de diff --git a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.md b/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.md deleted file mode 100644 index f38aaaf195..0000000000 --- a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.md +++ /dev/null @@ -1,31 +0,0 @@ -# Agent Note: Host registry for MCP connector accounts - -Status: implemented - -English | [中文](2026-11-02-mcp-account-host-registry.zh.md) - -## Problem - -Connector plugins such as Linear, Notion, and Tencent Docs register an OAuth MCP server with the MCP manager on the Host and show its account on the Plugins page: a section with status and actions, a title tag, activation guidance, a sign-out confirmation, and notices. The manager already owns the authorization attempt, the grant, and the server status, and every connector needs the same surfaces. Registering each account in the browser makes each connector ship a browser half with a 41-key dictionary, 26 of whose strings are identical across connectors, and a registration that restates the server name its Host half already registered. - -## Decision - -The Host service `ctx.mcpAccounts` in [`@deepseek-ai/dsh-client-ui-mcp-account`](../../../../packages/client/ui-mcp-account/README.md) holds the accounts. A connector's Host row registers its server name, its bundle package, and the copy that names its service as `LocalizedText`. It registers inside `ctx.inject(['mcpAccounts'], …)`, so a profile without the registry, such as headless, loads the connector without the page. The Web app composition loads the registry. - -The registry serves every account with the manager's view of its server through one `mcpAccounts` Remote; authorization, cancellation, sign-out, and restart stay on the manager's Remote, which already takes the server name. One browser half renders the surfaces of every account and keeps the state that belongs to one browser: it opens an authorization page only in the browser that started the attempt, reports notices only there, and ignores clicks while its own action is pending. The 26 shared strings live in the kit dictionary. - -## Alternatives considered - -**Browser registration.** Each connector's browser half registers with a browser `ctx.mcpAccounts` under its own dictionary namespace and follows the manager stream itself. That needs one browser package per connector, which only restates what its Host half registered, and one manager stream per account in each browser. - -**Connector copy from a shared template.** One dictionary with the service name as a placeholder would remove the 15 connector-specific strings, but those strings differ in more than the name, such as what signing out removes, and Chinese spacing around a Latin name depends on its position. Each connector supplies them as `LocalizedText` instead. - -**Actions through the registry.** The registry could route `startAuthorization` and the other actions by package. The manager's Remote already takes the server name, so routing would add a second action surface without a new check. - -**A base shared with CLI accounts.** The CLI account registry also registers Host accounts for the Plugins page, but MCP accounts follow the manager's fixed authorization states while CLI accounts present each vendor's own states. A shared base would couple the two registries without removing code from either. - -## Consequences - -A connector ships no browser code for its account; its Host row registers the account and the kit renders it. Each browser opens one stream for all accounts, which follows one manager stream on the Host. A connector whose Host row fails to load shows no account section, while the Plugins page still lists the bundle with its load failure. - -Host specs pin registration, the refusal of a second account per package or server, the merge with the manager's stream, its failure and end, and unload. Client specs pin authorization page opening in the starting browser, notices, the pending-action guard, and each account's slot registrations and their removal. diff --git a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.zh.md deleted file mode 100644 index 2df2e2929d..0000000000 --- a/.agents/notes/implemented/architecture/2026-11-02-mcp-account-host-registry.zh.md +++ /dev/null @@ -1,31 +0,0 @@ -# Agent Note: MCP 连接器账号的 Host 注册表 - -Status: implemented - -[English](2026-11-02-mcp-account-host-registry.md) | 中文 - -## 问题 - -Linear、Notion、腾讯文档等连接器插件在 Host 上向 MCP 管理器注册 OAuth MCP 服务器,并在插件页面显示其账号:带状态和操作的区块、标题标签、开启后的引导、退出登录确认和提示。管理器已经持有授权尝试、grant 和服务器状态,而每个连接器都需要同样的界面。在浏览器中注册账号,会让每个连接器都提供一个浏览器一侧:其中一份 41 个 key 的字典有 26 条文案在各连接器间完全相同,另有一次注册重复其 Host 一侧已注册的服务器名。 - -## 决定 - -[`@deepseek-ai/dsh-client-ui-mcp-account`](../../../../packages/client/ui-mcp-account/README.zh.md) 中的 Host 服务 `ctx.mcpAccounts` 保存账号。连接器的 Host 行注册其服务器名、bundle 包名,以及以 `LocalizedText` 表示的、指明其服务的文案。注册放在 `ctx.inject(['mcpAccounts'], …)` 中,因此没有注册表的 profile(如 headless)加载连接器时不带页面。Web 应用组合加载注册表。 - -注册表通过一个 `mcpAccounts` Remote 提供所有账号,并附上管理器对其服务器的视图;授权、取消、退出登录和重启仍走管理器的 Remote,它本来就接受服务器名。一个浏览器一侧渲染所有账号的界面,并保存属于单个浏览器的状态:只在发起尝试的浏览器中打开授权页面,只在那里报告提示,并在自身操作未完成时忽略点击。26 条共用文案放在套件字典中。 - -## 考虑过的替代方案 - -**浏览器注册。** 每个连接器的浏览器一侧以自己的字典命名空间向浏览器中的 `ctx.mcpAccounts` 注册,并自行跟随管理器流。这需要每个连接器一个浏览器包,而它只是重复其 Host 一侧已注册的内容,并且每个浏览器中每个账号各开一条管理器流。 - -**用共享模板生成连接器文案。** 用一份以服务名为占位符的字典可以去掉 15 条连接器专属文案,但这些文案不只服务名不同,例如退出登录会删除什么;而且中文里拉丁文名称两侧的空格取决于其位置。因此由各连接器以 `LocalizedText` 提供这些文案。 - -**通过注册表执行操作。** 注册表可以按包路由 `startAuthorization` 等操作。管理器的 Remote 本来就接受服务器名,路由只会多出第二个操作入口,而不增加任何检查。 - -**与 CLI 账号共用基座。** CLI 账号注册表同样为插件页面注册 Host 账号,但 MCP 账号遵循管理器固定的授权状态,而 CLI 账号呈现各厂商自己的状态。共用基座会把两个注册表耦合起来,却不能从任一方删去代码。 - -## 影响 - -连接器不为账号提供任何浏览器代码;其 Host 行注册账号,由套件渲染。每个浏览器为所有账号打开一条流,它在 Host 上跟随一条管理器流。Host 行加载失败的连接器不显示账号区块,而插件页面仍列出该 bundle 及其加载失败。 - -Host 测试固定注册、同一包或服务器的第二个账号被拒绝、与管理器流的合并及其失败和结束,以及卸载。客户端测试固定只在发起尝试的浏览器中打开授权页面、提示、未完成操作保护,以及每个账号的插槽注册及其移除。 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml new file mode 100644 index 0000000000..f3a0d8f1d3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-05-cua-scoped-surfaces-and-input.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +/agent-note-cua-scoped-surfaces-and-separated-input-capabilities: + en: a0a2e9d0651e212f + zh: b7a2ab4092c2595b +/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/problem: + en: f72db0b79aa02fb5 + zh: b91c1f177dc93ab4 +/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: + en: ec115e11f96ffe60 + zh: c1fe9eb2866196d0 +/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: + en: 32c970ae153e0f6c + zh: 8431be0a10ffed15 +/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: + en: 5c6ec60b77f1bff0 + zh: e1ae568ef3501b7b diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md new file mode 100644 index 0000000000..609e5bf901 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -0,0 +1,39 @@ +# Agent Note: CUA scoped surfaces and separated input capabilities + +Status: implemented + +English | [中文](2026-11-05-cua-scoped-surfaces-and-input.zh.md) + +## Problem + +Application and window objects share accessibility operations, but only an explicit window can capture or deliver pointer input. Duplicating shared methods on both factories creates two implementations to keep aligned. Moving application-only capability checks into the shared base makes window behavior depend on an application-level decision. Keyboard input has the same problem at a smaller scale: a chord string combines a key and its modifiers, and a complete-keystroke method cannot express a modifier held across calls or a standalone key-up. + +## Decision + +`CuaSurface` declares operations shared by application and window objects; `CuaApp` and `CuaWindow` extend it with their own operations. One base factory builds the surface, and the derived factories inject scope parameters plus `requireAccessibility` and `requireKeyboard` checks. The shared base never branches on a capability that exists only for applications. + +Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. + +Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. + +Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. + +## Alternatives considered + +**Duplicate application and window methods** would give each factory its own implementation of the same accessibility operations. Every shared change would then need matching edits, and the two surfaces could accept different arguments or results. One `CuaSurface` implementation keeps that behavior single. + +**An application-specific branch in the shared base** would let window objects inherit decisions and capability checks that apply only to applications. Scope factories that inject their own requirements keep the shared operations independent of which scope uses them. + +**A packed chord string** requires parsing key names, separators, and plus escaping together, and it pushes platform alias normalization into the shared layer. Keystroke and direction are separate semantics: `pressKey` describes one complete keystroke, while `sendKeyEvent` describes one explicit direction. Separate key and modifier values keep those semantics without a parser. + +**Platform keyboard key enumerations in the shared schema** would couple the portable operation schema to one provider's key names and require a schema change for each platform. Provider-defined strings let the provider interpret its own names while the shared schema stays neutral. + +**Static capabilities reported by native** would duplicate provider configuration in the native helper and make the helper responsible for knowledge that is fixed before it starts. The helper reports runtime state; the provider owns its startup capabilities. + +## Consequences + +Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. + +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, because the API never sends the opposite event. Keyboard modifier names are provider-defined, so the same string may have different support across providers. + +Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md new file mode 100644 index 0000000000..081f02986e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -0,0 +1,39 @@ +# Agent Note: CUA 作用域表面与分离的输入能力 + +Status: implemented + +[English](2026-11-05-cua-scoped-surfaces-and-input.md) | 中文 + +## 问题 + +应用对象和窗口对象共享辅助功能操作,但只有显式窗口能截图或发送指针输入。若在两个工厂上分别复制共享方法,就会出现两套需要同步的实现。把只适用于应用的能力检查放进共享基类,会让窗口行为依赖应用级判断。键盘输入也有同样的问题:组合键字符串把按键与修饰键混在一起,完整击键方法无法表达跨调用保持修饰键或单独抬起按键。 + +## 决策 + +`CuaSurface` 声明应用对象与窗口对象共享的操作;`CuaApp` 与 `CuaWindow` 通过扩展它增加各自的操作。一个基类工厂负责构建表面,派生工厂注入作用域参数以及 `requireAccessibility`、`requireKeyboard` 检查。共享基类从不为只属于应用的能力分支。 + +Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 + +键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 + +在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 + +## 考虑过的替代方案 + +**在应用和窗口上重复方法**会让每个工厂各自实现同一套辅助功能操作。每次共享改动都需要成对修改,两个表面还可能接受不同的参数或结果。单一 `CuaSurface` 实现让这份行为只有一处。 + +**在共享基类中加入应用专属分支**会让窗口对象继承只适用于应用的决定和能力检查。由各作用域工厂注入自己的要求,可以让共享操作不依赖使用它的作用域。 + +**打包的组合键字符串**需要一起解析按键名、分隔符和加号转义,并把平台别名归一化推入共享层。击键与方向是两种语义:`pressKey` 描述一次完整击键,`sendKeyEvent` 描述一个显式方向。分开的按键和修饰键值让这些语义无需解析器。 + +**在共享 schema 中枚举平台键盘按键**会把可移植的操作 schema 绑定到某个 provider 的按键名,并让每个平台都修改 schema。由 provider 定义字符串,平台可以解释自己的名称,共享 schema 保持中立。 + +**由原生报告静态能力**会在原生 helper 中重复 provider 配置,并让 helper 负责它在启动前就固定的知识。helper 报告运行时状态;启动能力由 provider 负责。 + +## 影响 + +元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 + +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 + +Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.i18n.yaml new file mode 100644 index 0000000000..25c6eefe08 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-05-harness-error-dependency-free-base.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.md +/agent-note-keep-the-harnesserror-base-in-a-dependency-free-package: + en: 6ff178be521c3318 + zh: 18a9a8cc261fe975 +/agent-note-keep-the-harnesserror-base-in-a-dependency-free-package/problem: + en: 29880462facde90c + zh: d07805b2000c85b1 +/agent-note-keep-the-harnesserror-base-in-a-dependency-free-package/decision: + en: caec42054c040d37 + zh: d726f0da57dc1e68 +/agent-note-keep-the-harnesserror-base-in-a-dependency-free-package/alternatives-considered: + en: 8245e473d4e90250 + zh: fe7883dfe13070a9 +/agent-note-keep-the-harnesserror-base-in-a-dependency-free-package/consequences: + en: 9a577f5c3bb9fa15 + zh: 4c18ec885768b9d3 diff --git a/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.md b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.md new file mode 100644 index 0000000000..9c79c374f2 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.md @@ -0,0 +1,31 @@ +# Agent Note: Keep the HarnessError base in a dependency-free package + +Status: implemented + +English | [中文](2026-11-05-harness-error-dependency-free-base.zh.md) + +## Problem + +The tool registry records a failed result's `error.name` and `error.code` only when the thrown value is `instanceof HarnessError`, so every expected failure must extend the one shared class; copying its `code` field is not enough. The [archived structured-error-taxonomy note](../../archived/architecture/2026-06-11-structured-error-taxonomy.md) placed the base in `dsh-llm` because `dsh-llm` was then a leaf that every package already imported, so the base added no dependency edge. + +`dsh-llm` stopped being a leaf. `ImageBlock` references `ImageAttachmentRef` from `dsh-attachment`, and `dsh-llm` depends on `dsh-typert-protocol`. A class in either lower package cannot extend a base defined in `dsh-llm` without a TypeScript project-reference cycle, so `AttachmentError` and `RemoteError` re-implement the `code` field on plain `Error`, and tool failures that carry them persist without structured identity. + +## Decision + +`HarnessError` lives in `@deepseek-ai/dsh-error` (`packages/util/error`), a package with no dependencies that contains only the base class. `dsh-llm` depends on it and re-exports the same class from its entry, so existing `import { HarnessError } from '@deepseek-ai/dsh-llm'` statements keep working and both import paths name one constructor, which keeps `instanceof` checks consistent. LLM-specific failure codes and helpers such as `isHarnessError` stay in `dsh-llm`. + +New code imports `HarnessError` from `dsh-error` when the importing package does not otherwise need `dsh-llm`, so a package that needs only the base takes no dependency on the LLM runtime. Packages below `dsh-llm`, such as `dsh-attachment`, can extend the base without a cycle. + +## Alternatives considered + +**Keep the base in `dsh-llm`.** Lower packages would keep re-implementing the field shape, and the registry would keep dropping their codes; recognizing those shapes structurally in the registry would make it trust any object with a string `code`, including Node errno values. + +**Recognize specific classes in the registry.** Matching `RemoteError` or `AttachmentError` by marker would add a dependency from `dsh-tools` to each package and repeat for every new low-level error class. + +**Move the base to an existing utility package.** `dsh-util-values` and `dsh-brand` have unrelated roles; a dedicated package names the role and keeps the base free of their dependencies and change history. + +**Drop the `dsh-llm` re-export.** Every existing import would have to change in one step without a behavior benefit. + +## Consequences + +Any package can extend `HarnessError`, including packages that `dsh-llm` depends on, and the base no longer changes with the LLM runtime. The cost is one more published package and one more dependency edge for `dsh-llm`. Two import paths exist for one class; both are supported, and the error-handling rules name `dsh-error` as the home. diff --git a/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.zh.md b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.zh.md new file mode 100644 index 0000000000..8ff0c999bb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-05-harness-error-dependency-free-base.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 把 HarnessError 基类放在无依赖的包中 + +Status: implemented + +[English](2026-11-05-harness-error-dependency-free-base.md) | 中文 + +## 问题 + +工具注册表只有在抛出值 `instanceof HarnessError` 时,才会在失败结果上记录 `error.name` 与 `error.code`,因此每种预期失败都必须继承这一个共享类;只复制它的 `code` 字段不够。[已归档的结构化错误分类决策](../../archived/architecture/2026-06-11-structured-error-taxonomy.md)把基类放在 `dsh-llm` 中,因为当时 `dsh-llm` 是所有包都已导入的叶子包,放在那里不会增加依赖边。 + +`dsh-llm` 后来不再是叶子包。`ImageBlock` 引用了 `dsh-attachment` 的 `ImageAttachmentRef`,`dsh-llm` 还依赖 `dsh-typert-protocol`。这两个更底层的包中的类无法继承定义在 `dsh-llm` 里的基类,否则 TypeScript 项目引用会成环,因此 `AttachmentError` 与 `RemoteError` 只能在普通 `Error` 上重复实现 `code` 字段,携带它们的工具失败在持久化时没有结构化身份。 + +## 决策 + +`HarnessError` 位于 `@deepseek-ai/dsh-error`(`packages/util/error`)。这个包没有任何依赖,只包含该基类。`dsh-llm` 依赖它,并从自身入口重新导出同一个类,因此现有的 `import { HarnessError } from '@deepseek-ai/dsh-llm'` 继续可用,两种导入路径指向同一个构造函数,`instanceof` 判断保持一致。LLM 专属的失败码以及 `isHarnessError` 等辅助函数仍留在 `dsh-llm`。 + +当导入方本身不需要 `dsh-llm` 时,新代码从 `dsh-error` 导入 `HarnessError`,这样只需要基类的包不必依赖 LLM 运行时。`dsh-attachment` 等位于 `dsh-llm` 之下的包可以继承该基类而不形成依赖环。 + +## 考虑过的替代方案 + +**把基类留在 `dsh-llm`。** 底层包会继续重复实现字段结构,注册表也会继续丢弃它们的 code;如果让注册表按结构识别这类对象,它就会信任任何带字符串 `code` 的对象,包括 Node errno 值。 + +**在注册表中识别特定类。** 按标记匹配 `RemoteError` 或 `AttachmentError` 会让 `dsh-tools` 依赖每个这样的包,而且每出现一个新的底层错误类都要重复一次。 + +**把基类移到现有的工具包。** `dsh-util-values` 与 `dsh-brand` 的职责与此无关;独立的包能准确命名职责,也让基类不受它们的依赖与变更历史影响。 + +**去掉 `dsh-llm` 的重新导出。** 所有现有导入都得一次性修改,却不带来任何行为收益。 + +## 后果 + +任何包都可以继承 `HarnessError`,包括 `dsh-llm` 所依赖的包,基类也不再随 LLM 运行时一起变更。代价是多发布一个包,`dsh-llm` 多一条依赖边。同一个类有两种导入路径,两者都受支持,错误处理规则把 `dsh-error` 作为它的归属位置。 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml new file mode 100644 index 0000000000..121a9d669b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-06-connector-account-registry.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts: + en: 3950421fb526f6b7 + zh: 47c5f6cc4b735058 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/problem: + en: 2a7b59cd509a0b9a + zh: 38130ce17829342d +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/decision: + en: d96b43106a1ba837 + zh: 97bc8f9436ec07d0 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/alternatives-considered: + en: ee0aa3f9ea40ef15 + zh: fded69a6dcc8ca87 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/consequences: + en: 5228f32becfbdec3 + zh: 013f1073e70d46f7 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md new file mode 100644 index 0000000000..93138b065e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md @@ -0,0 +1,42 @@ +# Agent Note: One Host registry and one browser half for connector accounts + +Status: implemented + +English | [中文](2026-11-06-connector-account-registry.zh.md) + +## Problem + +Connector plugins show an account section on the Plugins page. CLI app plugins keep the account in their vendor CLI; MCP connectors keep an OAuth grant through the MCP manager. Both kinds need the same surfaces: a bundle's section, title tag, and activation prompt, a confirmation before an action that changes the account outside DSH, and a notice in the browser that started the operation. A client plugin cannot share runtime code with another feature plugin ([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) rule 3), so one browser half per connector kind duplicates the same code and lets the copies drift. When the browser decides an account's state or relays an identifier from one Remote to another, the Host can no longer run the flow without the browser. + +## Decision + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.md) provides one Host registry, `ctx.connectorAccounts`, one `connectorAccounts` Remote, and one browser half for every connector kind. + +| Part | Contract | +|---|---| +| Registration | `register({ key, packageName?, source, operations, copy, present })` returns the disposer that withdraws the account | +| Key | Unique among registered accounts and independent of the package, so an account that no bundle owns, such as a server configured in Settings, registers too | +| Package | Decides which bundle page carries the section and tag; a package carries at most one account | +| Source | The registrant's account: `snapshot`, `observe`, `refresh`, `start`, and `cancel` | +| Display | `present(view)` on the Host gives the phase, status text, title tag, buttons and their commands, confirmations, failure, and the operation the activation prompt starts | +| Remote | `watch`, plus `start(key, operation)` and `cancel(key, id)`, which route by key to the account's source | + +The Host decides everything except opening the authorization page. The browser never learns how an account connects: it receives only the display, the operation in progress with its authorization page, and the latest result with its success text. The browser half keeps only what belongs to one browser: the operations it started, so their authorization pages open and their success is reported only there; the latest notice; and whether its stream is delivering. Buttons call `start` and `cancel` on the Remote themselves, and each surface keeps its own pending state. + +The page registers one title tag entry and one notice entry. It also registers a section and an activation prompt for each account that names a package, because those two slots are keyed by package. + +## Alternatives considered + +**Two registries behind one browser half.** Rejected: the browser would follow both Remotes and choose which one each button calls, which relays between Host services again, and the two Host registries would hold the same code. + +**One browser half per connector kind.** Rejected: client plugins cannot import each other's values, so the shared surfaces would be written twice and diverge. + +**Share the browser half through `PLATFORM_MODULES` or a browser-side service.** Rejected: the module table is reserved for shell-seeded and static infrastructure libraries, and a browser-side service would keep the registrations in the browser, which only repeat what the Host knows. + +**Let the browser derive an account's phase and actions from the registrant's raw state.** Rejected: the rules for which actions apply would live where the Host cannot test or run them, and the browser would need the registrant's own Remote. + +## Consequences + +The registry and browser half exist once. A new connector kind writes a source and `present` on the Host and needs no browser code. The account rules live beside the services that own them, and the Host can run every operation without a browser. + +Registrants map their account states onto five phases (checking, connecting, connected, disconnected, unavailable); a state outside them shows through its status text and detail. The Web and Desktop compositions load the registry whether or not a connector plugin is installed. An authorization page that opens after the start call answers can be blocked by the browser; the section's open button shows it again. diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md new file mode 100644 index 0000000000..e2c7a56b41 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md @@ -0,0 +1,42 @@ +# Agent Note:连接器账号使用一个 Host 注册表和一个浏览器一半 + +Status: implemented + +[English](2026-11-06-connector-account-registry.md) | 中文 + +## 问题 + +连接器插件会在插件页显示账号区块。CLI 应用插件的账号保存在厂商 CLI 中;MCP 连接器通过 MCP 管理器保存 OAuth 授权。两类插件需要同样的界面:插件包的区块、标题旁标签和开启引导,在会改变 DSH 之外账号状态的操作前确认,以及只在发起操作的浏览器中显示的提示。客户端插件不能与其他功能插件共享运行时代码([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) 第 3 条),因此每类连接器各有一个浏览器一半,就会把同样的代码写两遍,副本还会逐渐不一致。如果由浏览器决定账号状态,或在两个 Remote 之间转发标识,Host 就无法在没有浏览器的情况下完成流程。 + +## 决定 + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.zh.md) 为所有连接器类型提供一个 Host 注册表 `ctx.connectorAccounts`、一个 `connectorAccounts` Remote 和一个浏览器一半。 + +| 部分 | 约定 | +|---|---| +| 注册 | `register({ key, packageName?, source, operations, copy, present })` 返回撤下账号的销毁函数 | +| 键 | 在已注册账号中唯一,且与包无关,因此没有插件包承载的账号(如在 Settings 中配置的服务器)也能注册 | +| 包 | 决定由哪个插件包页面承载区块和标签;一个包最多承载一个账号 | +| 来源 | 注册方的账号:`snapshot`、`observe`、`refresh`、`start` 和 `cancel` | +| 展示 | Host 上的 `present(view)` 给出阶段、状态文字、标题旁标签、按钮及其命令、确认、失败信息,以及开启引导启动的操作 | +| Remote | `watch`,以及按键路由到账号来源的 `start(key, operation)` 和 `cancel(key, id)` | + +除了打开授权页,其余都由 Host 决定。浏览器不知道账号如何连接:它只收到展示内容、进行中的操作及其授权页,以及带成功文本的最新结果。浏览器一半只保存属于本浏览器的东西:它发起的操作(授权页只在这里打开,成功只在这里报告)、最新提示,以及它的流是否在推送。按钮自己调用 Remote 的 `start` 和 `cancel`,每个界面自己保存未完成状态。 + +页面只注册一个标题旁标签条目和一个提示条目;对每个带包名的账号,再注册一个区块和一个开启引导,因为这两个插槽以包为键。 + +## 考虑过的替代方案 + +**一个浏览器一半背后有两个注册表。** 否决:浏览器要同时跟随两个 Remote,并为每个按钮选择调用哪一个,这又是在 Host 服务之间转发;两个 Host 注册表的代码也会相同。 + +**每类连接器各有一个浏览器一半。** 否决:客户端插件不能导入彼此的值,共用界面就要写两遍,并逐渐不一致。 + +**通过 `PLATFORM_MODULES` 或浏览器端服务共享浏览器一半。** 否决:模块表只留给由 shell 预置的基础设施和静态库;浏览器端服务会把注册留在浏览器中,而这些注册只是重复 Host 已知的信息。 + +**由浏览器根据注册方的原始状态推算账号阶段和操作。** 否决:哪些操作可用的规则会放在 Host 无法测试和执行的地方,浏览器还需要注册方自己的 Remote。 + +## 后果 + +注册表和浏览器一半只有一份。新的连接器类型只需在 Host 上编写来源和 `present`,不需要浏览器代码。账号规则与拥有它们的服务在一起,Host 不依赖浏览器就能执行每个操作。 + +注册方需要把账号状态映射到五个阶段(检查中、连接中、已连接、未连接、不可用);超出这些阶段的状态通过状态文字和说明表达。无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml new file mode 100644 index 0000000000..ff89d65c02 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-08-mcp-connector-accounts.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md +/agent-note-mcp-connector-accounts-in-the-connector-account-registry: + en: de9535f7ca161ae3 + zh: 50be52d2946e2058 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/problem: + en: 3fcafe54fc134ff3 + zh: bbef331a0d9eccd5 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/decision: + en: 438e69f9a0d0dc87 + zh: 990a9e96aafbd532 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/alternatives-considered: + en: 0b7871c3d4aa7c52 + zh: c26061baed87bee4 +/agent-note-mcp-connector-accounts-in-the-connector-account-registry/consequences: + en: c90b9de7c3b4e662 + zh: 7e126b5ac0f3e59e diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md new file mode 100644 index 0000000000..b883f0e758 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.md @@ -0,0 +1,35 @@ +# Agent Note: MCP connector accounts in the connector account registry + +Status: implemented + +English | [中文](2026-11-08-mcp-connector-accounts.zh.md) + +## Problem + +Connector plugins such as Linear, Notion, and Tencent Docs register an OAuth MCP server with the MCP manager on the Host and show its account on the Plugins page. The manager already owns the authorization attempt, the grant, and the server status, and every connector shares the same states, buttons, and 23 strings. The [connector account registry](2026-11-06-connector-account-registry.md) shows each account from a Host source and presenter, so MCP needs one adapter that turns the manager's view of a server into that source and presenter. + +## Decision + +[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.md) provides `ctx.mcpAccounts`. A connector's Host row registers its server name, its bundle package, and the copy that names its service; the service registers the account with `ctx.connectorAccounts` under the key `mcp:`. + +| Part | Choice | +|---|---| +| Source | Reads the manager's `list()` entry for the server and observes `mcp-manager/status`; `refresh` does nothing, because the manager publishes every change | +| Operation | A running authorization attempt is the operation and its identity is the operation's, so the browser that started it follows the manager's own attempt; a finished attempt is the result | +| Page operations | `connect` starts authorization; `sign-out` and `retry` sign out and restart through the manager and report their own result once they finish | +| Phases | Waiting for the browser and authorizing are connecting; a server that needs authorization again is disconnected, with the reason in its detail; a closed, waiting, disabled, or failed server is unavailable, with Retry only where a restart recovers it | +| Copy | The 23 strings every connector shares are Host dictionaries in eight languages; each connector supplies only the strings that name its service | + +The manager's `startAuthorization`, `cancelAuthorization`, and `signOut` are Host methods without a Remote, so no browser names a server to authorize. + +## Alternatives considered + +**Keep the manager's authorization operations on its Remote.** Rejected: the page would pass a server name the Host already holds, and two paths would start the same attempt. + +**Track an adapter-owned operation for each authorization.** Rejected: the manager already tracks the attempt's identity, phases, and authorization page, so a second tracker would restate it. The registry lets a source answer `start` once the manager has created the attempt. + +**Key each connector's account by its package.** Rejected: the server name is unique among MCP accounts, so the key also refuses a second account for one server, and a server configured in Settings, which no bundle owns, uses the same form. + +## Consequences + +A connector ships no browser code and no page rules; the shared page renders its account. An account that needs reconnection shows as disconnected without a separate warning color, and its status and detail name the reason. Each browser follows the one registry stream, and the Host follows the manager through its status event. diff --git a/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md new file mode 100644 index 0000000000..f0d0b103e2 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-08-mcp-connector-accounts.zh.md @@ -0,0 +1,35 @@ +# Agent Note:MCP 连接器账号接入连接器账号注册表 + +Status: implemented + +[English](2026-11-08-mcp-connector-accounts.md) | 中文 + +## 问题 + +Linear、Notion、腾讯文档等连接器插件在 Host 上向 MCP 管理器注册 OAuth MCP 服务器,并在插件页显示其账号。管理器已经持有授权尝试、grant 和服务器状态,各连接器的状态、按钮和 23 条文案都相同。[连接器账号注册表](2026-11-06-connector-account-registry.zh.md)根据 Host 上的来源和展示函数显示每个账号,因此 MCP 需要一个适配,把管理器对服务器的视图转换为这样的来源和展示函数。 + +## 决定 + +[`@deepseek-ai/dsh-mcp-account`](../../../../packages/mcp/mcp-account/README.zh.md) 提供 `ctx.mcpAccounts`。连接器的 Host 行注册其服务器名、插件包以及点出服务名称的文案;该服务以 `mcp:` 为键,把账号注册到 `ctx.connectorAccounts`。 + +| 部分 | 选择 | +|---|---| +| 来源 | 读取管理器 `list()` 中该服务器的条目,并观察 `mcp-manager/status`;`refresh` 什么也不做,因为管理器会发布每次变化 | +| 操作 | 进行中的授权尝试就是操作,其 id 就是操作的 id,因此发起它的浏览器跟随的是管理器自己的尝试;结束的尝试就是结果 | +| 页面操作 | `connect` 发起授权;`sign-out` 和 `retry` 通过管理器退出登录、重启服务器,结束后报告各自的结果 | +| 阶段 | 等待浏览器和授权中属于连接中;需要重新授权的服务器属于未连接,原因写在说明里;已关闭、等待凭据、已停用或失败的服务器属于不可用,只有重启能恢复时才提供“重试” | +| 文案 | 各连接器共用的 23 条文案是 Host 上 8 种语言的字典;每个连接器只提供点出其服务名称的文案 | + +管理器的 `startAuthorization`、`cancelAuthorization` 和 `signOut` 是不带 Remote 的 Host 方法,因此浏览器不会指定要授权的服务器。 + +## 考虑过的替代方案 + +**管理器的授权操作继续走它的 Remote。** 否决:页面要传入 Host 已经知道的服务器名,而且会有两条路径发起同一次尝试。 + +**为每次授权维护适配自己的操作。** 否决:管理器已经记录尝试的 id、阶段和授权页,第二套记录只会重复它。注册表允许来源在管理器创建尝试后再回答 `start`。 + +**以插件包作为连接器账号的键。** 否决:服务器名在 MCP 账号中唯一,因此这个键也会拒绝同一服务器的第二个账号;没有插件包的、在 Settings 中配置的服务器也使用同样的键。 + +## 影响 + +连接器不提供任何浏览器代码和页面规则,由共用的页面渲染其账号。需要重新连接的账号显示为未连接,不再单独使用警示色,其状态和说明会点出原因。每个浏览器跟随同一条注册表流,Host 通过管理器的状态事件跟随管理器。 diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml index 5d4fc0da67..d8bd3470b9 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.i18n.yaml @@ -9,14 +9,14 @@ en: 7115cbaefaa11d2d zh: 23aff8797a651a36 /agent-note-settings-driven-mcp-server-manager/decision: - en: 7b7afbd37320e89a - zh: 36a308b3143350d9 + en: ac7cc4c046ca2377 + zh: 697233f3b09759de /agent-note-settings-driven-mcp-server-manager/alternatives-considered: - en: 26534ceaccf1f5b9 - zh: 882e38f8b3f9787f + en: 1154a35a2f9af53f + zh: 92ad94d6306463bb /agent-note-settings-driven-mcp-server-manager/testing: en: cbfd30400093ade5 zh: 018ad32e25c6c7fc /agent-note-settings-driven-mcp-server-manager/consequences: - en: 40419dfbc2f69ac3 - zh: 853c978d285c3310 + en: 078ddb6329aae177 + zh: dc2b2f3c457feb53 diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md index aeb5b994c8..c77fbb57e4 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.md @@ -20,9 +20,9 @@ Installed application plugins also bring their own servers. Each must add its se **A flat entry schema, validated cross-field.** The entry is flat with a `transport` discriminant, and write-time validation enforces the per-transport requirements and rejections (missing `command`/`url`, cross-transport fields, malformed templates) at the write — a schema-valid-but-unserviceable entry is never stored, and refusals name the offending field where a union's shape error would not. -**Children are plugin instances, not library calls.** Each enabled entry is a `dsh-mcp-client` instance that the MCP client host mounts below its own fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets the manager unmount every instance it mounted when it stops. +**Children are plugin instances, not library calls.** Each enabled entry is a `dsh-mcp-client` instance that the MCP client host mounts under the manager's fiber via `ctx.plugin()`. That reuses the tested activation/disposal semantics, makes `serverName` reservations collide correctly with statically composed instances (surfaced as a `failed`/`load` status with the actionable message), and lets manager disposal unwind every instance and its tools through ordinary fiber teardown. -**The MCP client host is the manager's only reach into mcp-client.** An mcp-client entry loaded with `host: true` provides `ctx.mcpClientHost`, and the manager injects it and imports only mcp-client types. The host validates an entry's client fields through each transport's own schema, so refusals still name the field; mounts instances below itself; probes; and creates authorization owners from its own context. Plugin entries export only what the Loader loads, and HMR reloads mcp-client as its own unit: replacing the host disposes the instances below it, and Cordis restarts the manager against the replacement, so the manager never keeps a replaced module's code or instances. +**The MCP client host is the manager's only reach into mcp-client.** The manager creates an `McpClientHost` at construction and imports only that class and mcp-client types. The host validates an entry's client fields through each transport's own schema, so refusals still name the field; mounts instances under the manager's fiber; probes; and creates authorization owners from the manager's context. A plugin entry exports what the Loader loads and its Service and error classes, so the host is a Service class rather than a set of functions. **Whole-entry identity; `enabled` controls mounting.** A changed entry rebuilds the child instance; disabling or deleting it disposes the child. Reconciliation and `restart` serialize on one operation tail. Probes run independently, and configuration changes cancel affected probes before queued cleanup waits for them. The manager retains a failed cleanup record and refuses a replacement until the Host restarts, preventing overlapping server lifetimes. @@ -50,9 +50,9 @@ Installed application plugins also bring their own servers. Each must add its se **Poll status from the management surface.** Rejected: the Remote plane already forwards Host events; peers that shipped polling (Reasonix) or lacked a status event (OpenCode v1) treat it as a defect to fix. -**Export validation, probe, status, and authorization values from the mcp-client entry.** Rejected: plugin entries export only what the Loader loads. A manager that imports another plugin's values keeps the module it loaded first; when mcp-client also has its own Loader entry, a reload replaces only mcp-client, and HMR also replaces the instances the manager mounted through that plugin without the manager knowing, which leaves stale status and an instance the manager cannot stop. +**Export validation, probe, status, and authorization values from the mcp-client entry.** Rejected: plugin entries export what the Loader loads and their Service and error classes, not helper values. -**A Service Definition in mcp-client that the manager extends to inherit probe and authorization.** Rejected: the subclass extends the base it imported, so after a reload it still runs the replaced code, and instances it mounts through its own import are replaced behind it as above. +**Load the host as its own mcp-client entry with `host: true` that the manager injects.** Rejected: every composition that loads the manager would need a second row, and the client's configuration would carry a shape that connects no server. Its only gain, a manager that restarts when mcp-client reloads during development, does not justify either. **Move the connection machinery into a separate service package.** Rejected: per-server mcp-client instances use the same machinery, so every composition that loads mcp-client would also have to load the new service. @@ -68,5 +68,5 @@ mcp-client unit tests cover status transitions, independent startup and probe bu - Liveness relies on transport closure and request failures; a Streamable HTTP server that stalls without closing is noticed when a request fails. - A rebuilt server’s tools remain unavailable until the replacement completes its initial sync. Replacement waits for confirmed transport closure and successful local cleanup. - The manager governs the global plane only; preset-scoped and static instances stay outside its list. -- A composition that loads the manager also loads an mcp-client entry with `host: true`; without it the manager stays pending. A reload of mcp-client restarts the manager, which remounts its servers. +- The manager keeps the mcp-client code it loaded until the manager itself reloads; a development reload of mcp-client alone does not restart it. - `startupTimeoutMs` bounds startup attempts, while notification-driven re-sync requests still ride the SDK's request default — recorded as an mcp-client limitation. diff --git a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md index f56719a090..31890b1998 100644 --- a/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md +++ b/.agents/notes/implemented/feature/2026-08-31-mcp-manager-plugin.zh.md @@ -20,9 +20,9 @@ Status: implemented **扁平条目 schema,跨字段校验。** 条目是带 `transport` 判别字段的扁平结构,写入期校验在写入处强制逐传输要求与拒绝(缺 `command`/`url`、跨传输字段、模板写错)——schema 合法但不可执行的条目永远不会被存下,且拒绝会点名出错字段,union 的形状错误做不到。 -**子实例是插件实例,不是库调用。** 每个启用条目都是 MCP 客户端宿主经 `ctx.plugin()` 挂在其自身 fiber 下的 `dsh-mcp-client` 实例。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器停止时卸载它挂载的每个实例。 +**子实例是插件实例,不是库调用。** 每个启用条目都是 MCP 客户端宿主经 `ctx.plugin()` 挂在管理器 fiber 下的 `dsh-mcp-client` 实例。这复用了经过测试的激活/销毁语义,让 `serverName` 预留与静态组合实例正确冲突(以带可操作消息的 `failed`/`load` 状态浮出),并让管理器销毁时经普通 fiber 收卷撤下每个实例及其工具。 -**MCP 客户端宿主是管理器接触 mcp-client 的唯一途径。** 以 `host: true` 加载的 mcp-client 条目提供 `ctx.mcpClientHost`,管理器注入它,并且只从 mcp-client 导入类型。宿主用各传输自己的 schema 校验条目的客户端字段,因此拒绝时仍点名字段;它把实例挂在自己之下、执行探测,并用自身 context 创建授权所有者。插件入口只导出 Loader 加载的内容,而 HMR 把 mcp-client 作为独立单元重载:替换宿主会销毁它之下的实例,Cordis 让管理器在替换后的宿主上重启,因此管理器不会保留被替换模块的代码或实例。 +**MCP 客户端宿主是管理器接触 mcp-client 的唯一途径。** 管理器在构造时创建 `McpClientHost`,并且只从 mcp-client 导入这个类和类型。宿主用各传输自己的 schema 校验条目的客户端字段,因此拒绝时仍点名字段;它把实例挂在管理器的 fiber 下、执行探测,并用管理器的 context 创建授权所有者。插件入口只导出 Loader 加载的内容及其 Service 与错误类,因此宿主是一个 Service 类,而不是一组函数。 **整条目决定实例;`enabled` 控制挂载。** 条目变化会重建子实例,停用或删除条目会销毁子实例。对账与 `restart` 在同一操作队列中串行执行。探测独立运行,配置变更先取消受影响的探测,再由队列中的清理操作等待它们结束。管理器保留清理失败记录,并在 Host 重启前拒绝替换,防止服务器生命周期重叠。 @@ -50,9 +50,9 @@ Status: implemented **让管理界面轮询状态。** 否决:Remote 面已转发宿主事件;发货了轮询的同类产品(Reasonix)或缺状态事件的(OpenCode v1)都把它当作待修缺陷。 -**从 mcp-client 入口导出校验、探测、状态与授权的值。** 否决:插件入口只导出 Loader 加载的内容。导入其他插件值的管理器会一直持有它最初加载的模块;当 mcp-client 另有自己的 Loader 条目时,重载只替换 mcp-client,HMR 还会在管理器不知情时替换它经该插件挂载的实例,留下过期状态和一个管理器停不掉的实例。 +**从 mcp-client 入口导出校验、探测、状态与授权的值。** 否决:插件入口只导出 Loader 加载的内容及其 Service 与错误类,不导出辅助值。 -**在 mcp-client 中定义供管理器继承探测与授权的 Service Definition。** 否决:子类继承的是它导入的基类,重载后仍运行被替换的代码,而它经自身导入挂载的实例也会如上在它不知情时被替换。 +**把宿主作为以 `host: true` 加载、由管理器注入的独立 mcp-client 条目。** 否决:每个加载管理器的组合都得多一行,客户端配置也要多出一种不连接任何服务器的形态。它唯一的好处是开发期 mcp-client 重载时管理器随之重启,不足以抵消这两点。 **把连接机制移到单独的服务包。** 否决:每台服务器的 mcp-client 实例使用同一套机制,因此所有加载 mcp-client 的组合都得额外加载这个新服务。 @@ -68,5 +68,5 @@ mcp-client 单测覆盖状态迁移、独立的启动与探测预算、模板绑 - 存活判断依赖传输关闭与请求失败;停滞但不关闭的 Streamable HTTP 服务器要等到请求失败时才会被发现。 - 被重建服务器的工具在替换连接完成首次同步前不可用。替换会等待传输确认关闭且本地清理成功。 - 管理器只治理全局面;preset 作用域与静态实例不在其列表内。 -- 加载管理器的组合同时加载一个 `host: true` 的 mcp-client 条目;缺少它时管理器保持等待。mcp-client 重载会重启管理器,管理器随之重新挂载其服务器。 +- 管理器沿用它加载的 mcp-client 代码,直到管理器自身重载;开发期只重载 mcp-client 不会重启管理器。 - `startupTimeoutMs` 只为启动尝试设界,通知驱动的重同步请求仍走 SDK 请求默认值——已记录为 mcp-client 的限制。 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml index 32af5fd21a..db6139954a 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml @@ -21,8 +21,8 @@ en: 8a9578bbc700c0bf zh: 8ee46e5ef1cf3972 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write: - en: 33312dc2b9813ef9 - zh: ba2fb5fac770e698 + en: c6b0d746185d0d3b + zh: a228633ecdf42800 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes: en: 85fb2b564bc40230 zh: 97c3e794124f8044 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md index 22c7693e9b..cb7ad564cd 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md @@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem ### Authorization loses required observation or an accepted credential write -**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts). +**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts). **Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced. diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md index 17580f8578..fd5a6c3f45 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md @@ -36,7 +36,7 @@ Status: proposed ### Authorization 丢失必需的提交观察或已接受的凭据写入 -**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts)。 +**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。 **写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。 diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index 126c9d0ecc..930c19adfd 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -11,20 +11,20 @@ Define failures, their owners, and what remains safe after failure. Expected failures need declared types, stable discriminants, and handling-relevant details. Reuse package error conventions, preserve causes, and separate machine identity from display text. Never route handling by parsing messages. Unexpected defects such as `assertNever` may remain plain `Error`; containment must never turn them into success. -An error class that carries a machine code extends `HarnessError` from `dsh-llm`, directly or through its package's error class, never bare `Error`. Prefer one error class per owning package or domain over a class per failure; a separate class is justified when callers catch it by type or it carries its own structured fields, such as `ToolArgsError.violations`. `name` is the class name, except for cancellation (below), and `code` values are stable `UPPER_SNAKE_CASE` strings, usually prefixed by the domain and declared as a union or constants beside the class. A code names the failure class its consumers act on, not the call site; add a code rather than reuse one whose meaning differs. The [error class and code guide](references/error-codes.md) defines class choice, naming, the standard conditions, declaration, foreign-error conversion, and compatibility. +An error class that carries a machine code extends `HarnessError` from `dsh-error` (also re-exported by `dsh-llm`), directly or through its package's error class, never bare `Error`. Prefer one error class per owning package or domain over a class per failure; a separate class is justified when callers catch it by type or it carries its own structured fields, such as `ToolArgsError.violations`. `name` is the class name, except for cancellation (below), and `code` values are stable `UPPER_SNAKE_CASE` strings, usually prefixed by the domain and declared as a union or constants beside the class. A code names the failure class its consumers act on, not the call site; add a code rather than reuse one whose meaning differs. The [error class and code guide](references/error-codes.md) defines class choice, naming, the standard conditions, declaration, foreign-error conversion, and compatibility. Convert foreign failures where the dependency is owned. Node errno, SDK, protocol, native, worker, and cross-realm errors become the owning package's error with the original as `cause`; a foreign numeric or vendor code belongs in the message, not in `code`. Preserve structure across layers: never re-wrap a `HarnessError` in a plain `Error`, store only its message for a later rethrow, or drop its `name` and `code` while redacting text. A process or worker boundary transports `name` and `code` and reconstructs the error. ## Tool failures -The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny` with `info`, the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, a guard denial, an approval rejection, and a post-execute block persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: +The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or an `Error` named `AbortError` that the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass: - Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`. -- Missing composition or caller context, such as an absent Agent, service, or open turn, throws the owning package's error with its own code. -- Caller cancellation throws a `HarnessError` whose `name` is `AbortError` and whose code is the `dsh-tools` `TOOL_ABORTED` constant (`ABORTED`), matching the registry's cancellation result; never a bare `AbortError` or `signal.reason`. +- Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`. +- Caller cancellation either propagates the signal's reason or an `Error` named `AbortError`, which the registry classifies as `AbortError` with the `dsh-tools` `TOOL_ABORTED` constant (`ABORTED`), or throws a `HarnessError` with that `name` and code. Never replace it with a different plain `Error`; a failure distinct from the cancellation, such as a cleanup failure, keeps its own class and code. - Dependency failures follow the conversion rule above; filesystem errno maps to `FsError` codes such as `FS_NOT_FOUND`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR`. -A policy that denies a call in `tools/pre-execute` supplies `info` with its own `name` and `code`. The registry's built-in approval rejections and guard denials currently carry only a reason, so they remain unroutable until the registry gives them codes. A failure the model must not treat as success is an `isError` result; a successful domain outcome in a non-ideal state, such as a non-zero exit or no matches, stays a success value, and a success-shaped failure value is allowed only when the output schema documents it. Tests assert `error.info.name` and `error.info.code` for each expected failure path, not only the message. +A policy that denies a call in `tools/pre-execute`, through `tools.guard()`, or by a post-execute block supplies `info` with its own `name` and `code`. A failure the model must not treat as success is an `isError` result; a successful domain outcome in a non-ideal state, such as a non-zero exit or no matches, stays a success value, and a success-shaped failure value is allowed only when the output schema documents it. Tests assert `error.info.name` and `error.info.code` for each expected failure path, not only the message. Existing `name` and `code` values persist in Session logs and feed analytics. Renaming or reclassifying one is an externally perceptible change that needs an [upgrade guide](../dsh-create-upgrade-guide/SKILL.md). diff --git a/.agents/skills/dsh-error-handling/references/error-codes.md b/.agents/skills/dsh-error-handling/references/error-codes.md index 26b2cada50..853dadd6ad 100644 --- a/.agents/skills/dsh-error-handling/references/error-codes.md +++ b/.agents/skills/dsh-error-handling/references/error-codes.md @@ -17,7 +17,7 @@ Use this guide when adding or reviewing an error class, an error code, or a fail ## Choose the class 1. Reuse the owning domain's existing class when the failure belongs to that domain: `FsError` for filesystem targets, `SearchError` for `glob`/`grep`, `LspError`, `WebError`, `SubagentError`, `TeamError`, `GoalError`, `WorkflowError`, `UserQuestionError`, `SessionQueryError`, the `Sandbox*Error` classes, and `CodeRunFailedError`. -2. Use `ToolArgsError` (`INVALID_ARGS`) for argument constraints the parameter schema cannot express, such as an empty string, a range, or a cross-field rule. +2. Use `ToolArgsError` (`INVALID_ARGS`) for argument constraints the parameter schema cannot express, such as an empty string, a range, or a cross-field rule, and `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) for a tool call that lacks a required Agent, service, or open turn. 3. Declare a new class only for a new owning domain. Prefer one class with a code union over one class per failure; a separate subclass is justified when consumers must catch it by type or it carries its own structured fields, such as `ToolArgsError.violations`, and it then extends the domain class when one exists so the domain still matches with `instanceof`. 4. Never declare a coded class that extends bare `Error`. An existing one is migrated by changing its base class and keeping every `name` and `code`. @@ -26,7 +26,7 @@ Use this guide when adding or reviewing an error class, an error code, or a fail - `name` is the PascalCase class name ending in `Error`, such as `JobError` or `SandboxEscalationError`. - Assign `this.name` a string literal in the constructor. `HarnessError` defaults `name` to `new.target.name`, but a bundler may rename a colliding class binding, and a renamed class would change persisted data. - Do not reuse another domain's class name, and do not encode a code in the name. -- Cancellation is the one exception: a tool throws a `HarnessError` whose `name` is `AbortError` and whose code is the `dsh-tools` `TOOL_ABORTED` constant (`ABORTED`), so tool-thrown and registry-generated cancellations share one `name` and `code`. +- Cancellation is the one exception: its `name` is `AbortError` and its code is the `dsh-tools` `TOOL_ABORTED` constant (`ABORTED`). The registry applies both to a signal reason or an `Error` named `AbortError` that a tool throws after cancellation, whichever operation inside the tool aborted; a tool that throws its own cancellation error uses a `HarnessError` with the same `name` and code. ## Format the code diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 96b711a333..1fa22d5a13 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -54,7 +54,7 @@ flowchart LR cfg --> plugin_dsh_base_settings plugin_dsh_base_authorization["authorization
@deepseek-ai/dsh-authorization"] cfg --> plugin_dsh_base_authorization - plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account-platform"] + plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account"] cfg --> plugin_dsh_base_deepseek_account plugin_dsh_base_credentials["credentials
@deepseek-ai/dsh-credentials-local"] cfg --> plugin_dsh_base_credentials @@ -233,7 +233,7 @@ flowchart LR | `config-editor` | `@deepseek-ai/dsh-config-editor` | | `settings` | `@deepseek-ai/dsh-settings` | | `authorization` | `@deepseek-ai/dsh-authorization` | -| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account-platform` | +| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` | | `credentials` | `@deepseek-ai/dsh-credentials-local` | | `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` | | `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` | diff --git a/apps/cli/tests/profile-mcp.spec.ts b/apps/cli/tests/profile-mcp.spec.ts index 577668e528..4fbc3de396 100644 --- a/apps/cli/tests/profile-mcp.spec.ts +++ b/apps/cli/tests/profile-mcp.spec.ts @@ -12,7 +12,7 @@ const installAnchor = fileURLToPath(new URL('../package.json', import.meta.url)) const resourcePackage = '@deepseek-ai/dsh-mcp-resources' describe('shipped MCP resource composition', () => { - it.each(Object.keys(PROFILE_TEMPLATES))('%s carries one shared resource consumer and no MCP server instance', (name) => { + it.each(Object.keys(PROFILE_TEMPLATES))('%s carries one shared resource consumer without a server', (name) => { const home = mkdtempSync(join(tmpdir(), 'dsh-profile-mcp-')) try { const profile = loadProfile('dsh', name, installAnchor, home) @@ -25,9 +25,7 @@ describe('shipped MCP resource composition', () => { expect(rows.filter(row => row.name === resourcePackage)).toEqual([ { id: 'mcp-resources', name: resourcePackage }, ]) - expect(rows.filter(row => row.name === '@deepseek-ai/dsh-mcp-client')).toEqual(name === 'web' - ? [{ id: 'mcp-client-host', name: '@deepseek-ai/dsh-mcp-client', config: { host: true } }] - : []) + expect(rows.filter(row => row.name === '@deepseek-ai/dsh-mcp-client')).toEqual([]) expect(warnings).toEqual([]) const owners = profile.layers.filter((layer) => { diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index a3e4b09a4d..14be185017 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -599,9 +599,7 @@ describe('the shipped Web composition', () => { expect(codePointLength(text) - codePointLength(path) + 256, file).toBeLessThan(8192) } - // The persona is `standard`'s, pinned verbatim so the two declarations - // cannot drift apart: tool descriptions and the skill catalog carry - // every creation-mode instruction. + // Creator adds its DSH customization intent to the shared coding persona. const standard = await ctx.agents.create({ sessionId: SessionId('preset-cordis-standard-persona'), setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), @@ -611,7 +609,30 @@ describe('the shipped Web composition', () => { .filter(section => section.name.startsWith('deployment:persona-')) const cordisPersona = await persona(handle.agent) expect(cordisPersona.map(section => section.name)).toEqual(['deployment:persona-prefix', 'deployment:persona-suffix']) - expect(cordisPersona).toEqual(await persona(standard.agent)) + const standardPersona = await persona(standard.agent) + const standardPrefix = standardPersona.find(section => section.name === 'deployment:persona-prefix') + expect(standardPrefix?.text).toMatch(/^You are a coding agent powered by the .+ model\.$/u) + expect(cordisPersona).toEqual(standardPersona.map(section => section.name === 'deployment:persona-prefix' + ? { ...section, text: `${section.text} You help the user customize DeepSeek Harness itself.` } + : section)) + const definition = composeEntries([webPatches('Creator persona')]) + .find(row => row.id === 'preset-cordis')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition + const unregister = await ctx.agentPresets.register({ + ...definition, id: 'cordis-coding-only', + plugins: definition.plugins.map(row => row.id === 'persona' + ? { ...row, config: { prefix: standardPrefix!.text } } + : row), + }) + try { + const codingOnly = await ctx.agents.create({ + sessionId: SessionId('preset-cordis-coding-only'), + setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis-coding-only').then(() => undefined), + }) + try { + expect(ctx.tools.schemas(handle.agent).toSorted((left, right) => left.name.localeCompare(right.name))) + .toEqual(ctx.tools.schemas(codingOnly.agent).toSorted((left, right) => left.name.localeCompare(right.name))) + } finally { await codingOnly.dispose() } + } finally { await unregister() } } finally { await standard.dispose() } @@ -865,6 +886,157 @@ describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surfac }, 120_000) }) +describe('the standard preset documentation skill', () => { + it.for([false, true])('loads the packaged skill without adding tools (badge skill: %s)', async (withBadge: boolean) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-standard-doc-')) + vi.stubEnv('DSH_HOME', join(root, 'home')) + vi.stubEnv('DSH_AGENTS_HOME', join(root, 'agents-home')) + vi.stubEnv('DSH_BUNDLED_SKILL_DIR', join(root, 'bundled-skills')) + let docCtx: Context | undefined + try { + const standard = composeEntries([webPatches('standard documentation')]) + .find(row => row.id === 'preset-standard')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition + docCtx = await bootWeb(root, [ + { id: 'skill-badge', disabled: !withBadge }, + { insert: [{ + id: 'preset-standard-without-doc', name: '@deepseek-ai/dsh-agent-preset', + config: { + ...standard, id: 'standard-without-doc', + plugins: standard.plugins.map(row => row.id === 'skill-filesystem' + ? { ...row, config: { customSkillDirs: [] } } + : row), + }, + }] }, + ]) + const testCtx = docCtx + const adapter = new MinimalCompactionAdapter() + testCtx.llm.registerAdapter(['standard-doc-test'], adapter) + const baseline = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-baseline'), meta: { cwd: root }, + agentOptions: { provider: 'standard-doc-test', model: 'standard-doc-test' }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard-without-doc').then(() => undefined), + }) + const standardAgent = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-current'), meta: { cwd: root }, + agentOptions: { provider: 'standard-doc-test', model: 'standard-doc-test' }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), + }) + const baselineSkills = await testCtx.skills.list({ cwd: root, scope: baseline.agent }) + const skills = await testCtx.skills.list({ cwd: root, scope: standardAgent.agent }) + expect(skills.map(skill => skill.name).sort()) + .toEqual([...baselineSkills.map(skill => skill.name), 'dsh-doc'].sort()) + const definition = await testCtx.skills.get('dsh-doc', { cwd: root, scope: standardAgent.agent }) + expect(definition?.path).toBe(await realpath(join(REPO_ROOT, 'packages/preset/agent-preset/skills/dsh-doc/SKILL.md'))) + if (definition === undefined) throw new Error('standard has no packaged dsh-doc skill') + const creator = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-creator'), meta: { cwd: root }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined), + }) + expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path) + const schemas = testCtx.tools.schemas(standardAgent.agent) + expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent)) + expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_list') + expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_query') + for (const handle of [baseline, standardAgent]) { + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply ready.' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + } + const baselineCatalogs = baseline.agent.session.snapshotEvents().flatMap(event => + event.type === 'user/message' && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + const catalogs = standardAgent.agent.session.snapshotEvents().flatMap(event => + event.type === 'user/message' && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + expect(baselineCatalogs).toHaveLength(baselineSkills.length > 0 ? 1 : 0) + expect(catalogs).toHaveLength(1) + expect(catalogs[0]?.source).toMatchObject({ + entries: skills.map(skill => ({ name: skill.name, description: skill.description })), + }) + const requests = adapter.requests.filter(request => request.purpose === undefined) + expect(requests).toHaveLength(2) + expect(requests[0]?.tools).toEqual(requests[1]?.tools) + const catalogSize = (messages: typeof catalogs) => { + const text = messages.flatMap(message => message.content.flatMap(block => block.type === 'text' ? [block.text] : [])).join('') + return { + utf8Bytes: Buffer.byteLength(text, 'utf8'), codePoints: Array.from(text).length, + heuristicTokens: messages.reduce((total, message) => total + testCtx.tokenMeter.estimateMessage(message), 0), + } + } + const beforeCatalog = catalogSize(baselineCatalogs) + const afterCatalog = catalogSize(catalogs) + expect({ + utf8Bytes: afterCatalog.utf8Bytes - beforeCatalog.utf8Bytes, + codePoints: afterCatalog.codePoints - beforeCatalog.codePoints, + heuristicTokens: afterCatalog.heuristicTokens - beforeCatalog.heuristicTokens, + }).toEqual({ utf8Bytes: 500, codePoints: 500, heuristicTokens: 125 }) + const requestTexts = requests.flatMap(request => request.messages.flatMap(message => + message.content.flatMap(block => block.type === 'text' ? [block.text] : []))) + expect(requestTexts.some(text => text.includes(definition.content))).toBe(false) + expect(standardAgent.agent.session.snapshotEvents().filter(event => event.type === 'tool/call')).toEqual([]) + const profileManifest = join(root, 'profiles/spec/package.json') + const before = await readFile(profileManifest, 'utf8') + const loaded = await executeToolFixture(testCtx, { + agent: standardAgent.agent, callId: ToolCallId('standard-doc-load'), + name: 'skill', arguments: { name: 'dsh-doc' }, signal: new AbortController().signal, + }) + expect(loaded.isError).toBe(false) + expect(loaded.content.some(block => block.type === 'text' && block.text.includes(definition.content))).toBe(true) + expect(testCtx.tools.schemas(standardAgent.agent)).toEqual(schemas) + expect(await readFile(profileManifest, 'utf8')).toBe(before) + } finally { + try { await docCtx?.fiber.dispose() } finally { + vi.unstubAllEnvs() + await rm(root, { recursive: true, force: true }) + } + } + }) + it('prefers project dsh-doc overrides while packaged guidance wins over user skills', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-standard-doc-priority-')) + const home = join(root, 'home') + const agentsHome = join(root, 'agents-home') + const workspace = join(root, 'workspace') + const projectAgents = join(root, 'project-agents') + const projectDsh = join(root, 'project-dsh') + vi.stubEnv('DSH_HOME', home) + vi.stubEnv('DSH_AGENTS_HOME', agentsHome) + vi.stubEnv('DSH_BUNDLED_SKILL_DIR', join(root, 'bundled-skills')) + let priorityCtx: Context | undefined + try { + await mkdir(workspace) + for (const project of [projectAgents, projectDsh]) await mkdir(join(project, '.git'), { recursive: true }) + for (const [directory, description] of [ + [join(home, 'skills'), 'User DSH skill'], + [join(agentsHome, 'skills'), 'User agents skill'], + [join(projectAgents, '.agents/skills'), 'Project agents skill'], + [join(projectDsh, '.agents/skills'), 'Lower priority project skill'], + [join(projectDsh, '.dsh/skills'), 'Project DSH skill'], + ] as const) { + const skill = join(directory, 'dsh-doc') + await mkdir(skill, { recursive: true }) + await writeFile(join(skill, 'SKILL.md'), `---\nname: dsh-doc\ndescription: ${description}\n---\n\n${description}\n`) + } + priorityCtx = await bootWeb(root) + const testCtx = priorityCtx + const handle = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-priority'), meta: { cwd: workspace }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), + }) + for (const [cwd, path] of [ + [workspace, join(REPO_ROOT, 'packages/preset/agent-preset/skills/dsh-doc/SKILL.md')], + [projectAgents, join(projectAgents, '.agents/skills/dsh-doc/SKILL.md')], + [projectDsh, join(projectDsh, '.dsh/skills/dsh-doc/SKILL.md')], + ] as const) { + const skills = await testCtx.skills.list({ cwd, scope: handle.agent }) + expect(skills.filter(skill => skill.name === 'dsh-doc')).toHaveLength(1) + expect((await testCtx.skills.get('dsh-doc', { cwd, scope: handle.agent }))?.path).toBe(await realpath(path)) + } + } finally { + try { await priorityCtx?.fiber.dispose() } finally { + vi.unstubAllEnvs() + await rm(root, { recursive: true, force: true }) + } + } + }) +}) + describe('a user preset declared from the shipped cordis rows', () => { /** The JSON text a `cordis_inspect_*` result renders. */ function resultText(result: { content: ReadonlyArray<{ type: string; text?: string }> }): string { diff --git a/apps/desktop-host/tests/platform-session.spec.ts b/apps/desktop-host/tests/platform-session.spec.ts index 73c2322621..35ea560923 100644 --- a/apps/desktop-host/tests/platform-session.spec.ts +++ b/apps/desktop-host/tests/platform-session.spec.ts @@ -1,5 +1,5 @@ -import { Context } from '@deepseek-ai/cordis' -import { DeepSeekAccount, type AccountView, type PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import { Context, Service } from '@deepseek-ai/cordis' +import type { DeepSeekAccount, AccountView, AccountUpdate, PlatformSession } from '@deepseek-ai/dsh-deepseek-account' import { expect, it } from 'vitest' import { installPlatformSessionPublisher } from '../src/platform-session.ts' @@ -8,31 +8,21 @@ const state: AccountView = { links: { usageUrl: 'https://platform.example/usage', topUpUrl: 'https://platform.example/top_up' }, } -class Account extends DeepSeekAccount { - getDeviceIdentity = async () => ({ osVersion: 'test-os' }) +class Account extends Service implements Pick { + constructor(ctx: Context) { super(ctx, 'deepseekAccount') } fail = false identityChangesRequested = false ended = Promise.withResolvers() reading = Promise.withResolvers() finished = Promise.withResolvers() read: () => Promise = async () => ({ origin: 'https://platform.example', userId: null, token: 'test' }) - override async getState() { return state } - override async getProfile() { return null } - override async getBalance() { return null } - override async getUnnotifiedBonuses() { return null } - override async ackBonusNotified() { return false } - override async startSignIn() { return state } - override async cancelSignIn() { return state } - override async signOut() { return state } - override async rejectToken() {} - override async resolveToken() { return undefined } - override async getPlatformSession() { this.reading.resolve(undefined); return this.read() } - override async *watch(signal: AbortSignal, includeIdentityChanges = false) { + async getPlatformSession() { this.reading.resolve(undefined); return this.read() } + async *watch(signal: AbortSignal, includeIdentityChanges = false): AsyncIterable { this.identityChangesRequested = includeIdentityChanges const abort = () => { this.ended.resolve(undefined) } signal.addEventListener('abort', abort, { once: true }) try { - yield state + yield { type: 'snapshot', state } await this.ended.promise if (this.fail) throw new Error('fixture subscription failure') } finally { diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index d36cd62277..7b4f37e1ad 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: 1f59637852e162b4 - zh: b1530a1af195cb92 + en: 37d36f8d57214336 + zh: ceb50c0fa866eb24 /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 @@ -57,8 +57,8 @@ en: f1302ed4a3ab58bb zh: cb53b9b349815028 /deepseek-harness-desktop/updates: - en: 67bf0a18faa7aa76 - zh: 782e14ce62bb939f + en: 8b0b9efeb83727ef + zh: 5ee95de48ceab392 /deepseek-harness-desktop/updates/local-desktop-settings: en: dbe57394894b7368 zh: a3bb788c2ce631a4 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 1e9c3a595d..ffe4f5b520 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -49,7 +49,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. -Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account-platform/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. +Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice. @@ -278,11 +278,11 @@ Ordinary update dialogs use an isolated shell-origin WebContentsView inside the Ordinary update dialogs, the Windows first-close notice, and mandatory-update documents share the UI design tokens bundled with the shell. Before displaying a card, each document resolves Electron's application theme through `prefers-color-scheme` and updates its dark-theme attribute when the palette changes. Welcome and update documents use the same initialization script. Explicit light/dark preferences and system appearance share this path; the isolated document keeps its background transparent, and dark mode adds a 1 CSS px token-based inset outline without changing the card size; light mode has no outline. -Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. +Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. During downloading or verification, **Check for Updates…** shows the state at the time the dialog opens; it does not refresh as the operation advances. Downloading explains that the app remains usable; verification has no download-completion instruction. Closing the status dialog leaves the update running. If any ordinary shell prompt is already open, the action focuses it without replacing its pending decision; close it before requesting update status. Failure to create the status surface uses a native dialog with the same status text and controls; presentation failures are logged without changing the update operation. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` configures the ordinary base interval, and `DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` configures the cap; both accept integer milliseconds from 1000 through 2147483647, with the cap at least the interval. An omitted cap defaults to the larger of one hour and the interval. `DSH_DESKTOP_UPDATE_CHECK_JITTER` sets the fractional jitter from 0 through 1, defaulting to `0.2`; the final delay is at least one second and never exceeds the cap. These settings do not change mandatory-policy polling or authorize download retries. -The lower-left account row displays localized availability, a spinner with download percentage, verification, readiness, or a persistent red retry action with an accessible tooltip. This Web-embedded copy follows the active in-application language; native dialogs use the Desktop shell locale. The collapsed sidebar shows a dot on its top expand button. Connection status takes priority. Selecting an available release starts downloading immediately. Successful preparation automatically opens a shell-owned restart confirmation; closing it retains readiness without reopening the dialog. Selecting the ready entry opens confirmation again. Running agents, queued input, and running or stopping jobs trigger an interruption warning in that confirmation. API requests alone do not trigger the warning. After approval, the Host locks new requests, drains admitted requests, and rechecks tasks, including work created by an admitted write. A drain that exceeds the control-request deadline refuses installation and unlocks admission. Unknown task status, newly started work without interruption approval, or unsuccessful graceful teardown prevents installation. The Host exits as soon as it acknowledges completed teardown, so handles left open by plugins do not count against the graceful deadline. Ordinary quit asks about interruptible work as described under Closing the window and quitting, then hides the product window before stopping the Host, ignores new focus requests during teardown, and never installs an update. The next launch reconciles the version-bound runtime through the existing startup and recovery path. +The lower-left account row displays localized availability, a spinner with download percentage, verification, readiness, or a persistent red retry action with an accessible tooltip. This Web-embedded copy follows the active in-application language; native dialogs use the Desktop shell locale. The collapsed sidebar shows a dot on its top expand button. Connection status takes priority. Selecting an available release starts downloading immediately. Selecting its download percentage opens the same status dialog as Check for Updates, explaining that downloading runs in the background and the app remains usable. Successful preparation automatically opens a shell-owned restart confirmation; closing it retains readiness without reopening the dialog. Selecting the ready entry opens confirmation again. Running agents, queued input, and running or stopping jobs trigger an interruption warning in that confirmation. API requests alone do not trigger the warning. After approval, the Host locks new requests, drains admitted requests, and rechecks tasks, including work created by an admitted write. A drain that exceeds the control-request deadline refuses installation and unlocks admission. Unknown task status, newly started work without interruption approval, or unsuccessful graceful teardown prevents installation. The Host exits as soon as it acknowledges completed teardown, so handles left open by plugins do not count against the graceful deadline. Ordinary quit asks about interruptible work as described under Closing the window and quitting, then hides the product window before stopping the Host, ignores new focus requests during teardown, and never installs an update. The next launch reconciles the version-bound runtime through the existing startup and recovery path. If task teardown fails after confirmed Host exit, installation is refused and the shell restores the current-version Host before allowing another restart confirmation. Installer launch failure after a clean Host stop uses the same recovery. After the replacement Host authenticates, the shell reloads the existing application URL so the Web page obtains its current port, cookie, and boot injections; page-load failure opens native fatal recovery. An unconfirmed process exit never permits a replacement Host. The downloaded target remains available for retry. A known mandatory policy remains blocking throughout recovery; unsuccessful Host restoration opens the native fatal-recovery dialog. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 96c44ba1e2..a6c2493fbc 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -49,7 +49,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 -Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account-platform/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 +Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。 @@ -278,11 +278,11 @@ macOS 在安装准备阶段等待产品主窗口退出全屏,再显示重启 普通更新弹窗、Windows 首次关闭提示和强更文档共用随壳打包的 UI design token。各文档在显示卡片前通过 `prefers-color-scheme` 解析 Electron 的应用主题,配色变化时同步暗色主题属性。欢迎页与更新文档复用同一初始化脚本。明确选择浅色/暗色及跟随系统共用此路径,隔离文档保持透明背景,仅暗色模式以基于 token 的 1 CSS px 内描边区分卡片,不改变尺寸;浅色模式不描边。 -打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。 +打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。下载或校验期间,“**检查更新…**”显示打开提示时的状态,不随操作进展刷新。下载提示说明可以继续使用应用;校验提示不再包含下载完成的说明。关闭状态提示不影响更新。若已有普通壳弹窗,点击会聚焦该弹窗,保留其待确认操作;关闭后可再次查看更新状态。状态界面创建失败时,使用相同状态文案和按钮的原生弹窗兜底;展示失败仅记日志,不改变更新操作。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。 `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` 配置常规基础间隔,`DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` 配置上限;两者均接受 1000 至 2147483647 的整数毫秒数,且上限不能小于间隔。省略上限时取一小时与间隔中的较大值。`DSH_DESKTOP_UPDATE_CHECK_JITTER` 配置 0 至 1 的抖动比例,默认 `0.2`;最终延迟至少一秒,且不超过上限。这些配置不改变强更策略轮询,也不授权下载重试。 -左下角账户行显示本地化的更新可用状态、加载图标与下载百分比、验证、就绪状态,或带可访问提示的持久红色重试操作。嵌入 Web 界面的文案跟随应用内当前语言;原生弹窗使用 Desktop 壳语言。侧栏收起时,顶部展开按钮显示圆点。连接状态优先展示。选择可用版本即开始下载。准备成功后自动打开壳拥有的重启确认;关闭后保留就绪状态,不重复弹窗。选择就绪入口可再次打开确认。运行中的 agent、排队输入,以及运行中或停止中的后台任务都会在该确认中触发中断警告。仅有 API 请求不会触发警告。用户批准后,Host 锁定新请求,等待已接收的请求结束,再检查任务,包括已接收写操作创建的工作。等待超过控制请求截止时间时,拒绝安装并解除准入锁。任务状态未知、未获中断授权的新任务,或未成功完成正常收尾,都会阻止安装。Host 确认收尾完成后立即退出,插件遗留的打开句柄不会占用正常收尾期限。常规退出先按"关闭窗口与退出"一节所述询问可中断的工作,再在停止 Host 前隐藏产品窗口,在收尾期间忽略新的聚焦请求,且从不安装更新。下次启动通过已有的启动与恢复流程校准版本绑定的运行时。 +左下角账户行显示本地化的更新可用状态、加载图标与下载百分比、验证、就绪状态,或带可访问提示的持久红色重试操作。嵌入 Web 界面的文案跟随应用内当前语言;原生弹窗使用 Desktop 壳语言。侧栏收起时,顶部展开按钮显示圆点。连接状态优先展示。选择可用版本即开始下载。点击下载百分比会打开与“检查更新”相同的状态提示,说明更新正在后台下载,可以继续使用应用。准备成功后自动打开壳拥有的重启确认;关闭后保留就绪状态,不重复弹窗。选择就绪入口可再次打开确认。运行中的 agent、排队输入,以及运行中或停止中的后台任务都会在该确认中触发中断警告。仅有 API 请求不会触发警告。用户批准后,Host 锁定新请求,等待已接收的请求结束,再检查任务,包括已接收写操作创建的工作。等待超过控制请求截止时间时,拒绝安装并解除准入锁。任务状态未知、未获中断授权的新任务,或未成功完成正常收尾,都会阻止安装。Host 确认收尾完成后立即退出,插件遗留的打开句柄不会占用正常收尾期限。常规退出先按"关闭窗口与退出"一节所述询问可中断的工作,再在停止 Host 前隐藏产品窗口,在收尾期间忽略新的聚焦请求,且从不安装更新。下次启动通过已有的启动与恢复流程校准版本绑定的运行时。 若任务收尾失败但已确认 Host 退出,安装会被拒绝,壳会在允许再次确认重启前恢复当前版本的 Host。Host 正常停止后的安装器启动失败使用同一恢复路径。替代 Host 启动并完成认证后,壳重新加载原有应用地址,让 Web 页面获取当前端口、Cookie 和启动注入数据;页面加载失败时打开原生致命故障恢复弹窗。未确认进程退出时,绝不允许启动替代 Host。已下载目标保留以供重试。已知强更策略在恢复过程中继续阻塞;Host 恢复失败打开原生致命故障恢复弹窗。 diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index 893969c6b8..fa2b2f5c4a 100644 --- a/apps/desktop/scripts/smoke-runtime.ts +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -12,6 +12,19 @@ import { DesktopHostProcess } from '../src/host-process.ts' import { createPluginProfile } from '../src/project-manager.ts' import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' +const OFFICE_SKILLS = ['office', 'office-docx', 'office-pptx', 'office-xlsx'] + +/** + * Require each bundled Office skill to be listed and loaded with a nonempty body. + * @param results - Host probe results; `bytes` is the loaded body length, 0 when unlisted or not loaded. + * @throws Error listing every result when a bundled Office skill is missing or empty. + */ +export function assertOfficeSkillsLoadable(results: ReadonlyArray<{ readonly name: string; readonly bytes: number }>): void { + if (!OFFICE_SKILLS.every(name => results.some(skill => skill.name === name && skill.bytes > 0))) { + throw new Error(`desktop runtime: packaged Office skills are not loadable: ${JSON.stringify(results)}`) + } +} + /** * Check CLI package operations, Host startup, its frontend, external plugins, packaged Office skill loading, * and real Office rendering, conversion, and recalculation. @@ -104,11 +117,11 @@ export function apply(ctx) { ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke-skills', async handler(_request, response) { try { - const names = ['office', 'office-docx', 'office-pptx', 'office-xlsx'] + const names = ${JSON.stringify(OFFICE_SKILLS)} const listed = new Set((await ctx.skills.list()).map(skill => skill.name)) const loaded = await Promise.all(names.map(async name => { const skill = listed.has(name) ? await ctx.skills.get(name) : undefined - return { name, path: skill?.path ?? null, bytes: skill?.content.length ?? 0 } + return { name, bytes: skill?.content.length ?? 0 } })) response.end(JSON.stringify(loaded)) } catch (error) { @@ -190,10 +203,8 @@ export function apply(ctx) { } const skills = await fetch(new URL('/desktop-smoke-skills', ready.url), { headers: { cookie }, signal: AbortSignal.timeout(120_000) }) if (!skills.ok) throw new Error(`desktop runtime: Office skill loading failed: ${await skills.text()}`) - const loadedSkills = await skills.json() as Array<{ name: string; path: string | null; bytes: number }> - if (loadedSkills.some(skill => skill.path === null || skill.bytes === 0)) { - throw new Error(`desktop runtime: packaged Office skills are not loadable: ${JSON.stringify(loadedSkills)}`) - } + const loadedSkills = await skills.json() as { name: string; bytes: number }[] + assertOfficeSkillsLoadable(loadedSkills) console.log('desktop runtime: packaged Office skills listed and loaded') for (const { extension } of inputs) { const converted = await fetch(new URL(`/desktop-smoke-office/${extension}`, ready.url), { diff --git a/apps/desktop/src/account-backend.ts b/apps/desktop/src/account-backend.ts index 19ae3fe796..7150655c48 100644 --- a/apps/desktop/src/account-backend.ts +++ b/apps/desktop/src/account-backend.ts @@ -117,7 +117,14 @@ export function desktopAccountBackend(origin: string, invoke: AccountInvoke, coo } if (frame.streamId === expiryStreamId && frame.type === 'item' && frame.value === 'session-expired') { expired(); return } if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream') - if (frame.type === 'item') listener(accountView(frame.value)) + if (frame.type === 'item') { + const update = frame.value + if (typeof update !== 'object' || update === null || !('type' in update) + || (update.type !== 'snapshot' && update.type !== 'credentials-changed') || !('state' in update)) { + throw new Error('desktop account: invalid stream update') + } + listener(accountView(update.state)) + } else socket?.close() } catch { socket?.close() } }) diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index 050548e879..3e2db64e24 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -138,6 +138,8 @@ export const en = { updateClose: 'Close', updateAcknowledge: 'OK', updateLater: 'Update later', + updateDownloadInProgress: 'Downloading update', + updateDownloadDetail: 'The update is downloading in the background. You can continue using the app.', updateDownloading: 'Downloading {percent}%…', updateVerifying: 'Verifying update files…', updateInstalling: 'Preparing to restart…', @@ -331,6 +333,8 @@ export const zh = { updateClose: '关闭', updateAcknowledge: '确定', updateLater: '稍后更新', + updateDownloadInProgress: '正在下载更新', + updateDownloadDetail: '更新正在后台下载,你可以继续使用应用。', updateDownloading: '正在下载 {percent}%…', updateVerifying: '正在校验更新文件…', updateInstalling: '正在准备重启…', @@ -522,6 +526,8 @@ export const ja = { updateClose: '閉じる', updateAcknowledge: 'OK', updateLater: '後でアップデート', + updateDownloadInProgress: 'アップデートをダウンロード中', + updateDownloadDetail: 'アップデートをバックグラウンドでダウンロードしています。アプリは引き続き使用できます。', updateDownloading: 'ダウンロード中 {percent}%…', updateVerifying: 'アップデートファイルを検証中…', updateInstalling: '再起動の準備中…', @@ -713,6 +719,8 @@ export const es = { updateClose: 'Cerrar', updateAcknowledge: 'OK', updateLater: 'Actualizar más tarde', + updateDownloadInProgress: 'Descargando actualización', + updateDownloadDetail: 'La actualización se está descargando en segundo plano. Puede seguir usando la aplicación.', updateDownloading: 'Descargando {percent}%…', updateVerifying: 'Verificando archivos de actualización...', updateInstalling: 'Preparándose para reiniciar…', @@ -904,6 +912,8 @@ export const fr = { updateClose: 'Fermer', updateAcknowledge: 'OK', updateLater: 'Mettre à jour plus tard', + updateDownloadInProgress: 'Téléchargement de la mise à jour', + updateDownloadDetail: 'La mise à jour se télécharge en arrière-plan. Vous pouvez continuer à utiliser l’application.', updateDownloading: 'Téléchargement de {percent}%…', updateVerifying: 'Vérification des fichiers de mise à jour…', updateInstalling: 'Préparation du redémarrage…', @@ -1095,6 +1105,8 @@ export const de = { updateClose: 'Schließen', updateAcknowledge: 'OK', updateLater: 'Später aktualisieren', + updateDownloadInProgress: 'Update wird heruntergeladen', + updateDownloadDetail: 'Das Update wird im Hintergrund heruntergeladen. Sie können die App weiter verwenden.', updateDownloading: '{percent}% wird heruntergeladen…', updateVerifying: 'Aktualisierungsdateien werden überprüft…', updateInstalling: 'Neustart wird vorbereitet…', @@ -1286,6 +1298,8 @@ export const ru = { updateClose: 'Закрыть', updateAcknowledge: 'OK', updateLater: 'Обновить позже', + updateDownloadInProgress: 'Загрузка обновления', + updateDownloadDetail: 'Обновление загружается в фоновом режиме. Вы можете продолжать пользоваться приложением.', updateDownloading: 'Загрузка {percent}%…', updateVerifying: 'Проверка файлов обновлений…', updateInstalling: 'Подготовка к перезапуску…', @@ -1477,6 +1491,8 @@ export const pt = { updateClose: 'Fechar', updateAcknowledge: 'OK', updateLater: 'Atualizar mais tarde', + updateDownloadInProgress: 'Baixando atualização', + updateDownloadDetail: 'A atualização está sendo baixada em segundo plano. Você pode continuar usando o aplicativo.', updateDownloading: 'Baixando {percent}%…', updateVerifying: 'Verificando arquivos de atualização…', updateInstalling: 'Preparando para reiniciar…', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9a08349620..8f9cd823a5 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1012,6 +1012,21 @@ async function main(): Promise { if (authenticationOperation !== undefined) { policyAuth?.focus(); updateDialog.focus() } + if (!isMandatory() && (updates.state.phase === 'downloading' || updates.state.phase === 'verifying')) { + if (updateDialog.isOpen) { + updateDialog.focus() + return Promise.resolve() + } + const options = { type: 'info' as const, title: locale.messages.updateCheckTitle, + message: updates.state.phase === 'downloading' ? locale.messages.updateDownloadInProgress : locale.messages.updateVerifying, + detail: updates.state.phase === 'downloading' ? locale.messages.updateDownloadDetail : '', buttons: [locale.messages.updateClose], cancelId: 0, + } + return ordinaryMessageBox(options).then(() => {}).catch(async (error: unknown) => { + console.error(error) + try { await dialog.showMessageBox(options) } + catch (nativeError) { console.error(nativeError) } + }) + } let failedOperation: 'check' | 'download' | 'install' = 'check' promptOperation ??= Promise.resolve().then(async () => { if (manual) updateJournal?.action('check-requested') diff --git a/apps/desktop/src/mandatory-update-policy.ts b/apps/desktop/src/mandatory-update-policy.ts index 6c65da3a68..44777281ab 100644 --- a/apps/desktop/src/mandatory-update-policy.ts +++ b/apps/desktop/src/mandatory-update-policy.ts @@ -1,7 +1,8 @@ /** Mandatory-update policy, independent of local business traffic and updater artifacts. */ import { valid } from 'semver' -import { platformClientHeaders, type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import { platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata' /** Installed release identity; no field is supplied by a renderer. */ export interface DesktopPolicyIdentity { diff --git a/apps/desktop/src/platform-view.ts b/apps/desktop/src/platform-view.ts index daf455ed09..7cc85e8cf6 100644 --- a/apps/desktop/src/platform-view.ts +++ b/apps/desktop/src/platform-view.ts @@ -2,7 +2,8 @@ import type { EventEmitter } from 'node:events' import { createHash, randomUUID } from 'node:crypto' import { WebContentsView, session, shell, type Session, type View, type WebFrameMain } from 'electron' -import { mergePlatformCookies, platformClientHeaders, type PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import { mergePlatformCookies, platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata' import { desktopClientMetadata } from './client-metadata.ts' import { PLATFORM_IPC, type PlatformLocale } from './platform-ipc.ts' diff --git a/apps/desktop/tests/account-backend.spec.ts b/apps/desktop/tests/account-backend.spec.ts index ffdc59d340..54d6eea798 100644 --- a/apps/desktop/tests/account-backend.spec.ts +++ b/apps/desktop/tests/account-backend.spec.ts @@ -45,7 +45,12 @@ it('does not replay an expiry reason from an account snapshot', () => { expect(accountView({ ...state, signOutReason: 'expired' })).toEqual(state) }) -it('receives live expiry separately from account snapshots', async () => { +it.each([ + ['snapshot', 'invalid'], + ['credentials-changed', 'invalid'], + ['snapshot', ['snapshot']], + ['credentials-changed', ['credentials-changed']], +] as const)('receives %s state updates separately from live expiry and rejects type %j', async (type, invalidType) => { const server = new WebSocketServer({ host: '127.0.0.1', port: 0 }) await once(server, 'listening') onTestFinished(async () => { @@ -61,8 +66,9 @@ it('receives live expiry separately from account snapshots', async () => { links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } const received = Promise.withResolvers() const backend = desktopAccountBackend(`http://127.0.0.1:${address.port}`, () => Promise.resolve(snapshot), 'dsh-auth-fixture=signed') + const failed = vi.fn() const stop = backend.watch( - (value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, vi.fn(), expired, onAnalyticsEnabledChanged, + (value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, failed, expired, onAnalyticsEnabledChanged, ) onTestFinished(stop) const [, upgrade] = await connected as [unknown, IncomingMessage] @@ -78,7 +84,7 @@ it('receives live expiry separately from account snapshots', async () => { if (streams.size === 3) opened.resolve(undefined) }) await opened.promise - socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: snapshot })) + socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type, state: snapshot } })) await received.promise socket.send(JSON.stringify({ type: 'item', streamId: streams.get('productAnalytics/watchPolicy'), value: true })) await vi.waitFor(() => { expect(onAnalyticsEnabledChanged).toHaveBeenLastCalledWith(true) }) @@ -91,5 +97,7 @@ it('receives live expiry separately from account snapshots', async () => { expect(expired).not.toHaveBeenCalled() socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watchExpiry'), value: 'session-expired' })) await vi.waitFor(() => { expect(expired).toHaveBeenCalledOnce() }) + socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type: invalidType, state: snapshot } })) + await vi.waitFor(() => { expect(failed).toHaveBeenCalledOnce() }) stop() }) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 8c58dec463..17e16cec09 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -2259,7 +2259,23 @@ describe('desktop main startup', () => { const action = invoke(DESKTOP_IPC.updatesOpen, 'app') await started.promise const repeated = invoke(DESKTOP_IPC.updatesOpen, 'app') - expect(harness.dialog.showMessageBox).not.toHaveBeenCalled() + await repeated + expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: en.updateDownloadInProgress, detail: en.updateDownloadDetail, + })) + harness.dialog.showMessageBox.mockClear() + const checks = harness.updateCheck.mock.calls.length + const check = applicationMenuItems().find(item => item.label === en.checkUpdatesMenu)!.click as () => void + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: en.updateDownloadInProgress, detail: en.updateDownloadDetail, buttons: [en.updateClose], + })) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + harness.shellDialog.isOpen = true + check() + expect(harness.shellDialog.focus).toHaveBeenCalled() + expect(harness.dialog.showMessageBox).toHaveBeenCalledOnce() + harness.shellDialog.isOpen = false expect(harness.updateDownload).toHaveBeenCalledExactlyOnceWith('1.0.1-nightly.1', 0) expect(harness.updateInstall).not.toHaveBeenCalled() downloading.resolve({ phase: 'ready', version: '1.0.1-nightly.1' }) @@ -2269,6 +2285,60 @@ describe('desktop main startup', () => { expect(harness.updateInstall).toHaveBeenCalledOnce() }) + it.each(['downloading', 'verifying'] as const)('explains %s when checking from the menu without another update operation', async (phase) => { + await readyForUpdate() + harness.updateState = { phase, version: '1.0.1-nightly.1', percent: 21 } + const checks = harness.updateCheck.mock.calls.length + const check = applicationMenuItems().find(item => item.label === en.checkUpdatesMenu)!.click as () => void + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: phase === 'downloading' ? en.updateDownloadInProgress : en.updateVerifying, + detail: phase === 'downloading' ? en.updateDownloadDetail : '', buttons: [en.updateClose], cancelId: 0, + })) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledTimes(2) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + }) + + it.each(['downloading', 'verifying'] as const)('falls back to native %s status without changing the message or restarting the update', async (phase) => { + await readyForUpdate() + harness.updateState = { phase, version: '1.0.1-nightly.1', percent: 21 } + const checks = harness.updateCheck.mock.calls.length + harness.dialog.showMessageBox.mockRejectedValueOnce(new Error('overlay unavailable')) + await invoke(DESKTOP_IPC.updatesOpen, 'app') + expect(harness.dialog.showMessageBox).toHaveBeenCalledTimes(2) + const first: unknown = harness.dialog.showMessageBox.mock.calls[0]!.at(-1) + expect(first).toEqual(expect.objectContaining(harness.dialog.showMessageBox.mock.calls[1]!.at(-1))) + expect(first).toEqual(expect.objectContaining({ + type: 'info', message: phase === 'downloading' ? en.updateDownloadInProgress : en.updateVerifying, + detail: phase === 'downloading' ? en.updateDownloadDetail : '', buttons: [en.updateClose], + })) + expect(console.error).toHaveBeenCalledWith(expect.objectContaining({ message: 'overlay unavailable' })) + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + }) + + it('logs native status fallback failure without rejecting the user action', async () => { + await readyForUpdate() + harness.updateState = { phase: 'downloading', version: '1.0.1-nightly.1', percent: 21 } + harness.dialog.showMessageBox.mockRejectedValueOnce(new Error('overlay unavailable')) + .mockRejectedValueOnce(new Error('native unavailable')) + await expect(invoke(DESKTOP_IPC.updatesOpen, 'app')).resolves.toBeUndefined() + expect(console.error).toHaveBeenCalledWith(expect.objectContaining({ message: 'native unavailable' })) + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe('downloading') + }) + it('does not lock or stop tasks when restart confirmation is dismissed', async () => { const host = await readyForUpdate() harness.dialog.showMessageBox.mockResolvedValueOnce({ response: 1 }) diff --git a/apps/desktop/tests/office-resources.e2e.ts b/apps/desktop/tests/office-resources.e2e.ts index 34b9d86e7a..ae626554e9 100644 --- a/apps/desktop/tests/office-resources.e2e.ts +++ b/apps/desktop/tests/office-resources.e2e.ts @@ -4,6 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' +import { assertOfficeSkillsLoadable } from '../scripts/smoke-runtime.ts' import { DesktopHostProcess } from '../src/host-process.ts' import { builtHost, prepareDesktopHome } from './harness.ts' @@ -24,9 +25,14 @@ export function apply(ctx) { ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/${SKILL_PROBE}', async handler(_request, response) { try { const names = (await ctx.skills.list()).map(skill => skill.name).filter(name => name.startsWith('office')) + const listed = new Set(names) + const loaded = await Promise.all(${JSON.stringify(OFFICE_SKILLS)}.map(async name => { + const skill = listed.has(name) ? await ctx.skills.get(name) : undefined + return { name, bytes: skill?.content.length ?? 0 } + })) const content = {} for (const name of ['office', 'office-docx']) content[name] = (await ctx.skills.get(name))?.content ?? null - response.end(JSON.stringify({ names, content, officeKit: ctx.get('officeKit') !== undefined, tools: ctx.tools.schemas().map(tool => tool.name).filter(name => name.startsWith('office_')) })) + response.end(JSON.stringify({ names, content, loaded, officeKit: ctx.get('officeKit') !== undefined, tools: ctx.tools.schemas().map(tool => tool.name).filter(name => name.startsWith('office_')) })) } catch (error) { response.statusCode = 500 response.end(String(error?.stack ?? error)) @@ -70,7 +76,14 @@ describe.skipIf(!existsSync(builtHost))('built Desktop Host Office resources', ( const probe = await fetch(new URL(`/${SKILL_PROBE}`, url), { headers: { cookie } }) const body = await probe.text() expect(probe.status, body).toBe(200) - const skills = JSON.parse(body) as { names: string[]; content: Record; officeKit: boolean; tools: string[] } + const skills = JSON.parse(body) as { + names: string[] + content: Record + loaded: { name: string; bytes: number }[] + officeKit: boolean + tools: string[] + } + assertOfficeSkillsLoadable(skills.loaded) expect(skills.officeKit).toBe(true) // Agent presets, not the Host root, mount the Office tools. expect(skills.tools).toEqual([]) diff --git a/apps/desktop/tests/smoke-runtime.spec.ts b/apps/desktop/tests/smoke-runtime.spec.ts new file mode 100644 index 0000000000..44b9cd9056 --- /dev/null +++ b/apps/desktop/tests/smoke-runtime.spec.ts @@ -0,0 +1,35 @@ +/** Behavioral checks for packaged Office skill probe results. */ + +import { describe, expect, it } from 'vitest' +import { assertOfficeSkillsLoadable } from '../scripts/smoke-runtime.ts' + +const loadedSkills = [ + { name: 'office', bytes: 772 }, + { name: 'office-docx', bytes: 4543 }, + { name: 'office-pptx', bytes: 5167 }, + { name: 'office-xlsx', bytes: 5611 }, +] + +describe('assertOfficeSkillsLoadable', () => { + it('accepts all four Office skills with nonempty bodies and no path', () => { + expect(() => { assertOfficeSkillsLoadable(loadedSkills) }).not.toThrow() + }) + + it('rejects an unlisted or empty Office skill and reports every result', () => { + const results = loadedSkills.map(skill => skill.name === 'office-docx' ? { ...skill, bytes: 0 } : skill) + expect(() => { assertOfficeSkillsLoadable(results) }).toThrow( + `desktop runtime: packaged Office skills are not loadable: ${JSON.stringify(results)}`, + ) + }) + + it('rejects results missing a bundled Office skill', () => { + const results = loadedSkills.filter(skill => skill.name !== 'office-xlsx') + expect(() => { assertOfficeSkillsLoadable(results) }).toThrow( + `desktop runtime: packaged Office skills are not loadable: ${JSON.stringify(results)}`, + ) + }) + + it('ignores empty results for skills outside the bundled Office set', () => { + expect(() => { assertOfficeSkillsLoadable([...loadedSkills, { name: 'other', bytes: 0 }]) }).not.toThrow() + }) +}) diff --git a/apps/desktop/tests/welcome-flow.e2e.ts b/apps/desktop/tests/welcome-flow.e2e.ts index 2fc04b5590..f298fd10fb 100644 --- a/apps/desktop/tests/welcome-flow.e2e.ts +++ b/apps/desktop/tests/welcome-flow.e2e.ts @@ -83,7 +83,7 @@ describe.skipIf(!existsSync(builtHost))('built Desktop welcome flow', () => { const nodeBin = join(root, 'runtime/primary-runtime/dependencies/node/bin') mkdirSync(nodeBin, { recursive: true }) cpSync(process.execPath, join(nodeBin, process.platform === 'win32' ? 'node.exe' : 'node')) - writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`) + writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n harnessOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`) let backend: DesktopWelcomeBackend let hostOrigin = '' const restart = async (): Promise => { diff --git a/apps/web/tests/account-login.e2e.ts b/apps/web/tests/account-login.e2e.ts index a186f74c91..029e6a3cc1 100644 --- a/apps/web/tests/account-login.e2e.ts +++ b/apps/web/tests/account-login.e2e.ts @@ -25,6 +25,7 @@ async function mockPlatform() { let state: string | undefined let redirectUri: string | undefined let avatarRequests = 0 + let notificationLists = 0 const server: Server = createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://127.0.0.1') const reply = (payload: unknown): void => { @@ -83,7 +84,10 @@ async function mockPlatform() { reply({ normal_wallets: [{ currency: 'CNY', balance: '1.00' }], bonus_wallets: [] }) return } - if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { reply([]); return } + if (url.pathname === '/api/v0/users/notifications/list') { + notificationLists++ + reply({ next_poll_after: 600, notifications: [] }); return + } res.writeHead(404).end() }) await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) @@ -91,7 +95,7 @@ async function mockPlatform() { if (address === null || typeof address === 'string') throw new Error('account login: missing mock listener') const origin = `http://127.0.0.1:${String(address.port)}` return { - origin, inits, pages, avatarRequests: () => avatarRequests, + origin, inits, pages, avatarRequests: () => avatarRequests, notificationLists: () => notificationLists, close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), } } @@ -144,7 +148,9 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await menu.locator('[data-avatar-status="failed"]').waitFor() expect(await menu.locator('img').count()).toBe(0) const states: string[] = [] + let expectedLists = 1 const capture = async (stage: string): Promise => { + await expect.poll(platform.notificationLists).toBe(expectedLists) const sidebar = menu.locator('[data-avatar-status]') const account = page.getByRole('region', { name: 'Account', exact: true }) const mounted = await account.count() > 0 @@ -152,10 +158,11 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain ? await account.locator('[data-avatar-status]').getAttribute('data-avatar-status') : 'unmounted' states.push(`${stage}: sidebar=${await sidebar.getAttribute('data-avatar-status')}, settings=${settingsStatus}, ` + `sidebarImages=${await menu.locator('img').count()}, settingsImages=${mounted ? await account.locator('img').count() : 0}, ` - + `requests=${platform.avatarRequests()}`) + + `requests=${platform.avatarRequests()}, notificationLists=${platform.notificationLists()}`) } await capture('Initial load') await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() const settings = page.getByRole('dialog', { name: 'Settings', exact: true }) const account = settings.getByRole('region', { name: 'Account', exact: true }) @@ -167,6 +174,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await expect.poll(() => menu.locator('img').count()).toBe(1) await expect.poll(() => account.locator('img').count()).toBe(1) @@ -179,6 +187,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await account.waitFor() expect(await menu.locator('img').count()).toBe(1) @@ -194,6 +203,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await expect.poll(() => menu.locator('img').count()).toBe(1) await expect.poll(() => account.locator('img').count()).toBe(1) diff --git a/apps/web/tests/bonus-notice.e2e.ts b/apps/web/tests/bonus-notice.e2e.ts index 61124bccb1..330c3e3505 100644 --- a/apps/web/tests/bonus-notice.e2e.ts +++ b/apps/web/tests/bonus-notice.e2e.ts @@ -22,10 +22,10 @@ const MODE = webSnapshotMode() const TOKEN = 'dsh_bonus_notice_test' const ACCOUNT_ID = 'bonus-user' -const ORDER_FIRST = 'bonus-notice-first' -const ORDER_LATER = '33333333-3333-4333-8333-333333333333' +const ORDER_FIRST = 'notice-first' +const ORDER_LATER = 'notice-later' const ORDER_EN = '44444444-4444-4444-8444-444444444444' -const ORDER_RETRY = '55555555-5555-4555-8555-555555555555' +const ORDER_FAILED_EVENT = '55555555-5555-4555-8555-555555555555' const ORDER_REPEAT = '66666666-6666-4666-8666-666666666666' const ORDER_TOPUP = '77777777-7777-4777-8777-777777777777' const ORDER_WEB = '99999999-9999-4999-8999-999999999999' @@ -65,9 +65,14 @@ interface AckRecord { async function mockPlatform() { const unnotified: Granted[] = [] const gets: GetRecord[] = [] + const contentReads: { id: string | null; locale: string | undefined }[] = [] + const contents = new Map() /** Reads already answered; a request the client is still awaiting is not evidence of a delivered response. */ const served: GetRecord[] = [] const acks: AckRecord[] = [] + const dismissals: AckRecord[] = [] + const clicks: AckRecord[] = [] + let includeUnsupportedNotification = false /** Wallet reads, one per balance refresh the settings panel performs. */ const summaries: GetRecord[] = [] let normalBalance = '12.34' @@ -78,20 +83,31 @@ async function mockPlatform() { let keepUnnotified = false /** Refuse the wallet read, which is how a Platform outage or an unparsable payload reaches the client. */ let failSummary = false + let holdProfile = false + const pendingProfiles: (() => void)[] = [] + const releaseProfiles = (): void => { holdProfile = false; for (const reply of pendingProfiles.splice(0)) reply() } /** Reply held back while the test controls when a read can answer. */ let heldReply: (() => void) | undefined const grant = (orderId: string, amount: string, extraCopy = ''): void => { - unnotified.unshift({ + const value = { orderId, amount, zh_CN: `已赠送您 ${amount} 元 DSH 体验赠金。${extraCopy}`, en_US: `You received a CNY ${amount} DSH trial credit.${extraCopy}`, - }) + } + unnotified.unshift(value) + contents.set(orderId, value) } /** @param value - granted bonus. @param locale - request language. @returns its wire fields. */ const wire = (value: Granted, locale: string | undefined): unknown => ({ - order_id: value.orderId, expires_at: value.orderId === ORDER_FIRST ? null : expiresAt(), - ...(value.orderId === ORDER_FIRST ? { title: '平台通知' } : {}), - msg: locale === 'en_US' ? value.en_US : value.zh_CN, + id: value.orderId, created_at: '2026-10-21T08:00:00Z', + display_until: value.orderId === ORDER_FIRST ? null : expiresAt(), + title: value.orderId === ORDER_FIRST ? (locale === 'en_US' ? 'Platform notice' : '平台通知') + : locale === 'en_US' ? 'Bonus credited' : '赠金已到账', + body: locale === 'en_US' ? value.en_US : value.zh_CN, + actions: value.orderId === 'b1111111-1111-4111-8111-111111111111' ? [ + { label: locale === 'en_US' ? 'View balance' : '查看余额', style: 'primary', target: { type: 'app_route', name: 'account' } }, + { label: locale === 'en_US' ? 'Got it' : '知道了', style: 'secondary', target: { type: 'dismiss' } }, + ] : [], }) const server: Server = createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://127.0.0.1') @@ -103,10 +119,14 @@ async function mockPlatform() { } if (req.headers['x-dsh-auth-token'] !== TOKEN) { res.writeHead(401).end(); return } if (url.pathname === '/auth-api/v0/users/current') { - // `email` is required by the provider's profile schema even when the account has none. - reply({ code: 0, data: { biz_code: 0, biz_data: { - id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null }, - } } }) + const answer = (): void => { + // `email` is required by the provider's profile schema even when the account has none. + reply({ code: 0, data: { biz_code: 0, biz_data: { + id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null }, + } } }) + } + if (holdProfile) pendingProfiles.push(answer) + else answer() return } if (url.pathname === '/api/v0/users/get_user_summary') { @@ -118,28 +138,48 @@ async function mockPlatform() { } } }) return } - if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { + if (url.pathname === '/api/v0/users/notifications/list') { const record = { locale, query: url.search } gets.push(record) - const payload = { code: 0, data: { biz_code: 0, biz_data: unnotified.map(value => wire(value, locale)) } } + const payload = { code: 0, data: { biz_code: 0, biz_data: { + next_poll_after: 3600, notifications: [ + ...includeUnsupportedNotification ? [{ + id: 'unsupported-action', created_at: '2026-10-21T00:00:00Z', display_until: null, + title: 'Unsupported action', body: 'Not supported by this client', + actions: [{ label: 'Open', style: 'primary', target: { type: 'future' } }], + }] : [], + ...unnotified.map(value => wire(value, locale)), + ], + } } } const answer = (): void => { served.push(record); reply(payload) } if (heldReply === undefined) { answer(); return } heldReply = answer return } - if (url.pathname === '/api/v0/users/ack_bonus_notified' && req.method === 'POST') { + if (url.pathname === '/api/v0/users/notifications/content') { + const id = url.searchParams.get('id') + contentReads.push({ id, locale }) + const value = id === null ? undefined : contents.get(id) + if (value === undefined) { res.writeHead(404).end(); return } + reply({ code: 0, data: { biz_code: 0, biz_data: wire(value, locale) } }) + return + } + if (url.pathname === '/api/v0/users/notifications/events' && req.method === 'POST') { let body = '' req.setEncoding('utf8') req.on('data', (chunk: string) => { body += chunk }) req.on('end', () => { const payload: unknown = JSON.parse(body) - const orderId = typeof payload === 'object' && payload !== null && 'order_id' in payload - && typeof payload.order_id === 'string' ? payload.order_id : null - acks.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body, + const orderId = typeof payload === 'object' && payload !== null && 'notification_id' in payload + && typeof payload.notification_id === 'string' ? payload.notification_id : null + const event = typeof payload === 'object' && payload !== null && 'type' in payload ? payload.type : null + if (event !== 'displayed' && event !== 'cta_clicked' && event !== 'dismissed') { res.writeHead(400).end(); return } + const records = event === 'displayed' ? acks : event === 'cta_clicked' ? clicks : dismissals + records.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body, query: url.search, contentType: req.headers['content-type'], at: performance.now() }) - if (ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) { + if (event === 'displayed' && ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) { ackFailure.remaining-- - // A transient gateway failure: the client retries it after its backoff. + // The event is lost; a later notification read can offer this order again. res.writeHead(502, { 'content-type': 'text/plain' }).end('Internal Server Error') return } @@ -147,8 +187,8 @@ async function mockPlatform() { reply({ code: 0, msg: '', data: { biz_code: 1, biz_msg: 'BONUS_ORDER_NOT_FOUND', biz_data: null } }); return } const index = unnotified.findIndex(value => value.orderId === orderId) - if (index >= 0 && !keepUnnotified) unnotified.splice(index, 1) - reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: null } }) + if (index >= 0 && !keepUnnotified && event !== 'cta_clicked') unnotified.splice(index, 1) + reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: { acked: true } } }) }) return } @@ -160,7 +200,11 @@ async function mockPlatform() { if (address === null || typeof address === 'string') throw new Error('bonus notice: missing mock listener') return { origin: `http://127.0.0.1:${String(address.port)}`, - grant, gets, served, acks, summaries, + grant, gets, served, acks, clicks, dismissals, summaries, contentReads, + setUnsupportedNotification: (value: boolean): void => { includeUnsupportedNotification = value }, + holdProfiles: (): void => { holdProfile = true }, + pendingProfileResponses: (): number => pendingProfiles.length, + releaseProfiles, /** @param value - recharge balance the settings page reads next. */ setNormalBalance: (value: string): void => { normalBalance = value }, /** @param value - bonus balance the settings page reads next. */ @@ -176,7 +220,7 @@ async function mockPlatform() { /** Hold the next unnotified-bonus read so the test can observe the in-flight state. */ holdNextGet: (): void => { heldReply = () => undefined }, releaseGet: (): void => { const held = heldReply; heldReply = undefined; held?.() }, - close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), + close: () => new Promise((resolve) => { releaseProfiles(); server.close(() => { resolve() }); server.closeAllConnections() }), } } @@ -286,6 +330,8 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { // A read the renderer never received cannot become a displayed notice: while the // response is held there is no card and no acknowledgement. platform.holdNextGet() + platform.holdProfiles() + platform.setUnsupportedNotification(true) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await expect.poll(() => platform.gets.length, { timeout: 30_000 }).toBe(1) observations.push(`startup.held cards=${String(await noticeCards(page).count())} acks=${String(platform.acks.length)}`) @@ -296,21 +342,34 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { // Startup signs in and reads the notice; the card shows it and only then is it acknowledged. observations.push(`startup.notice=${await shownNotice(page, zhFirst)}`) observations.push(`startup.ack orders=${await acked(platform, 1)}`) + expect(await noticeCards(page).count()).toBe(1) + expect(platform.acks.some(record => record.orderId === 'unsupported-action')).toBe(false) + observations.push('startup.unsupported-action skipped=true valid-card=true displayed=false') + platform.setUnsupportedNotification(false) + await expect.poll(platform.pendingProfileResponses).toBeGreaterThan(0) + observations.push('startup.profile-pending notice=true displayed=1') + platform.releaseProfiles() const get = platform.gets[0]! const ack = platform.acks[0]! observations.push(`startup.get locale=${String(get.locale)} query=${get.query}`) - observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} order_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`) + observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} notification_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`) expect(get.locale).toBe('zh_CN') expect(get.query).toBe('') expect(ack).toMatchObject({ - method: 'POST', path: '/api/v0/users/ack_bonus_notified', locale: 'zh_CN', orderId: ORDER_FIRST, - body: JSON.stringify({ order_id: ORDER_FIRST }), query: '', contentType: 'application/json', + method: 'POST', path: '/api/v0/users/notifications/events', locale: 'zh_CN', orderId: ORDER_FIRST, + body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'displayed' }), query: '', contentType: 'application/json', }) - // Closing the card only hides it; the acknowledgement already sent is not repeated. + // Explicit close reports dismissal without repeating the display event. await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() expect(await noticeCards(page).count()).toBe(0) expect(platform.acks).toHaveLength(1) + await expect.poll(() => platform.dismissals.length).toBe(1) + expect(platform.dismissals[0]).toMatchObject({ + method: 'POST', path: '/api/v0/users/notifications/events', orderId: ORDER_FIRST, + body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'dismissed' }), + }) + observations.push('startup.close event=dismissed displayed=1 dismissed=1') // A new grant and balance arrive before settings opens; one panel entry refreshes both once. platform.grant(ORDER_LATER, '8.00') @@ -463,32 +522,27 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() expect(await noticeCards(page).count()).toBe(0) - // A transient acknowledgement failure keeps the card and retries the same order after - // the backoff; the pending retry is page state, not browser storage. - const zhRetry = '已赠送您 6.00 元 DSH 体验赠金。' - platform.grant(ORDER_RETRY, '6.00') - platform.failNextAcks(ORDER_RETRY, 1) + // A failed event leaves the card intact and is not retried in the background. + const zhFailedEvent = '已赠送您 6.00 元 DSH 体验赠金。' + platform.grant(ORDER_FAILED_EVENT, '6.00') + platform.failNextAcks(ORDER_FAILED_EVENT, 1) await openSettings(page, 'zh') - const retryDialog = page.getByRole('dialog', { name: '设置', exact: true }) - await retryDialog.waitFor() - observations.push(`retry.notice=${await shownNotice(page, zhRetry)}`) - const retryAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_RETRY) - await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(1) - // The failed attempt does not withdraw the card the user is reading. - expect(await noticeCards(page).count()).toBe(1) - await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(2) - const attempts = retryAttempts() - // The first retry follows the configured first delay rather than arriving immediately. - // Only the lower bound is asserted: load can widen the observed gap, never shorten it - // below the timer's own 1s first step. - const retryGapMs = attempts[1]!.at - attempts[0]!.at - const retryBodyKept = attempts.every(item => item.body === JSON.stringify({ order_id: ORDER_RETRY }) + const failedEventDialog = page.getByRole('dialog', { name: '设置', exact: true }) + await failedEventDialog.waitFor() + observations.push(`event-failed.notice=${await shownNotice(page, zhFailedEvent)}`) + const failedAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_FAILED_EVENT) + await expect.poll(() => failedAttempts().length, { timeout: 30_000 }).toBe(1) + await page.clock.install() + await page.clock.fastForward(60_000) + const attempts = failedAttempts() + const eventBodyKept = attempts.every(item => item.body === JSON.stringify({ notification_id: ORDER_FAILED_EVENT, type: 'displayed' }) && item.query === '' && item.contentType === 'application/json') - observations.push(`retry.attempts=${String(attempts.length)} backoff=${String(retryGapMs >= 900)} body-kept=${String(retryBodyKept)} cards=${String(await noticeCards(page).count())}`) - expect(retryGapMs).toBeGreaterThanOrEqual(900) - expect(retryBodyKept).toBe(true) + observations.push(`event-failed.attempts=${String(attempts.length)} body-kept=${String(eventBodyKept)} cards=${String(await noticeCards(page).count())}`) + expect(attempts).toHaveLength(1) + expect(eventBodyKept).toBe(true) + expect(await noticeCards(page).count()).toBe(1) await page.keyboard.press('Escape') - await retryDialog.waitFor({ state: 'detached', timeout: 30_000 }) + await failedEventDialog.waitFor({ state: 'detached', timeout: 30_000 }) await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() // Display follows each response: the double keeps serving an acknowledged order, which @@ -580,31 +634,72 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { observations.push(`web.notice=${webNotice} acks=1`) await webPage.close() platform.clearUnnotified() - platform.grant('stack-third', '23.00') - platform.grant('stack-second', '22.00', '\nMore details'.repeat(8)) - platform.grant('stack-first', '21.00') + platform.grant('a3333333-3333-4333-8333-333333333333', '23.00') + platform.grant('a2222222-2222-4222-8222-222222222222', '22.00', '\nMore details'.repeat(8)) + platform.grant('a1111111-1111-4111-8111-111111111111', '21.00') const ackStart = platform.acks.length const stackPage = await openDesktopPage('zh-CN') + await stackPage.setViewportSize({ width: 900, height: 960 }) await stackPage.emulateMedia({ colorScheme: 'light' }) await stackPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) const cards = noticeCards(stackPage) await expect.poll(() => cards.count()).toBe(3) + expect(await cards.first().isVisible()).toBe(false) + expect(platform.acks.length).toBe(ackStart) + observations.push('stack.hidden cards=3 acks=0') + await stackPage.setViewportSize({ width: 1440, height: 960 }) + await expect.poll(() => cards.first().isVisible()).toBe(true) await expect.poll(() => platform.acks.length).toBe(ackStart + 1) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first']) + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111']) expect(await stackPage.getByRole('status').count()).toBe(1) const second = cards.filter({ hasText: '22.00' }) const secondNode = await second.elementHandle() const frontBox = await cards.first().boundingBox() const backBox = await second.boundingBox() - expect(frontBox!.width).toBeCloseTo(280, 0) - expect(backBox!.width).toBeCloseTo(272, 0) + expect(frontBox!.x).toBeCloseTo(10, 0) + expect(frontBox!.width).toBeCloseTo(260, 0) + expect(frontBox!.x + frontBox!.width).toBeCloseTo(270, 0) + expect(backBox!.width).toBeCloseTo(252, 0) expect(backBox!.y).toBeCloseTo(frontBox!.y - 4, 0) const transition = await second.evaluate((element) => { const style = getComputedStyle(element) return `${style.transitionDuration} ${style.transitionTimingFunction}` }) expect(transition).toBe('0.25s ease-out') - observations.push(`stack.initial cards=3 acks=stack-first widths=280,272 offset=-4 transition=${transition}`) + observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`) + for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) { + const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox() + const x = handle!.x + handle!.width / 2 + const y = handle!.y + handle!.height / 2 + await stackPage.mouse.move(x, y) + await stackPage.mouse.down() + await stackPage.mouse.move(x + delta, y, { steps: 5 }) + await stackPage.mouse.up() + await expect.poll(async () => Math.round((await cards.first().boundingBox())!.width)).toBe(width) + const movedHandle = await stackPage.locator('[data-side="sidebar"]').boundingBox() + expect(movedHandle!.x + movedHandle!.width / 2).toBeCloseTo(edge, 0) + const resized = await cards.first().boundingBox() + expect(resized!.x).toBeCloseTo(10, 0) + expect(resized!.x + resized!.width).toBeCloseTo(10 + width, 0) + observations.push(`stack.resized sidebar=${edge} card=${width} left-inset=10`) + } + const beforeCollapseAcks = platform.acks.length + const beforeCollapseDismissals = platform.dismissals.length + await stackPage.setViewportSize({ width: 900, height: 960 }) + await stackPage.locator('[data-sidebar-collapsed]:not([data-sidebar-drawer])').waitFor() + await expect.poll(() => cards.first().isVisible()).toBe(false) + expect(await cards.count()).toBe(3) + expect(platform.dismissals.length).toBe(beforeCollapseDismissals) + observations.push('stack.rail cards=3 visible=false dismissed=0') + await stackPage.setViewportSize({ width: 1440, height: 960 }) + await stackPage.locator('[data-sidebar-collapsed]').waitFor({ state: 'detached' }) + await expect.poll(() => cards.first().isVisible()).toBe(true) + expect(await cards.count()).toBe(3) + expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true) + expect(await cardText(cards.first())).toContain('21.00') + expect(platform.acks.length).toBe(beforeCollapseAcks) + expect(platform.dismissals.length).toBe(beforeCollapseDismissals) + observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0') const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url)) await mkdir(artifactDir, { recursive: true }) await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') }) @@ -635,20 +730,132 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { expect(promotion.middle.y).toBeLessThan(promotion.start.y) expect(promotion.middle.y).toBeGreaterThan(promotion.end.y) await expect.poll(() => cards.count()).toBe(2) - await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(280) + await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(260) expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true) expect(await second.getAttribute('data-front')).toBe('true') await expect.poll(() => platform.acks.length).toBe(ackStart + 2) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second']) - observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=280 same-node=true') + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222']) + observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true') await second.getByRole('button', { name: '关闭', exact: true }).click() await expect.poll(() => platform.acks.length).toBe(ackStart + 3) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second', 'stack-third']) + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333']) await cards.filter({ hasText: '23.00' }).getByRole('button', { name: '关闭', exact: true }).click() await expect.poll(() => cards.count()).toBe(0) + await expect.poll(() => platform.dismissals.filter(record => record.orderId?.startsWith('a')).length).toBe(3) + const stackDismissals = platform.dismissals.filter(record => record.orderId?.startsWith('a')) + expect(stackDismissals.map(record => record.body)).toEqual(stackDismissals.map(record => + JSON.stringify({ notification_id: record.orderId, type: 'dismissed' }))) observations.push('stack.dismissed cards=0 acks=stack-first,stack-second,stack-third') await stackPage.close() + platform.grant('b1111111-1111-4111-8111-111111111111', '31.00') + const refreshAckStart = platform.acks.length + const refreshPage = await openDesktopPage('zh-CN') + await refreshPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const refreshCards = noticeCards(refreshPage) + await shownNotice(refreshPage, '已赠送您 31.00 元 DSH 体验赠金。') + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 1) + const firstNode = await refreshCards.first().elementHandle() + platform.grant('b3333333-3333-4333-8333-333333333333', '33.00') + platform.grant('b2222222-2222-4222-8222-222222222222', '32.00') + await openSettings(refreshPage, 'zh') + await expect.poll(() => refreshCards.count()).toBe(3) + expect(await cardText(refreshCards.first())).toContain('31.00') + expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true) + expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111']) + observations.push('refresh.retained cards=3 acks=refresh-first same-node=true') + const localeReads = platform.gets.length + const localeContents = platform.contentReads.length + await refreshPage.getByRole('dialog', { name: '设置', exact: true }).getByRole('button', { name: '通用设置', exact: true }).click() + await refreshPage.getByRole('button', { name: '中文', exact: true }).click() + await refreshPage.getByRole('menuitem', { name: 'English', exact: true }).click() + await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor() + await expect.poll(() => cardText(refreshCards.first())).toContain('You received a CNY 31.00') + expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true) + expect(platform.gets.length).toBe(localeReads) + expect(platform.acks.length).toBe(refreshAckStart + 1) + expect(platform.contentReads.slice(localeContents).map(read => read.locale)).toEqual(['en_US', 'en_US', 'en_US']) + expect(await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).count()).toBe(1) + observations.push('refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true') + await refreshPage.keyboard.press('Escape') + await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor({ state: 'detached' }) + const clicksBeforeAction = platform.clicks.length + const dismissalsBeforeClick = platform.dismissals.length + await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).click() + await expect.poll(() => platform.clicks.length).toBe(clicksBeforeAction + 1) + expect(platform.clicks.at(-1)?.body).toBe(JSON.stringify({ notification_id: 'b1111111-1111-4111-8111-111111111111', type: 'cta_clicked' })) + expect(platform.dismissals.length).toBe(dismissalsBeforeClick) + expect(await refreshCards.count()).toBe(3) + const accountSettings = refreshPage.getByRole('dialog', { name: 'Settings', exact: true }) + await accountSettings.waitFor() + expect(await accountSettings.getByRole('button', { name: 'Account', exact: true }).getAttribute('aria-current')).toBe('true') + observations.push('refresh.business-action event=cta_clicked cards=3 account-open=true') + await refreshPage.keyboard.press('Escape') + await accountSettings.waitFor({ state: 'detached' }) + await refreshPage.setViewportSize({ width: 390, height: 844 }) + await refreshPage.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor() + await expect.poll(() => refreshCards.first().isVisible()).toBe(false) + expect(await refreshCards.count()).toBe(3) + await refreshPage.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() + const drawer = refreshPage.locator('[data-sidebar-drawer]:not([data-sidebar-collapsed])') + await drawer.waitFor() + expect(await refreshCards.first().evaluate(element => element.closest('[role="dialog"]')?.getAttribute('aria-label'))).toBe('Navigation') + await expect.poll(() => drawer.locator('[data-sidebar-mask]').evaluate(element => getComputedStyle(element).opacity)).toBe('1') + await expect.poll(() => refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).evaluate((element) => { + const rect = element.getBoundingClientRect() + return element.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2)) + })).toBe(true) + observations.push('refresh.drawer width=390 notice-above-sidebar=true') + const cardBounds = await refreshCards.first().boundingBox() + const drawerBounds = await drawer.getByRole('dialog', { name: 'Navigation', exact: true }).boundingBox() + const actionBounds = await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).boundingBox() + expect(cardBounds!.x - drawerBounds!.x).toBeCloseTo(10, 0) + expect(drawerBounds!.width - cardBounds!.width).toBeCloseTo(20, 0) + expect(cardBounds!.x).toBeGreaterThanOrEqual(0) + expect(cardBounds!.x + cardBounds!.width).toBeLessThanOrEqual(390) + expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(cardBounds!.x + cardBounds!.width) + const dismissalsBeforeAction = platform.dismissals.length + await refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).click() + expect(await drawer.count()).toBe(1) + await expect.poll(() => platform.dismissals.length).toBe(dismissalsBeforeAction + 1) + expect(platform.dismissals.at(-1)?.orderId).toBe('b1111111-1111-4111-8111-111111111111') + expect(platform.clicks.length).toBe(clicksBeforeAction + 1) + observations.push('refresh.action event=dismissed got-it=true') + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 2) + expect(await cardText(refreshCards.first())).toContain('32.00') + observations.push('refresh.promoted cards=2 acks=refresh-first,refresh-second') + await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 3) + expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111', 'b2222222-2222-4222-8222-222222222222', 'b3333333-3333-4333-8333-333333333333']) + await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => refreshCards.count()).toBe(0) + observations.push('refresh.dismissed cards=0 acks=refresh-first,refresh-second,refresh-third') + await refreshPage.close() + + const pollFirst = 'c1111111-1111-4111-8111-111111111111' + const pollSecond = 'c2222222-2222-4222-8222-222222222222' + platform.grant(pollFirst, '41.00') + const pollPage = await openDesktopPage('en-US') + await pollPage.clock.install() + await pollPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await shownNotice(pollPage, 'You received a CNY 41.00 DSH trial credit.') + await expect.poll(() => platform.acks.at(-1)?.orderId).toBe(pollFirst) + const pollCards = noticeCards(pollPage) + const retainedNode = await pollCards.first().elementHandle() + const pollReads = platform.gets.length + const pollAcks = platform.acks.length + platform.grant(pollSecond, '42.00') + await pollPage.clock.fastForward(3_600_000) + await expect.poll(() => pollCards.count()).toBe(2) + expect(platform.gets.length).toBe(pollReads + 1) + expect(platform.acks.length).toBe(pollAcks) + expect(await pollCards.first().evaluate((element, previous) => element === previous, retainedNode)).toBe(true) + await openSettings(pollPage, 'en') + await expect.poll(() => platform.gets.length).toBe(pollReads + 2) + expect(await pollCards.count()).toBe(2) + observations.push('poll.arrival cards=2 list-reads=1 duplicate-acks=0 same-node=true settings-immediate-read=true') + await pollPage.close() + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'notice-flow.expected.md'), observations.join('\n'), MODE) for (const tripwire of tripwires) { expect(tripwire.warnings).toEqual([]) diff --git a/apps/web/tests/composer-paste-routing.e2e.ts b/apps/web/tests/composer-paste-routing.e2e.ts new file mode 100644 index 0000000000..75a12217e7 --- /dev/null +++ b/apps/web/tests/composer-paste-routing.e2e.ts @@ -0,0 +1,169 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-subagent' +import { launchWebScaffold, selectedSessionFixture, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot } from './support.ts' + +const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const LABEL = 'event-sourcing researcher' +const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' + +/** Duplicate the base turn so the child owns its own replayed history. */ +function childFixture(source: string, fixtureId: string): string { + const [header, ...eventLines] = source.trimEnd().split('\n') + if (header === undefined) throw new Error('base replay fixture has no header') + const value = JSON.parse(header) as Record + value.id = fixtureId + return [JSON.stringify(value), ...eventLines, ''].join('\n') +} + +async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise { + const deadline = Date.now() + 30_000 + while (scaffold.ctx.agents.get(id) !== undefined) { + if (Date.now() >= deadline) throw new Error(`subagent ${id} did not settle`) + await new Promise(resolve => setTimeout(resolve, 10)) + } +} + +/** Put one PNG on the system clipboard, confirm the clipboard holds it, then paste it with the platform shortcut. */ +async function pasteImage(page: Page): Promise { + const types = await page.evaluate(async (base64) => { + const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0)) + await navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]) + return (await navigator.clipboard.read()).flatMap(item => item.types) + }, PNG_BASE64) + expect(types).toContain('image/png') + await page.keyboard.press('ControlOrMeta+V') +} + +/** Leave every control, as after clicking a transcript's empty space. */ +async function blurAll(page: Page): Promise { + await page.evaluate(() => { (document.activeElement as HTMLElement | null)?.blur() }) + expect(await page.evaluate(() => document.activeElement === document.body)).toBe(true) +} + +/** Editors of the main Conversation composer and the Sidebar chat composer. */ +const MAIN_INPUT = '[data-composer-input][contenteditable="true"]:not([data-sidebar-chat] *)' +const SIDEBAR_INPUT = '[data-sidebar-chat] [data-composer-input][contenteditable="true"]' + +/** Image thumbnails currently in each composer's draft rail. */ +async function railImages(page: Page): Promise<{ main: number; sidebar: number }> { + return page.evaluate(() => { + const count = (root: Element | null): number => + root?.querySelectorAll('[data-composer-card] img').length ?? 0 + const sidebar = document.querySelector('[data-sidebar-chat]') + const main = [...document.querySelectorAll('[data-conversation-content]')] + .find(element => sidebar === null || !sidebar.contains(element)) ?? null + return { main: count(main), sidebar: count(sidebar) } + }) +} + +describe('web e2e: composer paste routing', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let sidecarRoot: string + + beforeAll(async () => { + if (webSnapshotMode() === 'record') throw new Error('composer paste routing is a keyless assembled scenario') + const selectedBaseFixture = await selectedSessionFixture(BASE_FIXTURE) + const baseFixture = prepareSessionSnapshotFixtureForComparison(await readFile(selectedBaseFixture, 'utf8')) + sidecarRoot = await mkdtemp(join(tmpdir(), 'dsh-web-paste-')) + const childFixturePath = join(sidecarRoot, 'child.jsonl') + await writeFile(childFixturePath, childFixture(baseFixture, 'recorded-subagent')) + scaffold = await launchWebScaffold({ + replayFixture: selectedBaseFixture, + compareReplaySession: false, + replayChildFixtures: [childFixturePath], + paceMs: 25, + }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const parent = scaffold.ctx.agents.list().filter(agent => agent.session.header.origin !== 'subagent')[0] + if (parent === undefined) throw new Error('fresh workspace did not publish its parent Agent') + const parentSettled = scaffold.whenTurnSettled() + const parentInput = page.locator('[data-composer-input][contenteditable="true"]').first() + await parentInput.fill('Ask a research subagent to explain event sourcing.') + await parentInput.press('Enter') + expect(await parentSettled).toBe(parent.id) + const started = await scaffold.ctx.subagents.startActivation({ + delivery: 'parent', provider: 'spawn', label: LABEL, signal: new AbortController().signal, + prompt: [{ type: 'text', text: 'Explain event sourcing in one sentence.' }], + parent, + }) + await waitForAgentToSettle(scaffold, started.childId) + await page.getByRole('button', { name: '1 subagent', exact: true }).hover() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }) + .getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click() + await page.locator('[data-sidebar-chat] [data-composer-card]').waitFor({ timeout: 15_000 }) + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (sidecarRoot !== undefined) await rm(sidecarRoot, { recursive: true, force: true }) + }) + + it('pastes into the focused editor once and an unfocused paste into the last focused composer', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste')) + const before = await railImages(page) + await page.locator(SIDEBAR_INPUT).click() + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main, sidebar: before.sidebar + 1 }) + await blurAll(page) + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main, sidebar: before.sidebar + 2 }) + await page.locator(MAIN_INPUT).click() + await blurAll(page) + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar + 2 }) + }) + + it('ignores an unfocused paste while Settings is open', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste-modal')) + await page.locator(MAIN_INPUT).click() + await blurAll(page) + const before = await railImages(page) + await openSettings(page, 'en') + const settings = page.getByRole('dialog', { name: 'Settings' }) + await settings.waitFor() + await pasteImage(page) + await page.keyboard.press('Escape') + await settings.waitFor({ state: 'detached' }) + await blurAll(page) + // Exactly one image after a paste that would succeed: the paste behind Settings added none. + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar }) + }) + + it('sends an unfocused paste to the main composer once the focused Sidebar collapses', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste-collapsed')) + await page.locator(SIDEBAR_INPUT).click() + const before = await railImages(page) + await page.getByRole('button', { name: 'Collapse right sidebar', exact: true }).click() + await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor() + // The collapsed Sidebar keeps the chat mounted inside an inert dock section. + expect(await page.locator('[data-sidebar-chat] [data-composer-card]') + .evaluate(card => card.closest('[inert]') !== null)).toBe(true) + await blurAll(page) + try { + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar }) + } finally { + await page.getByRole('button', { name: 'Open right sidebar', exact: true }).click() + await page.locator(SIDEBAR_INPUT).waitFor() + } + }) +}) diff --git a/apps/web/tests/creator-persona.e2e.ts b/apps/web/tests/creator-persona.e2e.ts new file mode 100644 index 0000000000..c9382bbde5 --- /dev/null +++ b/apps/web/tests/creator-persona.e2e.ts @@ -0,0 +1,55 @@ +/** Creator mode adds its DSH customization intent to the actual model prompt. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import type {} from '@deepseek-ai/dsh-token-meter' +import { fixtureUserPrompts, launchWebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/creator-persona/session.v4.jsonl', import.meta.url)) +const CUSTOMIZATION_INTENT = 'You help the user customize DeepSeek Harness itself.' + +it('sends the Creator customization intent without taking actions for an ordinary request', async () => { + const scaffold = await launchWebScaffold({ + replayFixture: FIXTURE, compareReplaySession: true, paceMs: 10, + agentPresets: { default: 'cordis' }, + }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const prompts = fixtureUserPrompts(await readFile(FIXTURE, 'utf8')) + expect(prompts).toHaveLength(1) + const settled = scaffold.whenTurnSettled() + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + await composer.fill(prompts[0]!) + await composer.press('Enter') + const sessionId = await settled + const agent = scaffold.ctx.agents.get(sessionId) + if (agent === undefined) throw new Error('Creator persona session is missing') + expect(agent.session.header.agentPreset).toBe('cordis') + const system = agent.session.deriveMessages().find(message => message.role === 'system') + if (system === undefined) throw new Error('Creator request has no system prompt') + const prompt = system.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + expect(prompt).toMatch(/^You are a coding agent powered by the .+ model\. You help the user customize DeepSeek Harness itself\.$/mu) + expect(prompt.split(CUSTOMIZATION_INTENT)).toHaveLength(2) + const sharedPrompt = prompt.replace(` ${CUSTOMIZATION_INTENT}`, '') + console.info('Creator persona context increment', { + utf8Bytes: Buffer.byteLength(prompt) - Buffer.byteLength(sharedPrompt), + codePoints: Array.from(prompt).length - Array.from(sharedPrompt).length, + heuristicTokens: scaffold.ctx.tokenMeter.estimateMessage(system) + - scaffold.ctx.tokenMeter.estimateMessage({ ...system, content: [{ type: 'text', text: sharedPrompt }] }), + }) + expect(agent.session.snapshotEvents().filter(event => event.type === 'tool/call')).toEqual([]) + await page.getByText('READY', { exact: true }).waitFor() + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/cua-permissions.e2e.ts b/apps/web/tests/cua-permissions.e2e.ts index 52578a412e..d0fd1caf6d 100644 --- a/apps/web/tests/cua-permissions.e2e.ts +++ b/apps/web/tests/cua-permissions.e2e.ts @@ -31,7 +31,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr const state = join(root, 'permissions.json'), audit = join(root, 'helper-events.jsonl') const launchApplication = { name: 'DSH Computer Use.app', path: '/Applications/DSH Computer Use.app', icon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' } - await writeFile(state, JSON.stringify({ accessibility: false, screenRecording: false, launchApplication })) + await writeFile(state, JSON.stringify({ platform: 'darwin' as const, accessibility: false, screenRecording: false, launchApplication })) await writeFile(join(root, 'observe-helper'), '') const fixturePatch = join(root, 'native-fixture.yml') // Keep the external helper override above bundle order changes when CUA is re-enabled. @@ -201,7 +201,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await accessibility.getByRole('button', { name: 'Request permission', exact: true }).click() await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false') expect(await accessibility.getByRole('button', { name: 'Request permission', exact: true }).count()).toBe(1) - await writeFile(state, JSON.stringify({ accessibility: true, screenRecording: false, launchApplication })) + await writeFile(state, JSON.stringify({ platform: 'darwin' as const, accessibility: true, screenRecording: false, launchApplication })) // Returning from System Settings refreshes the page's native permission observation. await page.evaluate(() => { window.dispatchEvent(new Event('focus')) }) await accessibility.getByText('Allowed', { exact: true }).waitFor() @@ -297,7 +297,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await trace.evaluate((value) => { value.stop() }) await trace.dispose() } - await writeFile(state, JSON.stringify({ accessibility: 'unavailable', screenRecording: false })) + await writeFile(state, JSON.stringify({ platform: 'darwin', accessibility: 'unavailable', screenRecording: false })) await page.evaluate(() => { window.dispatchEvent(new Event('focus')) }) const diagnostic = panel.getByRole('alert') await diagnostic.waitFor() @@ -325,7 +325,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr } await expect.poll(() => rowToggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('false') await expect.poll(() => rowToggle.isEnabled(), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe(true) - await writeFile(state, JSON.stringify({ accessibility: false, screenRecording: false, launchApplication })) + await writeFile(state, JSON.stringify({ platform: 'darwin', accessibility: false, screenRecording: false, launchApplication })) await rowToggle.click() await expect.poll(() => rowToggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('true') await expect.poll(() => panel.getAttribute('aria-busy'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('false') diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 6033c8f06f..bd4f463f3b 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -1,9 +1,14 @@ -/** Web DeepSeek configuration, credential reuse, and saved model selection. */ +/** Web provider credentials, environment fallback, and DeepSeek model selection. */ import { readFile } from 'node:fs/promises' +import { once } from 'node:events' +import { createServer } from 'node:http' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, webkit, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { BlockAssembler, createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, @@ -12,6 +17,157 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url)) +it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'acme-gateway'])( + 'clears the saved %s key and sends the next request with environment authentication', async (provider) => { + const messages = provider === 'deepseek-official' + const google = provider === 'google' + const ref = credentialRef(messages ? 'DEEPSEEK_API_KEY' : `${provider.toUpperCase().replaceAll('-', '_')}_API_KEY`) + const envRef = google ? 'GEMINI_API_KEY' : ref + const calls: { path: string; key: string | undefined }[] = [] + const server = createServer((request, response) => { + request.on('end', () => { + const key = request.headers[messages ? 'x-api-key' : google ? 'x-goog-api-key' : 'authorization'] + calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined }) + const events = messages ? [ + { type: 'message_start', message: { id: 'clear', type: 'message', role: 'assistant', model: 'clear-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } }, + { type: 'message_stop' }, + ] : google ? [{ candidates: [{ content: { role: 'model', parts: [{ text: 'connection-ok' }] }, finishReason: 'STOP' }] }] + : [{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: 'connection-ok' }, finish_reason: null }] }, + { id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }] + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('')) + }) + request.resume() + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + let scaffold: WebScaffold | undefined + let browser: Browser | undefined + try { + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Missing credential test listener') + const baseURL = `http://127.0.0.1:${String(address.port)}/configured` + scaffold = await launchWebScaffold({ + deepSeekMissingCredential: true, + openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { [envRef]: 'fixture-environment-key' } }]), + }) + const profile = { apiKeyEnv: ref, baseURL, models: [{ id: 'clear-model' }], + ...messages || google ? {} : { api: 'openai-completions' } } + await scaffold.ctx.settings.mutate(messages ? 'llm-deepseek' : 'llm-pi-ai', [{ + op: 'set', path: messages ? [] : ['providers', provider], value: profile, + }]) + await scaffold.ctx.credentials.set(ref, 'fixture-saved-key') + const runtime = scaffold.ctx + const generate = async (): Promise => { + const assembler = new BlockAssembler() + const chunks: StreamChunk[] = [] + for await (const chunk of runtime.llm.stream({ provider, model: 'clear-model', + messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply connection-ok' }], source: { kind: 'user' } })] })) { + chunks.push(chunk) + assembler.push(chunk) + } + expect(assembler.message({ provider, model: 'clear-model' }).content, JSON.stringify(chunks)) + .toContainEqual({ type: 'text', text: 'connection-ok' }) + } + await generate() + browser = await chromium.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + await key.press('Delete') + expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) + await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'), + await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) + await dialog.getByRole('button', { name: '取消', exact: true }).click() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + await edit.click() + await key.press('Delete') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await generate() + expect(calls).toHaveLength(2) + expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key') + expect(calls[1]).toEqual({ path: calls[0]?.path, + key: messages || google ? 'fixture-environment-key' : 'Bearer fixture-environment-key' }) + expect(calls[1]?.path).toContain('/configured/') + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).not.toContain('fixture-saved-key') + await edit.click() + await dialog.getByText(`已检测到环境变量(${envRef})`, { exact: true }).waitFor() + await dialog.getByText('自定义设置', { exact: true }).click() + expect(await dialog.getByLabel('API 地址', { exact: true }).inputValue()).toBe(baseURL) + expect(await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).count()).toBe(0) + } finally { + try { await browser?.close() } finally { + try { await scaffold?.close() } finally { + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + } + } + } + }, +) + +it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( + 'protects saved keys and reveals only unsaved replacements in $name', async ({ engine }) => { + const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) + let browser: Browser | undefined + try { + await scaffold.ctx.credentials.set(credentialRef('DEEPSEEK_API_KEY'), 'fixture-protected-old-key') + browser = await engine.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`) + expect(await key.inputValue()).toBe('') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') + await key.press('Backspace') + await dialog.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() + expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') + await dialog.getByRole('button', { name: '取消', exact: true }).click() + await edit.click() + expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`) + await key.fill('fixture-new-key') + await dialog.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() + await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() + expect(await key.getAttribute('type')).toBe('text') + expect(await key.inputValue()).toBe('fixture-new-key') + await key.press('ControlOrMeta+A') + await key.press('ControlOrMeta+X') + await expect.poll(() => key.inputValue()).toBe('') + await key.fill('fixture-new-key') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await edit.click() + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length)) + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('type')).toBe('password') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key') + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } + }, +) + it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( 'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => { const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) @@ -90,6 +246,10 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1) await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click() const messages = dialog + const key = messages.getByLabel('API 密钥', { exact: true }) + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('placeholder')).toBe(`sk-messa${'•'.repeat(10)}ding`) + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') @@ -114,6 +274,17 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages') expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY') expect(await page.locator('body').innerText()).not.toContain('sk-e2e-') + await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click() + expect(await key.inputValue()).toBe('') + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() + expect(await key.getAttribute('type')).toBe('password') + await key.fill('sk-cancelled-replacement') + await messages.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() + expect(await messages.getByText('使用已保存的 API key。', { exact: true }).count()).toBe(0) + await key.fill('') + await messages.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() + await messages.getByRole('button', { name: '取消', exact: true }).click() + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) await page.keyboard.press('Escape') await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e') await page.getByRole('button', { name: /^选择模型/ }).click() diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index c275135057..8283fb7125 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -51,21 +51,21 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => screenshots = undefined root = await mkdtemp(join(tmpdir(), 'dsh-desktop-onboarding-')) server = createServer((request, response) => { - if (request.url === '/api/v0/users/get_unnotified_bonuses') { + if (request.url === '/api/v0/users/notifications/list') { bonusReads++ response.setHeader('content-type', 'application/json') - response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: bonusOffered ? [{ - order_id: '88888888-8888-4888-8888-888888888888', campaign: 'dsh_login_bonus', - amount: '5.00', currency: 'CNY', granted_at: new Date().toISOString(), - expires_at: new Date(Date.now() + 86_400_000).toISOString(), msg: '已赠送您 5.00 元 DSH 体验赠金。', - }] : [] } })) + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { next_poll_after: 600, notifications: bonusOffered ? [{ + id: '88888888-8888-4888-8888-888888888888', type: 'account.bonus_granted', + created_at: new Date().toISOString(), title: '赠金已到账', actions: [], + display_until: new Date(Date.now() + 86_400_000).toISOString(), body: '已赠送您 5.00 元 DSH 体验赠金。', + }] : [] } } })) return } - if (request.url === '/api/v0/users/ack_bonus_notified') { + if (request.url === '/api/v0/users/notifications/events') { bonusAcks++ bonusOffered = false response.setHeader('content-type', 'application/json') - response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: null } })) + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { acked: true } } })) return } if (request.url !== '/auth-api/v0/users/current' && request.url !== '/api/v0/users/get_user_summary') { @@ -85,7 +85,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => if (address === null || typeof address === 'string') throw new Error('fixture server address unavailable') origin = `http://127.0.0.1:${address.port}` const overlay = join(root, 'account.patch.yml') - await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n allowLoopbackHttp: true\n`) + await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n harnessOrigin: ${origin}\n allowLoopbackHttp: true\n`) scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, extraOverlayPath: overlay }) await scaffold.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), async () => ({ kind: 'grant', payload: { version: 1, issuer: origin, token: 'onboarding-fixture-token' }, diff --git a/apps/web/tests/desktop-updates.e2e.ts b/apps/web/tests/desktop-updates.e2e.ts index ac596249b3..0fb963b7ea 100644 --- a/apps/web/tests/desktop-updates.e2e.ts +++ b/apps/web/tests/desktop-updates.e2e.ts @@ -74,11 +74,10 @@ describe('web e2e: Desktop update workspace chrome', () => { await publish(progress) const downloading = page.getByRole('button', { name: '58%', exact: true }) await downloading.waitFor() - expect(await downloading.getAttribute('aria-disabled')).toBe('true') + expect(await downloading.getAttribute('aria-disabled')).toBe('false') expect(await downloading.locator('svg').count()).toBe(1) - // Force dispatch past Playwright's aria-disabled guard to verify the product's click guard. - await downloading.click({ force: true }) - expect(await opens()).toBe(1) + await downloading.click() + await expect.poll(opens).toBe(2) await page.screenshot({ path: join(evidence, 'downloading.png') }) const collapse = locale === 'zh-CN' ? '收起侧边栏' : 'Collapse sidebar' @@ -118,21 +117,21 @@ describe('web e2e: Desktop update workspace chrome', () => { await expect.poll(() => tooltip.evaluateAll(elements => elements.map(element => getComputedStyle(element).opacity))).toEqual(['1']) await page.screenshot({ path: join(evidence, 'retry.png') }) await retry.click() - await expect.poll(opens).toBe(2) + await expect.poll(opens).toBe(3) await publish(presentDesktopUpdate({ phase: 'ready', version })) const ready = page.getByRole('button', { name: readyLabel, exact: true }) await ready.waitFor() expect(await ready.getAttribute('aria-disabled')).toBe('false') - expect(await opens()).toBe(2) + expect(await opens()).toBe(3) await page.screenshot({ path: join(evidence, 'ready.png') }) await ready.click() - await expect.poll(opens).toBe(3) + await expect.poll(opens).toBe(4) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) expect(await page.evaluate(() => (window as FixtureWindow).updateFixture.listeners.size)).toBe(1) await writeFile(join(evidence, 'result.json'), JSON.stringify({ locale, geometry, updateBackground, failedBackground, - passed: true, explicitActions: 3, carrier: 'substituted', host: 'real Web composition', + passed: true, explicitActions: 4, carrier: 'substituted', host: 'real Web composition', electron: false, installerExecuted: false }, null, 2) + '\n') console.log(`Desktop workspace chrome evidence: ${evidence}`) } catch (error) { diff --git a/apps/web/tests/expected/account-login/avatar-retry.expected.md b/apps/web/tests/expected/account-login/avatar-retry.expected.md index 4106b7eb4b..e86b065689 100644 --- a/apps/web/tests/expected/account-login/avatar-retry.expected.md +++ b/apps/web/tests/expected/account-login/avatar-retry.expected.md @@ -1,6 +1,6 @@ -Initial load: sidebar=failed, settings=unmounted, sidebarImages=0, settingsImages=0, requests=1 -First Settings entry: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=2 -Second Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 -Third Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 -Rendered image failure: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=3 -Settings entry after rendered failure: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 +Initial load: sidebar=failed, settings=unmounted, sidebarImages=0, settingsImages=0, requests=1, notificationLists=1 +First Settings entry: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=2, notificationLists=2 +Second Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=3 +Third Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=4 +Rendered image failure: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=3, notificationLists=4 +Settings entry after rendered failure: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=5 diff --git a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md index c4ff30f121..08f4861da9 100644 --- a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md +++ b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md @@ -1,11 +1,14 @@ startup.held cards=0 acks=0 startup.notice=平台通知 / 已赠送您 5.00 元 DSH 体验赠金。 -startup.ack orders=bonus-notice-first +startup.ack orders=notice-first +startup.unsupported-action skipped=true valid-card=true displayed=false +startup.profile-pending notice=true displayed=1 startup.get locale=zh_CN query= -startup.ack method=POST path=/api/v0/users/ack_bonus_notified locale=zh_CN order_id=bonus-notice-first body="{\"order_id\":\"bonus-notice-first\"}" +startup.ack method=POST path=/api/v0/users/notifications/events locale=zh_CN notification_id=notice-first body="{\"notification_id\":\"notice-first\",\"type\":\"displayed\"}" +startup.close event=dismissed displayed=1 dismissed=1 open.held cards=0 acks=1 gets=1 open.shown notice=赠金已到账 / 已赠送您 8.00 元 DSH 体验赠金。 -open.shown ack orders=bonus-notice-first,33333333-3333-4333-8333-333333333333 +open.shown ack orders=notice-first,notice-later open.shown painted-under-settings=true cards=1 acks=2 open.get locale=zh_CN query= served=true gets=1 open.balance bonus-row=true amount=true dated=false @@ -21,8 +24,8 @@ topup.returned bridge=open:top-up,close cards=0 topup.notice=赠金已到账 / 已赠送您 11.00 元 DSH 体验赠金。 topup.refresh gets=2 summaries=2 acks=1 recharge=true bonus=true topup.closed cards=1 acks=1 -retry.notice=赠金已到账 / 已赠送您 6.00 元 DSH 体验赠金。 -retry.attempts=2 backoff=true body-kept=true cards=1 +event-failed.notice=赠金已到账 / 已赠送您 6.00 元 DSH 体验赠金。 +event-failed.attempts=1 body-kept=true cards=1 repeat.first=赠金已到账 / 已赠送您 7.00 元 DSH 体验赠金。 repeat.reload=赠金已到账 / 已赠送您 7.00 元 DSH 体验赠金。 repeat.shown added-storage-keys=0 reload-added=0 acks=2 cards=1 @@ -31,6 +34,19 @@ failed.reached usages=2 gets=1 summaries=1 en.notice=Bonus credited / You received a CNY 9.00 DSH trial credit. en.get locale=en_US query= web.notice=赠金已到账 / 已赠送您 4.00 元 DSH 体验赠金。 acks=1 -stack.initial cards=3 acks=stack-first widths=280,272 offset=-4 transition=0.25s ease-out -stack.promoted cards=2 acks=stack-first,stack-second width=280 same-node=true +stack.hidden cards=3 acks=0 +stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=0.25s ease-out +stack.resized sidebar=360 card=280 left-inset=10 +stack.resized sidebar=280 card=260 left-inset=10 +stack.rail cards=3 visible=false dismissed=0 +stack.expanded cards=3 duplicate-acks=0 dismissed=0 +stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true stack.dismissed cards=0 acks=stack-first,stack-second,stack-third +refresh.retained cards=3 acks=refresh-first same-node=true +refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true +refresh.business-action event=cta_clicked cards=3 account-open=true +refresh.drawer width=390 notice-above-sidebar=true +refresh.action event=dismissed got-it=true +refresh.promoted cards=2 acks=refresh-first,refresh-second +refresh.dismissed cards=0 acks=refresh-first,refresh-second,refresh-third +poll.arrival cards=2 list-reads=1 duplicate-acks=0 same-node=true settings-immediate-read=true diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 93993bbe04..5a3a367e7a 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: sk-messa••••••••••ding + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md new file mode 100644 index 0000000000..b1c8c2f328 --- /dev/null +++ b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md @@ -0,0 +1,25 @@ +- dialog "设置": + - text: 设置 + - navigation: + - button "通用设置" + - button "模型" + - button "内置插件" + - button "Agent 预设" + - button "打开配置文件" + - button "关闭" + - heading "模型" [level=2] + - paragraph: 填入各提供商的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: DeepSeek + - img "API 密钥已配置" + - button "编辑 DeepSeek (deepseek-official)": 编辑 + - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" + - textbox "API 密钥": + - /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY) + - paragraph: 保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。 + - group: 自定义设置 + - button "取消" + - button "保存" + - button "添加模型提供商" diff --git a/apps/web/tests/expected/forge-panel/review-quotes.expected.md b/apps/web/tests/expected/forge-panel/review-quotes.expected.md index 0f7262a4b1..292dd3382f 100644 --- a/apps/web/tests/expected/forge-panel/review-quotes.expected.md +++ b/apps/web/tests/expected/forge-panel/review-quotes.expected.md @@ -1,6 +1,6 @@ - textbox "发消息或创建任务, / 调用指令, @ 文件或对话": - paragraph: - button "移除引用" - - text: "## User Comment 2 File: src/extra.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const extra = 1 ``` Comment: 请检查这项修改" + - text: src/extra.ts R1 请检查这项修改 - button "移除引用" - - text: "## User Comment 1 File: src/app.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const app = 1 ``` Comment: 请解释这行代码" + - text: src/app.ts R1 请解释这行代码 diff --git a/apps/web/tests/expected/models-settings/declared-edit.expected.md b/apps/web/tests/expected/models-settings/declared-edit.expected.md index 85aa3923d0..c8f652fbf3 100644 --- a/apps/web/tests/expected/models-settings/declared-edit.expected.md +++ b/apps/web/tests/expected/models-settings/declared-edit.expected.md @@ -36,6 +36,7 @@ - option "OpenAI Chat Completions" [selected] - option "OpenAI Responses" - option "Anthropic Messages" + - option "Gemini API" - group "重试策略": - text: 重试策略 - combobox "重试策略": diff --git a/apps/web/tests/expected/models-settings/image-only.expected.md b/apps/web/tests/expected/models-settings/image-only.expected.md index 9645929155..051df42792 100644 --- a/apps/web/tests/expected/models-settings/image-only.expected.md +++ b/apps/web/tests/expected/models-settings/image-only.expected.md @@ -36,6 +36,7 @@ - option "OpenAI Chat Completions" - option "OpenAI Responses" - option "Anthropic Messages" [selected] + - option "Gemini API" - group "重试策略": - text: 重试策略 - combobox "重试策略": diff --git a/apps/web/tests/expected/models-settings/mobile-collapsed.expected.md b/apps/web/tests/expected/models-settings/mobile-collapsed.expected.md index 2f573f6e53..c052e8c61f 100644 --- a/apps/web/tests/expected/models-settings/mobile-collapsed.expected.md +++ b/apps/web/tests/expected/models-settings/mobile-collapsed.expected.md @@ -36,6 +36,7 @@ - option "OpenAI Chat Completions" - option "OpenAI Responses" - option "Anthropic Messages" [selected] + - option "Gemini API" - group "重试策略": - text: 重试策略 - combobox "重试策略": diff --git a/apps/web/tests/expected/models-settings/mobile-expanded.expected.md b/apps/web/tests/expected/models-settings/mobile-expanded.expected.md index 5e0855c653..69444fb808 100644 --- a/apps/web/tests/expected/models-settings/mobile-expanded.expected.md +++ b/apps/web/tests/expected/models-settings/mobile-expanded.expected.md @@ -36,6 +36,7 @@ - option "OpenAI Chat Completions" - option "OpenAI Responses" - option "Anthropic Messages" [selected] + - option "Gemini API" - group "重试策略": - text: 重试策略 - combobox "重试策略": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index a7be30e8c3..3bd004257e 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index b369a619b4..5b10207801 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md index 5d275c2323..a7bb6c76e3 100644 --- a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md +++ b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md @@ -3,7 +3,7 @@ - status - switch "启用 @fixture/missing-bundle" [checked] - heading "@fixture/missing-bundle" [level=3] -- text: 异常 未安装 +- text: 未运行 未安装 - paragraph: - code: "@fixture/missing-bundle" - status: "原因: dsh: cannot resolve profile bundle \"@fixture/missing-bundle\" from the dsh installation or {{home}}/profiles/scaffold; run 'dsh plugin --profile scaffold install' if its dependency is not installed" diff --git a/apps/web/tests/expected/retained-steering/trajectory.expected.md b/apps/web/tests/expected/retained-steering/trajectory.expected.md index 1cf298260c..c453914925 100644 --- a/apps/web/tests/expected/retained-steering/trajectory.expected.md +++ b/apps/web/tests/expected/retained-steering/trajectory.expected.md @@ -9,9 +9,9 @@ - 'row "CONTEXT, The following information describes your current session: Current working directory: \"{{cwd}}/workspace\". Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}/workspace\". Some platform te…"': - cell "CONTEXT" - 'cell " The following information describes your current session: Current working directory: \"{{cwd}}/workspace\". Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}/workspace\". Some platform te…"' - - 'row "CONTEXT, A skill is a reusable set of task-specific instructions. The following skills are available in this session: office: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step. office-docx: Create, read, edit, and validate Word documents (.docx). office-pptx: Create, read, edit, and validate PowerPoint presentations (.pptx). office-xlsx: Read, cr…"': + - 'row "CONTEXT, A skill is a reusable set of task-specific instructions. The following skills are available in this session: dsh-doc: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skil…"': - cell "CONTEXT" - - 'cell " A skill is a reusable set of task-specific instructions. The following skills are available in this session: office: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step. office-docx: Create, read, edit, and validate Word documents (.docx). office-pptx: Create, read, edit, and validate PowerPoint presentations (.pptx). office-xlsx: Read, cr…"' + - 'cell " A skill is a reusable set of task-specific instructions. The following skills are available in this session: dsh-doc: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skil…"' - 'row "CONTEXT, Time sampled while preparing turn 1, step 1: 2026-01-15T{{clock}}+{{clock}}[Asia/Shanghai] Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone. Elapsed since the preceding model-visible message: unavailable."': - cell "CONTEXT" - 'cell "Time sampled while preparing turn 1, step 1: 2026-01-15T{{clock}}+{{clock}}[Asia/Shanghai] Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone. Elapsed since the preceding model-visible message: unavailable."' diff --git a/apps/web/tests/fixtures/account-login/cordis.patch.yml b/apps/web/tests/fixtures/account-login/cordis.patch.yml index a31eac8f46..c61c6bfbbf 100644 --- a/apps/web/tests/fixtures/account-login/cordis.patch.yml +++ b/apps/web/tests/fixtures/account-login/cordis.patch.yml @@ -4,6 +4,7 @@ - id: deepseek-account config: platformOrigin: "{{origin}}" + harnessOrigin: "{{origin}}" allowLoopbackHttp: true # The scenario signs in from the account menu after initial setup. - id: ui-settings-account diff --git a/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml b/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml index 11e43d1493..a3a7a9129c 100644 --- a/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml +++ b/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml @@ -1,13 +1,17 @@ # The bonus notice scenario points the shipped account provider at a loopback # Platform double. The scaffold substitutes {{origin}} after the listener binds, -# so no port is ever committed here. No notice timing is overridden: every read -# comes from the product's own startup and settings-refresh paths. +# so no port is ever committed here. A long query interval isolates other notice +# interactions; the polling scenario advances the browser clock explicitly. - id: deepseek-account config: platformOrigin: "{{origin}}" + harnessOrigin: "{{origin}}" allowLoopbackHttp: true # This scenario exercises the account launcher after initial setup. - id: ui-settings-account config: step: done completion: completed +- id: ui-account-notifications + config: + notificationPollIntervalMs: 7200000 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 6654187eb8..44f24a6a58 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -892,10 +892,13 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() expect(await resizeTree.getAttribute('aria-valuenow')).toBe(rightWidth) for (const side of ['old', 'new'] as const) { - const firstLine = await panelFile.locator(`[data-review-code][data-${side}-line="2"]`).boundingBox() + const firstCode = panelFile.locator(`[data-review-code][data-${side}-line="2"]`) + const firstLine = await firstCode.boundingBox() const lastLine = await panelFile.locator(`[data-review-code][data-${side}-line="4"]`).boundingBox() if (firstLine === null || lastLine === null) throw new Error('Review text must be visible') - await page.mouse.move(firstLine.x + 7, firstLine.y + firstLine.height / 2) + // Press on the first character, past the lane where the hovered row shows its comment plus. + const textStart = await firstCode.evaluate(element => Number.parseFloat(getComputedStyle(element).paddingLeft)) + await page.mouse.move(firstLine.x + textStart + 1, firstLine.y + firstLine.height / 2) await page.mouse.down() await page.mouse.move(lastLine.x + 120, lastLine.y + lastLine.height / 2, { steps: 5 }) await page.mouse.up() @@ -1170,6 +1173,109 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre expect(tripwire.warnings).toEqual([]) }) +it.skipIf(MODE === 'record')('opens a comment from the hover plus in one press without covering the line number or the code', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-hover-plus') + // notes.txt changes into context, a deletion followed by context, and an addition, so unified rows show both numbers. + await writeFile(join(project, 'notes.txt'), ['keep 1', 'keep 2', 'drop 3', 'keep 4', 'keep 5', 'keep 6'].map(line => `${line}\n`).join('')) + await git(project, 'add', 'notes.txt') + await git(project, 'commit', '--quiet', '-m', 'notes') + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await writeFile(join(project, 'README.md'), `changed\n${Array.from({ length: 8 }, (_, line) => `line ${line + 2}\n`).join('')}`) + await writeFile(join(project, 'notes.txt'), ['keep 1', 'keep 2', 'keep 4', 'keep 5', 'added', 'keep 6'].map(line => `${line}\n`).join('')) + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.locator('[data-forge-header]').click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更/ }).click() + const view = page.locator('[data-forge-changes="local"]') + const file = view.locator('[data-forge-diff-file="README.md"]') + const number = (name: string) => file.getByRole('button', { name: `选择第 ${name} 行`, exact: true }) + const plus = (name: string) => file.locator(`[data-review-add="${name}"]`) + const code = (line: number) => file.locator(`[data-review-code][data-new-line="${line}"]`) + const draggable = async (from: string, to: string) => { + const start = await plus(from).boundingBox(), end = await number(to).boundingBox() + if (start === null || end === null) throw new Error('The plus and the line number must be rendered') + const x = start.x + start.width / 2 + return { start: { x, y: start.y + start.height / 2 }, end: { x, y: end.y + end.height / 2 } } + } + await number('R3').waitFor() + + // The plus appears only on the hovered side of the hovered row, for the code as for the line number. + expect(await plus('R3').isVisible()).toBe(false) + await code(3).hover() + expect(await plus('R3').isVisible()).toBe(true) + expect(await plus('R4').isVisible()).toBe(false) + expect(await plus('L1').isVisible()).toBe(false) + await number('L1').hover() + expect(await plus('L1').isVisible()).toBe(true) + expect(await plus('R3').isVisible()).toBe(false) + + // Playwright refuses a click on a covered point, so these prove the hovered number and first character stay reachable. + await number('R3').hover() + await number('R3').click() + expect(await number('R3').getAttribute('aria-pressed')).toBe('true') + const first = await code(5).boundingBox() + const textStart = await code(5).evaluate(element => Number.parseFloat(getComputedStyle(element).paddingLeft)) + if (first === null) throw new Error('Review text must be visible') + await page.mouse.move(first.x + textStart + 1, first.y + first.height / 2) + await page.mouse.down() + await page.mouse.move(first.x + textStart + 30, first.y + first.height / 2, { steps: 3 }) + await page.mouse.up() + expect(await page.evaluate(() => document.getSelection()?.toString())).toMatch(/^li/) + await page.evaluate(() => { document.getSelection()?.removeAllRanges() }) + + // One press selects, a drag extends within the side, and the release opens the editor. + await code(6).hover() + const { start, end } = await draggable('R6', 'R8') + await page.mouse.move(start.x, start.y) + await page.mouse.down() + await page.mouse.move(end.x, end.y, { steps: 5 }) + expect(await number('R8').getAttribute('aria-pressed')).toBe('true') + expect(await file.getByRole('textbox').count()).toBe(0) + await page.mouse.up() + await file.getByRole('region', { name: '评论 R6–8', exact: true }).waitFor() + expect(await plus('R6').count()).toBe(0) + await file.getByRole('button', { name: '取消', exact: true }).click() + await file.getByRole('textbox').waitFor({ state: 'detached' }) + + // The single-column layout keeps the same gesture on the line's own side. + await view.getByRole('button', { name: '左右对比', exact: true }).click() + await file.locator('[data-diff-line]').first().waitFor() + await code(4).hover() + expect(await plus('R4').isVisible()).toBe(true) + await number('R4').click() + expect(await number('R4').getAttribute('aria-pressed')).toBe('true') + + // With both numbers shown, a deleted line's plus sits where a context line's does: in the sign column. + const notes = view.locator('[data-forge-diff-file="notes.txt"]') + const notesPlus = (name: string) => notes.locator(`[data-review-add="${name}"]`) + const notesCode = (side: 'old' | 'new', line: number) => notes.locator(`[data-review-code][data-${side}-line="${line}"]`) + await notesCode('new', 3).hover() + const contextPlus = await notesPlus('R3').boundingBox() + await notesCode('old', 3).hover() + const deletedPlus = await notesPlus('L3').boundingBox() + const nextRow = await notesCode('old', 4).boundingBox() + if (contextPlus === null || deletedPlus === null || nextRow === null) throw new Error('The pluses and the next row must be rendered') + expect(deletedPlus.x).toBe(contextPlus.x) + // A drag from the deleted line's plus extends through the context row below it on the old side. + const x = deletedPlus.x + deletedPlus.width / 2 + await page.mouse.move(x, deletedPlus.y + deletedPlus.height / 2) + await page.mouse.down() + await page.mouse.move(x, nextRow.y + nextRow.height / 2, { steps: 5 }) + await page.mouse.up() + await notes.getByRole('region', { name: '评论 L3–4', exact: true }).waitFor() + await notes.getByRole('button', { name: '取消', exact: true }).click() + await notes.getByRole('textbox').waitFor({ state: 'detached' }) + // The labeled plus of a left context line stays reachable; Playwright refuses a covered target. + await notes.getByRole('button', { name: '选择第 L2 行', exact: true }).click() + expect((await notes.getByRole('button', { name: '添加评论', exact: true }).boundingBox())?.x).toBe(contextPlus.x) + await notes.getByRole('button', { name: '添加评论', exact: true }).click() + await notes.getByRole('region', { name: '评论 L2', exact: true }).waitFor() + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record')('keeps tall branch and changed-file menus aligned with their triggers', async () => { const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-tall-menus') await Promise.all(Array.from({ length: 45 }, (_, index) => diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 58d76d04f1..d467ccc230 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() - await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByPlaceholder('•'.repeat('sk-e2e-minimax'.length), { exact: true }).waitFor({ timeout: 10_000 }) expect(await dialog.textContent()).not.toContain('API 密钥来源:') expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() @@ -298,7 +298,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { // The custom-API mode is the second segment of the one add card; its // purpose line replaces the catalog one. await dialog.getByRole('tab', { name: '自定义模型 API' }).click() - await dialog.getByText('连接中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口,需填写 API 地址、协议和模型。').waitFor({ timeout: 10_000 }) + await dialog.getByText('连接中转站、自部署服务或其他兼容 OpenAI / Anthropic / Gemini 协议的接口,需填写 API 地址、协议和模型。').waitFor({ timeout: 10_000 }) // The third-party panel stays mounted, hidden, beside this one, so the // form is addressed through its own panel. const custom = dialog.getByRole('tabpanel', { name: '自定义模型 API' }) diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8706a7a4de..d8d5b9356f 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -33,6 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup let page: Page let tripwire: ReturnType const browserConsole: string[] = [] + const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test` beforeAll(async () => { scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true }) @@ -86,7 +87,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE) - const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}` await keyInput.fill(secret) await credentialStep.getByRole('button', { name: '保存并继续' }).click() await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) @@ -115,7 +115,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe(`dsh_onboa${'•'.repeat(31)}test`) const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -257,7 +257,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe(`dsh_onboa${'•'.repeat(31)}test`) const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() diff --git a/apps/web/tests/settings-appearance.e2e.ts b/apps/web/tests/settings-appearance.e2e.ts index fa55a444df..26be4bdedc 100644 --- a/apps/web/tests/settings-appearance.e2e.ts +++ b/apps/web/tests/settings-appearance.e2e.ts @@ -149,7 +149,7 @@ it('shares settings card materials and control sizes in both palettes', async () bonusWallets: [{ currency: 'CNY', balance: '12.00' }], }), vi.spyOn(account, 'watch').mockImplementation(async function* (signal) { - yield state + yield { type: 'snapshot', state } if (signal.aborted) return await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) }), diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index ba6bcc0cca..36b74d0e88 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -823,7 +823,7 @@ it('routes one browser-authored Auto request through the same model and asks the event.type === 'tool/result' && event.data.message.toolCallId === AUTO_CALL_ID )) - expect(result?.data.error).toBeUndefined() + expect(result?.data.error).toEqual({ name: 'ApprovalError', code: 'APPROVAL_REJECTED' }) const durableModelResult = JSON.stringify(result?.data.message) expect(durableModelResult).toContain('the user rejected tool \\"bash\\"') expect(durableModelResult).not.toContain('direct user authorized inspection only') diff --git a/apps/web/tests/sidebar-alignment.e2e.ts b/apps/web/tests/sidebar-alignment.e2e.ts index ed5fced520..7f5ecdeabe 100644 --- a/apps/web/tests/sidebar-alignment.e2e.ts +++ b/apps/web/tests/sidebar-alignment.e2e.ts @@ -519,7 +519,7 @@ describe('web e2e: sidebar search alignment and row action targets', () => { }), vi.spyOn(account, 'getBalance').mockResolvedValue({ status: 'ready', value: [], bonusWallets: [] }), vi.spyOn(account, 'watch').mockImplementation(async function* (signal) { - yield state + yield { type: 'snapshot', state } if (signal.aborted) return await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) }), diff --git a/apps/web/tests/standard-dsh-doc.e2e.ts b/apps/web/tests/standard-dsh-doc.e2e.ts new file mode 100644 index 0000000000..26d920ac98 --- /dev/null +++ b/apps/web/tests/standard-dsh-doc.e2e.ts @@ -0,0 +1,51 @@ +/** Standard mode offers the installed documentation skill without loading it for an unrelated task. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { dirname } from 'node:path' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { assertFixtureInventory, fixtureUserPrompts, launchWebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/standard-dsh-doc/session.v4.jsonl', import.meta.url)) + +it('lists dsh-doc once without loading instructions or calling tools for an ordinary task', async () => { + const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, compareReplaySession: true, paceMs: 10 }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const prompts = fixtureUserPrompts(await readFile(FIXTURE, 'utf8')) + expect(prompts).toHaveLength(1) + const settled = scaffold.whenTurnSettled() + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + await composer.fill(prompts[0]!) + await composer.press('Enter') + const sessionId = await settled + const agent = scaffold.ctx.agents.get(sessionId) + if (agent === undefined) throw new Error('standard documentation session is missing') + const events = agent.session.snapshotEvents() + expect(events.filter(event => event.type === 'tool/call')).toEqual([]) + const catalogs = events.flatMap(event => event.type === 'user/message' + && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + expect(catalogs).toHaveLength(1) + const skills = await scaffold.ctx.skills.list({ cwd: agent.session.header.cwd, scope: agent }) + expect(skills.filter(skill => skill.name === 'dsh-doc')).toHaveLength(1) + expect(catalogs[0]?.source).toMatchObject({ entries: skills.map(skill => ({ name: skill.name })) }) + expect(events.filter(event => event.type === 'user/message' + && event.data.source.kind === 'skill-invocation')).toEqual([]) + const names = scaffold.ctx.tools.schemas(agent).map(tool => tool.name) + expect(names).not.toContain('cordis_inspect_list') + expect(names).not.toContain('cordis_inspect_query') + await page.getByText('READY', { exact: true }).waitFor() + await assertFixtureInventory(dirname(FIXTURE), ['session.v4.jsonl']) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 7294b2fd47..9e6e59f142 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -210,6 +210,8 @@ "tests/queue-image.e2e.ts", "tests/skill-invocation-policy.e2e.ts", "tests/skill-user-invoke.e2e.ts", + "tests/standard-dsh-doc.e2e.ts", + "tests/creator-persona.e2e.ts", "tests/skill-menu-plugin-change.e2e.ts", "tests/permission-policy-context.e2e.ts", "tests/access-confirmation.e2e.ts", @@ -230,6 +232,7 @@ "tests/goal-bar.e2e.ts", "tests/goal-command-presentation.e2e.ts", "tests/subagent-conversation.e2e.ts", + "tests/composer-paste-routing.e2e.ts", "tests/subagent-interrupt.e2e.ts", "tests/subagent-interrupt-ui.e2e.ts", "tests/sidebar-subagent-activity.e2e.ts", diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 36b947a177..39c754498f 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 6355651b822ad47c - zh: dadfa336d8881ad7 + en: 484321127d29936b + zh: 136af4ad9c3472ea diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 274e18f9ea..a2b2f1e1bd 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -28,6 +28,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -142,8 +144,6 @@ flowchart LR pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] - pkg_deepseek_account_platform["deepseek-account-platform"] - pkg_api_account_controller["api-account-controller"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -214,7 +214,7 @@ flowchart LR pkg_mcp_manager["mcp-manager"] svc_mcpManager["ctx.mcpManager
Settings-driven MCP server fleet"] svc_mcpClientHost["ctx.mcpClientHost
MCP client host for a server manager"] - pkg_client_ui_mcp_account["client-ui-mcp-account"] + pkg_mcp_account["mcp-account"] svc_mcpAccounts["ctx.mcpAccounts
MCP connector accounts on the Plugins page"] pkg_schedule["schedule"] svc_schedule["ctx.schedule
Host scheduled messages"] @@ -349,7 +349,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics - pkg_client_ui_mcp_account --> svc_mcpAccounts + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -364,7 +364,6 @@ flowchart LR pkg_credentials_local --> svc_credentials pkg_cua --> svc_cuaAccess pkg_deepseek_account --> svc_deepseekAccount - pkg_deepseek_account_platform --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_api_speech_to_text --> svc_speechController pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse @@ -407,6 +406,7 @@ flowchart LR pkg_llm_replay --> svc_llm pkg_lsp --> svc_lsp pkg_lsp_stdio --> svc_lsp + pkg_mcp_account --> svc_mcpAccounts pkg_mcp_client --> svc_mcpClientHost pkg_mcp_client --> svc_mcpResources pkg_mcp_manager --> svc_mcpManager @@ -523,7 +523,6 @@ flowchart LR svc_credentials --> pkg_llm_deepseek svc_credentials --> pkg_llm_pi_ai svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_api_account_controller svc_deepseekAccount --> pkg_llm_deepseek svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller @@ -669,6 +668,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | @@ -710,7 +710,7 @@ flowchart LR | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. | | `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. | -| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | Product analytics and Session feedback adapters create independent reporting channels through one injected service. | @@ -738,8 +738,8 @@ flowchart LR | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. | | `ctx.mcpManager` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | Reconciles mcp-client instances against its volatile servers configuration, aggregates their connection statuses, and serves restart and probe to management surfaces. | -| `ctx.mcpClientHost` | `service` | [`mcp-client`](../packages/mcp/mcp-client) | - | [`mcp-manager`](../packages/mcp/mcp-manager) | - | An mcp-client entry loaded with host: true validates, mounts, probes, and authorizes servers for the manager, which reaches no other mcp-client value; its servers run below it, so a reload of the MCP client restarts the manager. | -| `ctx.mcpAccounts` | `service` | [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | - | - | - | Holds the accounts MCP connector plugins register and serves them, with the manager's view of each server, to the Plugins page through one Remote; authorization runs through the manager. | +| `ctx.mcpClientHost` | `service` | [`mcp-client`](../packages/mcp/mcp-client) | - | [`mcp-manager`](../packages/mcp/mcp-manager) | - | The manager creates it to validate, mount, probe, and authorize servers, and reaches no other mcp-client value; its servers run below the manager. | +| `ctx.mcpAccounts` | `service` | [`mcp-account`](../packages/mcp/mcp-account) | - | - | - | Shows the OAuth server account each MCP connector plugin registers through the connector account registry; the page's operations run through the manager. | | `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in each task's target Session. | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. | | `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | Owns one authenticated OpenSSH connection, installed helper identity, independent program streams and disconnect cleanup for the paired remote providers. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 695e10a3ac..40880eae54 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -30,6 +30,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -144,8 +146,6 @@ flowchart LR pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] - pkg_deepseek_account_platform["deepseek-account-platform"] - pkg_api_account_controller["api-account-controller"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -216,7 +216,7 @@ flowchart LR pkg_mcp_manager["mcp-manager"] svc_mcpManager["ctx.mcpManager
Settings-driven MCP server fleet"] svc_mcpClientHost["ctx.mcpClientHost
MCP client host for a server manager"] - pkg_client_ui_mcp_account["client-ui-mcp-account"] + pkg_mcp_account["mcp-account"] svc_mcpAccounts["ctx.mcpAccounts
MCP connector accounts on the Plugins page"] pkg_schedule["schedule"] svc_schedule["ctx.schedule
Host scheduled messages"] @@ -351,7 +351,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics - pkg_client_ui_mcp_account --> svc_mcpAccounts + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -366,7 +366,6 @@ flowchart LR pkg_credentials_local --> svc_credentials pkg_cua --> svc_cuaAccess pkg_deepseek_account --> svc_deepseekAccount - pkg_deepseek_account_platform --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_api_speech_to_text --> svc_speechController pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse @@ -409,6 +408,7 @@ flowchart LR pkg_llm_replay --> svc_llm pkg_lsp --> svc_lsp pkg_lsp_stdio --> svc_lsp + pkg_mcp_account --> svc_mcpAccounts pkg_mcp_client --> svc_mcpClientHost pkg_mcp_client --> svc_mcpResources pkg_mcp_manager --> svc_mcpManager @@ -525,7 +525,6 @@ flowchart LR svc_credentials --> pkg_llm_deepseek svc_credentials --> pkg_llm_pi_ai svc_cuaAccess --> pkg_cua - svc_deepseekAccount --> pkg_api_account_controller svc_deepseekAccount --> pkg_llm_deepseek svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller @@ -671,6 +670,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | 保存 CLI 应用插件和 MCP 连接器注册的账号,并通过一个 Remote 把 Host 算好的展示内容提供给插件页;授权页和提示只出现在发起操作的浏览器中。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | @@ -712,7 +712,7 @@ flowchart LR | `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. | | `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 | | `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 | -| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 | +| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 | | `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 | | `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 | | `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | 产品埋点和 Session 反馈适配器通过同一个注入服务创建独立上报通道。 | @@ -740,8 +740,8 @@ flowchart LR | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 | | `ctx.mcpManager` | `core` | [`mcp-manager`](../packages/mcp/mcp-manager) | - | - | - | 依据自身 volatile servers 配置对账 mcp-client 实例,聚合它们的连接状态,并向管理界面提供 restart 与 probe。 | -| `ctx.mcpClientHost` | `service` | [`mcp-client`](../packages/mcp/mcp-client) | - | [`mcp-manager`](../packages/mcp/mcp-manager) | - | 以 `host: true` 加载的 mcp-client 条目为管理器校验、挂载、探测和授权服务器,管理器只经由它使用 mcp-client;服务器运行在宿主之下,因此 MCP 客户端重载时管理器随之重启。 | -| `ctx.mcpAccounts` | `service` | [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | - | - | - | 保存 MCP 连接器插件注册的账号,并通过一个 Remote 把账号连同管理器对各服务器的视图提供给插件页;授权经由管理器完成。 | +| `ctx.mcpClientHost` | `service` | [`mcp-client`](../packages/mcp/mcp-client) | - | [`mcp-manager`](../packages/mcp/mcp-manager) | - | 管理器创建它来校验、挂载、探测和授权服务器,此外不使用 mcp-client 的任何值;其服务器运行在管理器之下。 | +| `ctx.mcpAccounts` | `service` | [`mcp-account`](../packages/mcp/mcp-account) | - | - | - | 在插件页通过连接器账号注册表显示每个 MCP 连接器插件注册的 OAuth 服务器账号;页面的操作经由管理器执行。 | | `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入每个任务的目标 Session。 | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | 从会话日志折叠带修订版本的目标状态,并将实时延续激活保留在进程本地。 | | `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | 负责一条经过认证的 OpenSSH 连接、已安装辅助程序身份、独立程序流,以及配套远端提供方的断连清理。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ebf12f0e9e..5822cef025 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -578,6 +578,22 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-client-ui-account-notifications` + +- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts) + +```ts config-catalog +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +``` + + @@ -625,16 +641,12 @@ export interface Config extends ContactConfig { developerTools: Volatile } -/** Questionnaire destination and bonus notice timings shared by Host and Client. */ +/** Questionnaire destination shared by Host and Client. */ export interface ContactConfig { /** HTTPS questionnaire URL; override for a test form. */ contactFormUrl: string /** Questionnaire source option; empty until Harness is supported by the form. */ contactSource: string - /** First delay before retrying a failed bonus acknowledgement. */ - bonusAckRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - bonusAckRetryMaxDelayMs: number } /** Persisted steps; a native top-up page leaves the durable step at credit. */ @@ -858,19 +870,21 @@ export interface Config { ``` - - + + -## `@deepseek-ai/dsh-deepseek-account-platform` +## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string + /** Harness API origin for account notifications. */ + harnessOrigin?: string /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ @@ -881,9 +895,11 @@ export interface Config { allowLoopbackHttp?: boolean /** Map authorization and completion pages to platformOrigin for private development proxies. */ rewriteBrowserOrigin?: boolean - /** Host-only headers sent exclusively to platformOrigin; account authorization cannot be overridden. */ + /** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */ requestHeaders?: Record - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ accountRequestHeaders?: Record /** Deadline for each platform HTTP request. */ requestTimeoutMs?: number @@ -897,7 +913,7 @@ export interface Config { attemptTimeoutMs?: number } ``` - + @@ -1112,7 +1128,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ @@ -2384,20 +2400,11 @@ export interface LspLocalServerConfig { ## `@deepseek-ai/dsh-mcp-client` - `inject`: `tools` -- `source`: [`packages/mcp/mcp-client/src/index.ts:144`](../packages/mcp/mcp-client/src/index.ts) +- `source`: [`packages/mcp/mcp-client/src/index.ts:134`](../packages/mcp/mcp-client/src/index.ts) ```ts config-catalog -/** Configuration of one mcp-client instance: a server, or the host. */ -export type Config = ServerConfig | HostConfig - /** Configuration for one stdio or Streamable HTTP MCP server. */ -export type ServerConfig = StdioConfig | StreamableHttpConfig - -/** Config of an instance that provides `ctx.mcpClientHost` instead of connecting a server. */ -export interface HostConfig { - /** Provide the MCP client host. */ - host: true -} +export type Config = StdioConfig | StreamableHttpConfig /** Config for connecting to an MCP server via a spawned child process over stdio. */ export interface StdioConfig { @@ -2506,9 +2513,9 @@ export interface McpOAuthConfig { ## `@deepseek-ai/dsh-mcp-manager` -- `inject`: `mcpClientHost` +- `inject`: `tools` - `refs`: [`McpOAuthConfigInput`](../packages/mcp/mcp-client/src/index.ts) · [`ReconnectConfig`](../packages/mcp/mcp-client/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/mcp/mcp-manager/src/index.ts:75`](../packages/mcp/mcp-manager/src/index.ts) +- `source`: [`packages/mcp/mcp-manager/src/index.ts:77`](../packages/mcp/mcp-manager/src/index.ts) ```ts config-catalog /** Manager configuration with live server entries. */ @@ -5027,7 +5034,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | --- | --- | --- | | `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) | | `@deepseek-ai/dsh-agent` | `sessionProjections` | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) | -| `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) | | `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) | | `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) | | `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) | @@ -5044,6 +5050,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | @@ -5058,7 +5065,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) | | `@deepseek-ai/dsh-client-ui-jobs` | — | [`packages/client/ui-jobs/src/index.ts`](../packages/client/ui-jobs/src/index.ts) | | `@deepseek-ai/dsh-client-ui-layout` | — | [`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpManager` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-message-feedback` | — | [`packages/client/ui-message-feedback/src/index.ts`](../packages/client/ui-message-feedback/src/index.ts) | | `@deepseek-ai/dsh-client-ui-model-selection` | — | [`packages/client/ui-model-selection/src/index.ts`](../packages/client/ui-model-selection/src/index.ts) | | `@deepseek-ai/dsh-client-ui-open-in-app` | — | [`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts) | @@ -5120,6 +5126,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-host-plugin-inventory` | `loader` | [`packages/host/plugin-inventory/src/index.ts`](../packages/host/plugin-inventory/src/index.ts) | | `@deepseek-ai/dsh-llm` | — | [`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts) | | `@deepseek-ai/dsh-lsp` | — | [`packages/lsp/lsp/src/index.ts`](../packages/lsp/lsp/src/index.ts) | +| `@deepseek-ai/dsh-mcp-account` | `mcpManager` · `connectorAccounts` | [`packages/mcp/mcp-account/src/index.ts`](../packages/mcp/mcp-account/src/index.ts) | | `@deepseek-ai/dsh-mcp-resources` | `tools` | [`packages/mcp/mcp-resources/src/index.ts`](../packages/mcp/mcp-resources/src/index.ts) | | `@deepseek-ai/dsh-message-quotes` | — | [`packages/session/message-quotes/src/index.ts`](../packages/session/message-quotes/src/index.ts) | | `@deepseek-ai/dsh-otel` | — | [`packages/telemetry/otel/src/index.ts`](../packages/telemetry/otel/src/index.ts) | @@ -5157,7 +5164,6 @@ Abstract service classes — a deployment loads a concrete implementation packag | `@deepseek-ai/dsh-attachment` | `AttachmentStore` | — | [`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts) | | `@deepseek-ai/dsh-compaction` | `CompactionEngine` | — | [`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts) | | `@deepseek-ai/dsh-credentials` | `CredentialProvider` | — | [`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts) | -| `@deepseek-ai/dsh-deepseek-account` | `DeepSeekAccount` | — | [`packages/credentials/deepseek-account/src/index.ts`](../packages/credentials/deepseek-account/src/index.ts) | | `@deepseek-ai/dsh-file-reference` | `FileReferenceService` | — | [`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts) | | `@deepseek-ai/dsh-fs` | `FileSystem` | — | [`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker` | `DirectoryPicker` | — | [`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts) | @@ -5195,6 +5201,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-cmdline` | — | [`packages/boot/cmdline/src/index.ts`](../packages/boot/cmdline/src/index.ts) | | `@deepseek-ai/dsh-cua-bundle` | — | [`packages/experimental/cua-bundle/src/index.ts`](../packages/experimental/cua-bundle/src/index.ts) | | `@deepseek-ai/dsh-deque` | — | [`packages/util/deque/src/index.ts`](../packages/util/deque/src/index.ts) | +| `@deepseek-ai/dsh-error` | — | [`packages/util/error/src/index.ts`](../packages/util/error/src/index.ts) | | `@deepseek-ai/dsh-experimental-badge-skill-bundle` | — | [`packages/experimental/badge-skill-bundle/src/index.ts`](../packages/experimental/badge-skill-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 7c741c2112..b45bbe5803 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -580,6 +580,22 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-client-ui-account-notifications` + +- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts) + +```ts config-catalog +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +``` + + @@ -627,16 +643,12 @@ export interface Config extends ContactConfig { developerTools: Volatile } -/** Questionnaire destination and bonus notice timings shared by Host and Client. */ +/** Questionnaire destination shared by Host and Client. */ export interface ContactConfig { /** HTTPS questionnaire URL; override for a test form. */ contactFormUrl: string /** Questionnaire source option; empty until Harness is supported by the form. */ contactSource: string - /** First delay before retrying a failed bonus acknowledgement. */ - bonusAckRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - bonusAckRetryMaxDelayMs: number } /** Persisted steps; a native top-up page leaves the durable step at credit. */ @@ -860,19 +872,21 @@ export interface Config { ``` - - + + -## `@deepseek-ai/dsh-deepseek-account-platform` +## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string + /** Harness API origin for account notifications. */ + harnessOrigin?: string /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ @@ -883,9 +897,11 @@ export interface Config { allowLoopbackHttp?: boolean /** Map authorization and completion pages to platformOrigin for private development proxies. */ rewriteBrowserOrigin?: boolean - /** Host-only headers sent exclusively to platformOrigin; account authorization cannot be overridden. */ + /** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */ requestHeaders?: Record - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ accountRequestHeaders?: Record /** Deadline for each platform HTTP request. */ requestTimeoutMs?: number @@ -899,7 +915,7 @@ export interface Config { attemptTimeoutMs?: number } ``` - + @@ -1114,7 +1130,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ @@ -2386,20 +2402,11 @@ export interface LspLocalServerConfig { ## `@deepseek-ai/dsh-mcp-client` - `inject`: `tools` -- `source`: [`packages/mcp/mcp-client/src/index.ts:144`](../packages/mcp/mcp-client/src/index.ts) +- `source`: [`packages/mcp/mcp-client/src/index.ts:134`](../packages/mcp/mcp-client/src/index.ts) ```ts config-catalog -/** Configuration of one mcp-client instance: a server, or the host. */ -export type Config = ServerConfig | HostConfig - /** Configuration for one stdio or Streamable HTTP MCP server. */ -export type ServerConfig = StdioConfig | StreamableHttpConfig - -/** Config of an instance that provides `ctx.mcpClientHost` instead of connecting a server. */ -export interface HostConfig { - /** Provide the MCP client host. */ - host: true -} +export type Config = StdioConfig | StreamableHttpConfig /** Config for connecting to an MCP server via a spawned child process over stdio. */ export interface StdioConfig { @@ -2508,9 +2515,9 @@ export interface McpOAuthConfig { ## `@deepseek-ai/dsh-mcp-manager` -- `inject`: `mcpClientHost` +- `inject`: `tools` - `refs`: [`McpOAuthConfigInput`](../packages/mcp/mcp-client/src/index.ts) · [`ReconnectConfig`](../packages/mcp/mcp-client/src/index.ts) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/mcp/mcp-manager/src/index.ts:75`](../packages/mcp/mcp-manager/src/index.ts) +- `source`: [`packages/mcp/mcp-manager/src/index.ts:77`](../packages/mcp/mcp-manager/src/index.ts) ```ts config-catalog /** Manager configuration with live server entries. */ @@ -5029,7 +5036,6 @@ export interface Config { | --- | --- | --- | | `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) | | `@deepseek-ai/dsh-agent` | `sessionProjections` | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) | -| `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) | | `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) | | `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) | | `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) | @@ -5046,6 +5052,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | @@ -5060,7 +5067,6 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) | | `@deepseek-ai/dsh-client-ui-jobs` | — | [`packages/client/ui-jobs/src/index.ts`](../packages/client/ui-jobs/src/index.ts) | | `@deepseek-ai/dsh-client-ui-layout` | — | [`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts) | -| `@deepseek-ai/dsh-client-ui-mcp-account` | `mcpManager` | [`packages/client/ui-mcp-account/src/index.ts`](../packages/client/ui-mcp-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-message-feedback` | — | [`packages/client/ui-message-feedback/src/index.ts`](../packages/client/ui-message-feedback/src/index.ts) | | `@deepseek-ai/dsh-client-ui-model-selection` | — | [`packages/client/ui-model-selection/src/index.ts`](../packages/client/ui-model-selection/src/index.ts) | | `@deepseek-ai/dsh-client-ui-open-in-app` | — | [`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts) | @@ -5122,6 +5128,7 @@ export interface Config { | `@deepseek-ai/dsh-host-plugin-inventory` | `loader` | [`packages/host/plugin-inventory/src/index.ts`](../packages/host/plugin-inventory/src/index.ts) | | `@deepseek-ai/dsh-llm` | — | [`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts) | | `@deepseek-ai/dsh-lsp` | — | [`packages/lsp/lsp/src/index.ts`](../packages/lsp/lsp/src/index.ts) | +| `@deepseek-ai/dsh-mcp-account` | `mcpManager` · `connectorAccounts` | [`packages/mcp/mcp-account/src/index.ts`](../packages/mcp/mcp-account/src/index.ts) | | `@deepseek-ai/dsh-mcp-resources` | `tools` | [`packages/mcp/mcp-resources/src/index.ts`](../packages/mcp/mcp-resources/src/index.ts) | | `@deepseek-ai/dsh-message-quotes` | — | [`packages/session/message-quotes/src/index.ts`](../packages/session/message-quotes/src/index.ts) | | `@deepseek-ai/dsh-otel` | — | [`packages/telemetry/otel/src/index.ts`](../packages/telemetry/otel/src/index.ts) | @@ -5159,7 +5166,6 @@ export interface Config { | `@deepseek-ai/dsh-attachment` | `AttachmentStore` | — | [`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts) | | `@deepseek-ai/dsh-compaction` | `CompactionEngine` | — | [`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts) | | `@deepseek-ai/dsh-credentials` | `CredentialProvider` | — | [`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts) | -| `@deepseek-ai/dsh-deepseek-account` | `DeepSeekAccount` | — | [`packages/credentials/deepseek-account/src/index.ts`](../packages/credentials/deepseek-account/src/index.ts) | | `@deepseek-ai/dsh-file-reference` | `FileReferenceService` | — | [`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts) | | `@deepseek-ai/dsh-fs` | `FileSystem` | — | [`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker` | `DirectoryPicker` | — | [`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts) | @@ -5197,6 +5203,7 @@ export interface Config { | `@deepseek-ai/dsh-cmdline` | — | [`packages/boot/cmdline/src/index.ts`](../packages/boot/cmdline/src/index.ts) | | `@deepseek-ai/dsh-cua-bundle` | — | [`packages/experimental/cua-bundle/src/index.ts`](../packages/experimental/cua-bundle/src/index.ts) | | `@deepseek-ai/dsh-deque` | — | [`packages/util/deque/src/index.ts`](../packages/util/deque/src/index.ts) | +| `@deepseek-ai/dsh-error` | — | [`packages/util/error/src/index.ts`](../packages/util/error/src/index.ts) | | `@deepseek-ai/dsh-experimental-badge-skill-bundle` | — | [`packages/experimental/badge-skill-bundle/src/index.ts`](../packages/experimental/badge-skill-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | diff --git a/docs/cookbook/adding-a-tool.i18n.yaml b/docs/cookbook/adding-a-tool.i18n.yaml index 5f78bb6983..fefaa9bfd1 100644 --- a/docs/cookbook/adding-a-tool.i18n.yaml +++ b/docs/cookbook/adding-a-tool.i18n.yaml @@ -9,8 +9,8 @@ en: 2cc80a2a79e23005 zh: 87e43383055890ce /tool-authoring-reference/rules-of-the-execute-contract: - en: f12260d67c4c4d4d - zh: 3955d44622432fd9 + en: b81b03778cfdecde + zh: 83f0b7863a5217c6 /tool-authoring-reference/long-running-work: en: 5f6b0c15cb91e21b zh: 633a2192df186ac3 diff --git a/docs/cookbook/adding-a-tool.md b/docs/cookbook/adding-a-tool.md index b1eaed1098..f13c9f169f 100644 --- a/docs/cookbook/adding-a-tool.md +++ b/docs/cookbook/adding-a-tool.md @@ -45,7 +45,7 @@ Registration is effect-based: disposing the plugin fiber unregisters the tool. S - **Execution identity is protected.** The registry materializes `arguments` as detached lossless JSON in one recursive pass, freezes that value before policy starts, and assigns an opaque `exec.token`; `callId`, `name`, `arguments`, `agent`, `token`, the required caller-owned `signal`, and an optional enclosing-transport `parent` token stay immutable through dispatch. `parent` is identity-only and exposes no live outer execution. Treat `args` as readonly input. Only an around-dispatch wrapper receives a mutable view, and it may replace and restore the required `exec.signal` to impose a deadline but cannot remove it. - **Declare and return one canonical JSON value.** `output.schema` uses `ValueSchemaSpec` and may have an object, array, scalar, or null root. `execute` returns only the inferred value; the registry snapshots it as lossless JSON, validates it, freezes it, and passes it to `output.render(args, value)`. Do not return content blocks from the body or make callers parse prose for ids and fields. - **Throwing or returning an invalid value means `isError`.** The registry catches throws and contains schema, renderer, metadata-projector, and lossless-JSON failures before observers run. Throw a `HarnessError` subclass with a stable `code` for every expected failure; a thrown `HarnessError` is the only tool-body outcome that keeps `error.name` and `error.code` on the result, and the [error-handling rules](../../.agents/skills/dsh-error-handling/SKILL.md#tool-failures) define the classes and codes. Represent a successful domain outcome in the canonical value even when its Native renderer explains a non-ideal state, such as a non-zero process exit. -- **Honor `exec.signal`.** Cancel in-flight work when it fires and throw a `HarnessError` named `AbortError` whose code is the `TOOL_ABORTED` constant (`ABORTED`), matching the registry's own cancellation result. +- **Honor `exec.signal`.** Cancel in-flight work when it fires and let the signal's reason or a dependency's error named `AbortError` propagate; the registry records it as `AbortError` with the `TOOL_ABORTED` constant (`ABORTED`). Do not replace it with a different plain `Error`. - **Project durable card data with `presentationMeta` (optional).** `output.presentationMeta(args, value)` derives replayable JSON from the same canonical value. The core persists it on `tool/result` and hands it to `presentResult`, so a card that needs result-time facts—such as `write`/`edit` applied hunks—survives replay without persisting the canonical value. The projector is skipped for nested Code dispatches because they have no cards. - **Use `exec.agent` for async notifications.** `agent.inject({ content, source: { kind: 'my-plugin' } })` appends durable context the NEXT model request sees — it is not a wake-up (an idle agent stays idle). Declare that `kind` through [`MessageSourceMap`](../subsystems/llm-streaming.md#content-blocks-and-messages) in your plugin: session format V4 rejects the retired `{ kind: 'plugin', plugin: '' }` wrapper at message admission. Guard against disposed agents (try/catch). diff --git a/docs/cookbook/adding-a-tool.zh.md b/docs/cookbook/adding-a-tool.zh.md index 0149575daf..68ca1f0b61 100644 --- a/docs/cookbook/adding-a-tool.zh.md +++ b/docs/cookbook/adding-a-tool.zh.md @@ -45,7 +45,7 @@ export function apply(ctx: Context) { - **执行身份受保护。** 注册表在一次递归遍历中将 `arguments` 物化为分离的无损 JSON,在策略开始前冻结该值,并分配一个不透明的 `exec.token`;`callId`、`name`、`arguments`、`agent`、`token`、必填且由调用方持有的 `signal`,以及可选的外层传输 `parent` token 在整个分发过程中保持不可变。`parent` 仅用于身份标识,不暴露活跃的外层执行。请将 `args` 视为只读输入。只有 around-dispatch 包装器会收到可变视图;它可以替换并恢复必填的 `exec.signal` 以施加截止时间,但不能移除该信号。 - **声明并返回一个规范 JSON 值。** `output.schema` 使用 `ValueSchemaSpec`,根可以是对象、数组、标量或 null。`execute` 只返回推导出的值;注册表将其快照为无损 JSON,完成校验和冻结后,再传给 `output.render(args, value)`。工具主体不要返回内容块,也不要迫使调用方从自然语言中解析 id 和字段。 - **抛出异常或返回无效值意味着 `isError`。** 注册表会捕获异常,并在观察者运行前收敛 schema、渲染器、元数据投影器和无损 JSON 失败。每种预期失败都应抛出带稳定 `code` 的 `HarnessError` 子类;在工具主体的各种产出中,只有抛出的 `HarnessError` 会让结果保留 `error.name` 和 `error.code`,具体的错误类和 code 由[错误处理规则](../../.agents/skills/dsh-error-handling/SKILL.md#tool-failures)规定。成功的领域结果即使表示不理想的状态,也应写入规范值;其 Native 渲染器可以解释该状态,例如进程以非零状态退出。 -- **遵守 `exec.signal`。** 信号触发时取消进行中的工作,并抛出 `name` 为 `AbortError`、code 为 `TOOL_ABORTED` 常量(值为 `ABORTED`)的 `HarnessError`,与注册表自己生成的取消结果一致。 +- **遵守 `exec.signal`。** 信号触发时取消进行中的工作,让 signal 的 reason 或依赖抛出的、name 为 `AbortError` 的错误直接传播;注册表会把它记录为 `AbortError` 与 `TOOL_ABORTED` 常量(值为 `ABORTED`)。不要把它替换成另一个普通 `Error`。 - **使用 `presentationMeta` 投影持久化的卡片数据(可选)。** `output.presentationMeta(args, value)` 从同一个规范值派生可回放的 JSON。核心将其持久化在 `tool/result` 上并传给 `presentResult`,因此需要结果期事实的卡片——例如 `write`/`edit` 的已应用 hunk——无需持久化规范值也能在回放中重现。嵌套 Code 分发没有卡片,因此会跳过该投影器。 - **使用 `exec.agent` 发送异步通知。** `agent.inject({ content, source: { kind: 'my-plugin' } })` 追加持久化上下文,下一次模型请求会看到它——这不是唤醒(空闲的 agent(智能体)保持空闲)。在插件里通过 [`MessageSourceMap`](../subsystems/llm-streaming.zh.md#content-blocks-and-messages) 声明该 `kind`:session format V4 在消息准入处拒绝退役的 `{ kind: 'plugin', plugin: '' }` 包装。请防范已 dispose 的 agent(try/catch)。 diff --git a/docs/defensive-patterns/remote-and-api.i18n.yaml b/docs/defensive-patterns/remote-and-api.i18n.yaml index c16a005c98..0e705303e6 100644 --- a/docs/defensive-patterns/remote-and-api.i18n.yaml +++ b/docs/defensive-patterns/remote-and-api.i18n.yaml @@ -12,5 +12,5 @@ en: 86422ee69c63f339 zh: 4a5e8d6f5d9a6ae3 /remote-and-api-rules/packages-api-carries-generic-orchestration-only: - en: 12a964b9c04fccf9 - zh: cf804f8044535727 + en: b9991b7ffcbf9029 + zh: bb7ef15064e922be diff --git a/docs/defensive-patterns/remote-and-api.md b/docs/defensive-patterns/remote-and-api.md index 5bfda3bd19..d79fa0309d 100644 --- a/docs/defensive-patterns/remote-and-api.md +++ b/docs/defensive-patterns/remote-and-api.md @@ -84,7 +84,7 @@ The hand-written copy drifts from the generated type without failing a build, th The packages under `packages/api` — the controllers, `gateway`, and `remotes` — carry transport, call shape, Session lifecycle, and other generic orchestration. A business branch never aggregates there: a decision that depends on concrete business state, handling bound to one feature, or a per-feature filter belongs in its own package or module and reaches this layer as projected data or through a registration surface. The criterion is where the logic belongs, not where the file sits, so a branch that only makes sense for one feature is a defect even when the file holding it is generic. -- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds nine packages — `account-controller`, `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3, account-controller 2). +- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds eight packages — `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3). - Not covered: generic Session lifecycle, transport, and storage abstraction stay — `gateway` dispatch, `remotes` selection, and shared session-list and catalog reads are infrastructure, not business logic. [Business ownership](../api-gateway.md#business-ownership) states the same split from the Gateway side. - Exception: none by default. Adding a business branch here needs an independent-package review, and that review answers why the logic cannot live in the package that owns the feature. - Fix: move the decision into the owning package, publish its result as projected data or register it on a registry this layer already injects, and leave only the orchestration that reads it. diff --git a/docs/defensive-patterns/remote-and-api.zh.md b/docs/defensive-patterns/remote-and-api.zh.md index 46e1925ef9..5ff8385c96 100644 --- a/docs/defensive-patterns/remote-and-api.zh.md +++ b/docs/defensive-patterns/remote-and-api.zh.md @@ -84,7 +84,7 @@ type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written `packages/api` 下的包——各 controller、`gateway`、`remotes`——承载传输、调用形态、Session 生命周期等通用编排。业务分支绝不在其中聚合:依赖具体业务状态的判断、与单个功能绑定的处理、逐功能的过滤,都归独立包或模块,并作为投影数据或经注册面接入本层。判据是逻辑的归属,而不是文件的位置,所以只对一个功能成立的业务分支即使放在通用文件里也是缺陷。 -- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 9 个包——`account-controller`、`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3、account-controller 2)。 +- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 8 个包——`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3)。 - 不覆盖:通用 Session 生命周期、传输与存储抽象留下——`gateway` 的分发、`remotes` 的选择、共享的会话列表与目录读取属于基础设施,不是业务逻辑。[业务所有权](../api-gateway.zh.md#business-ownership)从 Gateway 一侧给出同一个划分。 - 例外:默认无例外。在此新增业务分支须走独立包评审,评审要回答这些逻辑为什么不能住在拥有该功能的包里。 - 修法:把判断移进归属包,将其结果作为投影数据发布、或注册到本层本就注入的注册表上,这里只留下读取它的编排。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index bcb0b95b47..e05d536d14 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -40,11 +40,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -60,13 +60,13 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | +| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | [`mcp-account`](../packages/mcp/mcp-account) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:458`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:465`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:444`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:472`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:461`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 384497d7c2..5be97cb27a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -42,11 +42,11 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | -| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | -| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | -| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | +| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` | +| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | @@ -62,13 +62,13 @@ | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | -| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | +| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | [`mcp-account`](../packages/mcp/mcp-account) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:458`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:465`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:444`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:472`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:461`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 1fea5cbd5e..20e12276a4 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -12,6 +12,7 @@ flowchart TD pkg_brand["brand"] pkg_chunked_list["chunked-list"] pkg_deque["deque"] + pkg_error["error"] pkg_home_paths["home-paths"] pkg_http_proxy["http-proxy"] pkg_launch_environment["launch-environment"] @@ -114,7 +115,6 @@ flowchart TD pkg_acp["acp"] end subgraph group_api["packages/api"] - pkg_api_account_controller["api-account-controller"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] pkg_api_remote_access["api-remote-access"] @@ -158,6 +158,7 @@ flowchart TD pkg_client_resources["client-resources"] pkg_client_shortcuts["client-shortcuts"] pkg_client_store["client-store"] + pkg_client_ui_account_notifications["client-ui-account-notifications"] pkg_client_ui_agent_preset["client-ui-agent-preset"] pkg_client_ui_agent_team["client-ui-agent-team"] pkg_client_ui_approval["client-ui-approval"] @@ -165,6 +166,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -178,7 +180,6 @@ flowchart TD pkg_client_ui_input_trigger["client-ui-input-trigger"] pkg_client_ui_jobs["client-ui-jobs"] pkg_client_ui_layout["client-ui-layout"] - pkg_client_ui_mcp_account["client-ui-mcp-account"] pkg_client_ui_message_feedback["client-ui-message-feedback"] pkg_client_ui_model_selection["client-ui-model-selection"] pkg_client_ui_open_in_app["client-ui-open-in-app"] @@ -245,7 +246,6 @@ flowchart TD pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] - pkg_deepseek_account_platform["deepseek-account-platform"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -366,6 +366,7 @@ flowchart TD pkg_tool_lsp["tool-lsp"] end subgraph group_mcp["packages/mcp"] + pkg_mcp_account["mcp-account"] pkg_mcp_client["mcp-client"] pkg_mcp_manager["mcp-manager"] pkg_mcp_resources["mcp-resources"] @@ -486,12 +487,8 @@ flowchart TD subgraph group_workspace["packages/workspace"] pkg_workspace["workspace"] end + pkg_llm --> pkg_error pkg_session --> pkg_scope - pkg_system_prompt --> pkg_llm - pkg_system_prompt --> pkg_scope - pkg_skill --> pkg_llm - pkg_skill --> pkg_scope - pkg_web --> pkg_llm pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_app_boot --> pkg_home_paths @@ -499,8 +496,6 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm pkg_credentials_local --> pkg_atomic_write pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths @@ -508,17 +503,17 @@ flowchart TD pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths - pkg_lsp --> pkg_brand - pkg_lsp --> pkg_llm pkg_storage_domain --> pkg_storage pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry - pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web + pkg_system_prompt --> pkg_llm + pkg_system_prompt --> pkg_scope + pkg_skill --> pkg_llm + pkg_skill --> pkg_scope + pkg_web --> pkg_llm pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -527,17 +522,14 @@ flowchart TD pkg_attachment_local --> pkg_home_paths pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline - pkg_deliverable_file_references --> pkg_system_prompt + pkg_authorization --> pkg_credentials + pkg_authorization --> pkg_llm pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver - pkg_plugin_recommendations --> pkg_llm - pkg_plugin_recommendations --> pkg_skill - pkg_plugin_recommendations --> pkg_typert_protocol - pkg_skill_badge --> pkg_skill pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native @@ -546,11 +538,10 @@ flowchart TD pkg_host_directory_picker_auto --> pkg_host_webserver pkg_host_frontend_static --> pkg_client_connection pkg_host_frontend_static --> pkg_host_webserver - pkg_persona --> pkg_system_prompt + pkg_lsp --> pkg_brand + pkg_lsp --> pkg_llm pkg_sandbox --> pkg_llm pkg_sandbox --> pkg_session - pkg_sandbox_windows_acl --> pkg_skill - pkg_sandbox_windows_acl --> pkg_subprocess pkg_session_format_catalog --> pkg_session pkg_session_log_deepseek --> pkg_deepseek_llm_api_extensions pkg_session_log_deepseek --> pkg_session @@ -568,11 +559,15 @@ flowchart TD pkg_fs --> pkg_brand pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox + pkg_skill_office --> pkg_skill + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr + pkg_deliverable_file_references --> pkg_system_prompt pkg_experimental_speech_to_text --> pkg_settings pkg_experimental_translator --> pkg_credentials pkg_experimental_translator --> pkg_launch_environment @@ -581,11 +576,18 @@ flowchart TD pkg_experimental_translator --> pkg_session_persistence pkg_experimental_translator --> pkg_timeout pkg_experimental_translator --> pkg_util_values + pkg_plugin_recommendations --> pkg_llm + pkg_plugin_recommendations --> pkg_skill + pkg_plugin_recommendations --> pkg_typert_protocol + pkg_skill_badge --> pkg_skill pkg_host_product_telemetry_otel --> pkg_otel + pkg_persona --> pkg_system_prompt pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm pkg_sandbox_local --> pkg_sandbox pkg_sandbox_local --> pkg_session + pkg_sandbox_windows_acl --> pkg_skill + pkg_sandbox_windows_acl --> pkg_subprocess pkg_session_persistence_jsonl --> pkg_session pkg_session_persistence_jsonl --> pkg_session_persistence pkg_session_projection_cache --> pkg_session @@ -693,8 +695,12 @@ flowchart TD pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell pkg_deepseek_account --> pkg_agent + pkg_deepseek_account --> pkg_authorization pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver pkg_deepseek_account --> pkg_llm + pkg_deepseek_account --> pkg_typert_protocol pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment @@ -718,6 +724,7 @@ flowchart TD pkg_user_questions --> pkg_typert_protocol pkg_jobs --> pkg_agent pkg_jobs --> pkg_brand + pkg_jobs --> pkg_error pkg_jobs --> pkg_session pkg_jobs --> pkg_workspace pkg_sandbox_policy --> pkg_agent @@ -740,6 +747,7 @@ flowchart TD pkg_working_directory --> pkg_system_prompt pkg_terminal --> pkg_agent pkg_terminal --> pkg_brand + pkg_terminal --> pkg_error pkg_loader_smoke --> pkg_agent pkg_loader_smoke --> pkg_http_proxy pkg_loader_smoke --> pkg_llm @@ -772,17 +780,10 @@ flowchart TD pkg_web_search_deepseek --> pkg_llm_deepseek pkg_web_search_deepseek --> pkg_session pkg_web_search_deepseek --> pkg_web - pkg_api_account_controller --> pkg_agent - pkg_api_account_controller --> pkg_deepseek_account - pkg_api_account_controller --> pkg_typert_protocol pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm pkg_compaction --> pkg_session - pkg_deepseek_account_platform --> pkg_authorization - pkg_deepseek_account_platform --> pkg_credentials - pkg_deepseek_account_platform --> pkg_deepseek_account - pkg_deepseek_account_platform --> pkg_host_webserver pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime pkg_experimental_ptc_runtime_python --> pkg_sandbox pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy @@ -1546,6 +1547,7 @@ flowchart TD | [`brand`](../packages/util/brand) | `util` | — | | [`chunked-list`](../packages/util/chunked-list) | `util` | — | | [`deque`](../packages/util/deque) | `util` | — | +| [`error`](../packages/util/error) | `util` | — | | [`home-paths`](../packages/util/home-paths) | `util` | — | | [`http-proxy`](../packages/util/http-proxy) | `util` | — | | [`launch-environment`](../packages/util/launch-environment) | `util` | — | @@ -1564,7 +1566,6 @@ flowchart TD | [`util-values`](../packages/util/values) | `util` | — | | [`util-workspace-path`](../packages/util/workspace-path) | `util` | — | | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | -| [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | | [`fs-patch`](../packages/fs/fs-patch) | `fs` | — | | [`api-gateway`](../packages/api/gateway) | `api` | — | @@ -1584,6 +1585,7 @@ flowchart TD | [`client-resources`](../packages/client/resources) | `client` | — | | [`client-shortcuts`](../packages/client/shortcuts) | `client` | — | | [`client-store`](../packages/client/store) | `client` | — | +| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — | | [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — | | [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — | | [`client-ui-approval`](../packages/client/ui-approval) | `client` | — | @@ -1591,6 +1593,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | @@ -1604,7 +1607,6 @@ flowchart TD | [`client-ui-input-trigger`](../packages/client/ui-input-trigger) | `client` | — | | [`client-ui-jobs`](../packages/client/ui-jobs) | `client` | — | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | — | -| [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | `client` | — | | [`client-ui-message-feedback`](../packages/client/ui-message-feedback) | `client` | — | | [`client-ui-model-selection`](../packages/client/ui-model-selection) | `client` | — | | [`client-ui-open-in-app`](../packages/client/ui-open-in-app) | `client` | — | @@ -1678,6 +1680,7 @@ flowchart TD | [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | — | | [`host-open-in-app`](../packages/host/open-in-app) | `host` | — | | [`host-webserver`](../packages/host/webserver) | `host` | — | +| [`mcp-account`](../packages/mcp/mcp-account) | `mcp` | — | | [`message-quotes`](../packages/session/message-quotes) | `session` | — | | [`session-format`](../packages/session/session-format) | `session` | — | | [`session-format-v0-to-v1`](../packages/session/session-format-v0-to-v1) | `session` | — | @@ -1691,44 +1694,38 @@ flowchart TD | [`typert-generator`](../packages/typert/generator) | `typert` | — | | [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | +| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | -| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | -| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | | [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | -| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | +| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | +| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | -| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | -| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | -| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | +| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-format-catalog`](../packages/session/session-format-catalog) | `session` | [`session`](../packages/core/session) | | [`session-log-deepseek`](../packages/session/session-log-deepseek) | `session` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | @@ -1738,14 +1735,21 @@ flowchart TD | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | +| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | +| [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | | [`experimental-translator`](../packages/experimental/translator) | `experimental` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | +| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | +| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | +| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | +| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | | [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | @@ -1774,16 +1778,16 @@ flowchart TD | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) | +| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | -| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | +| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | -| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | +| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | @@ -1791,9 +1795,7 @@ flowchart TD | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | -| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 8b92c10097..49e6f47adf 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -14,6 +14,7 @@ flowchart TD pkg_brand["brand"] pkg_chunked_list["chunked-list"] pkg_deque["deque"] + pkg_error["error"] pkg_home_paths["home-paths"] pkg_http_proxy["http-proxy"] pkg_launch_environment["launch-environment"] @@ -116,7 +117,6 @@ flowchart TD pkg_acp["acp"] end subgraph group_api["packages/api"] - pkg_api_account_controller["api-account-controller"] pkg_api_gateway["api-gateway"] pkg_api_job_controller["api-job-controller"] pkg_api_remote_access["api-remote-access"] @@ -160,6 +160,7 @@ flowchart TD pkg_client_resources["client-resources"] pkg_client_shortcuts["client-shortcuts"] pkg_client_store["client-store"] + pkg_client_ui_account_notifications["client-ui-account-notifications"] pkg_client_ui_agent_preset["client-ui-agent-preset"] pkg_client_ui_agent_team["client-ui-agent-team"] pkg_client_ui_approval["client-ui-approval"] @@ -167,6 +168,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -180,7 +182,6 @@ flowchart TD pkg_client_ui_input_trigger["client-ui-input-trigger"] pkg_client_ui_jobs["client-ui-jobs"] pkg_client_ui_layout["client-ui-layout"] - pkg_client_ui_mcp_account["client-ui-mcp-account"] pkg_client_ui_message_feedback["client-ui-message-feedback"] pkg_client_ui_model_selection["client-ui-model-selection"] pkg_client_ui_open_in_app["client-ui-open-in-app"] @@ -247,7 +248,6 @@ flowchart TD pkg_credentials["credentials"] pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] - pkg_deepseek_account_platform["deepseek-account-platform"] end subgraph group_deliverables["packages/deliverables"] pkg_deliverable_file_references["deliverable-file-references"] @@ -368,6 +368,7 @@ flowchart TD pkg_tool_lsp["tool-lsp"] end subgraph group_mcp["packages/mcp"] + pkg_mcp_account["mcp-account"] pkg_mcp_client["mcp-client"] pkg_mcp_manager["mcp-manager"] pkg_mcp_resources["mcp-resources"] @@ -488,12 +489,8 @@ flowchart TD subgraph group_workspace["packages/workspace"] pkg_workspace["workspace"] end + pkg_llm --> pkg_error pkg_session --> pkg_scope - pkg_system_prompt --> pkg_llm - pkg_system_prompt --> pkg_scope - pkg_skill --> pkg_llm - pkg_skill --> pkg_scope - pkg_web --> pkg_llm pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand pkg_app_boot --> pkg_home_paths @@ -501,8 +498,6 @@ flowchart TD pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand - pkg_authorization --> pkg_credentials - pkg_authorization --> pkg_llm pkg_credentials_local --> pkg_atomic_write pkg_credentials_local --> pkg_credentials pkg_credentials_local --> pkg_home_paths @@ -510,17 +505,17 @@ flowchart TD pkg_experimental_liveshare --> pkg_scope pkg_anonymous_user_id --> pkg_brand pkg_anonymous_user_id --> pkg_home_paths - pkg_lsp --> pkg_brand - pkg_lsp --> pkg_llm pkg_storage_domain --> pkg_storage pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry - pkg_skill_office --> pkg_skill - pkg_web_fetch_http --> pkg_timeout - pkg_web_fetch_http --> pkg_web + pkg_system_prompt --> pkg_llm + pkg_system_prompt --> pkg_scope + pkg_skill --> pkg_llm + pkg_skill --> pkg_scope + pkg_web --> pkg_llm pkg_spill --> pkg_brand pkg_spill --> pkg_llm pkg_spill --> pkg_session @@ -529,17 +524,14 @@ flowchart TD pkg_attachment_local --> pkg_home_paths pkg_hmr --> pkg_app_boot pkg_hmr --> pkg_cmdline - pkg_deliverable_file_references --> pkg_system_prompt + pkg_authorization --> pkg_credentials + pkg_authorization --> pkg_llm pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess pkg_experimental_webworker_runtime --> pkg_client_connection pkg_experimental_webworker_runtime --> pkg_client_modules pkg_experimental_webworker_runtime --> pkg_host_webserver - pkg_plugin_recommendations --> pkg_llm - pkg_plugin_recommendations --> pkg_skill - pkg_plugin_recommendations --> pkg_typert_protocol - pkg_skill_badge --> pkg_skill pkg_host_directory_picker_auto --> pkg_client_connection pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_native @@ -548,11 +540,10 @@ flowchart TD pkg_host_directory_picker_auto --> pkg_host_webserver pkg_host_frontend_static --> pkg_client_connection pkg_host_frontend_static --> pkg_host_webserver - pkg_persona --> pkg_system_prompt + pkg_lsp --> pkg_brand + pkg_lsp --> pkg_llm pkg_sandbox --> pkg_llm pkg_sandbox --> pkg_session - pkg_sandbox_windows_acl --> pkg_skill - pkg_sandbox_windows_acl --> pkg_subprocess pkg_session_format_catalog --> pkg_session pkg_session_log_deepseek --> pkg_deepseek_llm_api_extensions pkg_session_log_deepseek --> pkg_session @@ -570,11 +561,15 @@ flowchart TD pkg_fs --> pkg_brand pkg_fs --> pkg_llm pkg_fs --> pkg_sandbox + pkg_skill_office --> pkg_skill + pkg_web_fetch_http --> pkg_timeout + pkg_web_fetch_http --> pkg_web pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence pkg_config_editor --> pkg_app_boot pkg_config_editor --> pkg_hmr + pkg_deliverable_file_references --> pkg_system_prompt pkg_experimental_speech_to_text --> pkg_settings pkg_experimental_translator --> pkg_credentials pkg_experimental_translator --> pkg_launch_environment @@ -583,11 +578,18 @@ flowchart TD pkg_experimental_translator --> pkg_session_persistence pkg_experimental_translator --> pkg_timeout pkg_experimental_translator --> pkg_util_values + pkg_plugin_recommendations --> pkg_llm + pkg_plugin_recommendations --> pkg_skill + pkg_plugin_recommendations --> pkg_typert_protocol + pkg_skill_badge --> pkg_skill pkg_host_product_telemetry_otel --> pkg_otel + pkg_persona --> pkg_system_prompt pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm pkg_sandbox_local --> pkg_sandbox pkg_sandbox_local --> pkg_session + pkg_sandbox_windows_acl --> pkg_skill + pkg_sandbox_windows_acl --> pkg_subprocess pkg_session_persistence_jsonl --> pkg_session pkg_session_persistence_jsonl --> pkg_session_persistence pkg_session_projection_cache --> pkg_session @@ -695,8 +697,12 @@ flowchart TD pkg_tmux_context --> pkg_session_projection pkg_tmux_context --> pkg_shell pkg_deepseek_account --> pkg_agent + pkg_deepseek_account --> pkg_authorization pkg_deepseek_account --> pkg_brand + pkg_deepseek_account --> pkg_credentials + pkg_deepseek_account --> pkg_host_webserver pkg_deepseek_account --> pkg_llm + pkg_deepseek_account --> pkg_typert_protocol pkg_deepseek_account --> pkg_util_values pkg_commands --> pkg_agent pkg_commands --> pkg_attachment @@ -720,6 +726,7 @@ flowchart TD pkg_user_questions --> pkg_typert_protocol pkg_jobs --> pkg_agent pkg_jobs --> pkg_brand + pkg_jobs --> pkg_error pkg_jobs --> pkg_session pkg_jobs --> pkg_workspace pkg_sandbox_policy --> pkg_agent @@ -742,6 +749,7 @@ flowchart TD pkg_working_directory --> pkg_system_prompt pkg_terminal --> pkg_agent pkg_terminal --> pkg_brand + pkg_terminal --> pkg_error pkg_loader_smoke --> pkg_agent pkg_loader_smoke --> pkg_http_proxy pkg_loader_smoke --> pkg_llm @@ -774,17 +782,10 @@ flowchart TD pkg_web_search_deepseek --> pkg_llm_deepseek pkg_web_search_deepseek --> pkg_session pkg_web_search_deepseek --> pkg_web - pkg_api_account_controller --> pkg_agent - pkg_api_account_controller --> pkg_deepseek_account - pkg_api_account_controller --> pkg_typert_protocol pkg_compaction --> pkg_brand pkg_compaction --> pkg_commands pkg_compaction --> pkg_llm pkg_compaction --> pkg_session - pkg_deepseek_account_platform --> pkg_authorization - pkg_deepseek_account_platform --> pkg_credentials - pkg_deepseek_account_platform --> pkg_deepseek_account - pkg_deepseek_account_platform --> pkg_host_webserver pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime pkg_experimental_ptc_runtime_python --> pkg_sandbox pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy @@ -1548,6 +1549,7 @@ flowchart TD | [`brand`](../packages/util/brand) | `util` | — | | [`chunked-list`](../packages/util/chunked-list) | `util` | — | | [`deque`](../packages/util/deque) | `util` | — | +| [`error`](../packages/util/error) | `util` | — | | [`home-paths`](../packages/util/home-paths) | `util` | — | | [`http-proxy`](../packages/util/http-proxy) | `util` | — | | [`launch-environment`](../packages/util/launch-environment) | `util` | — | @@ -1566,7 +1568,6 @@ flowchart TD | [`util-values`](../packages/util/values) | `util` | — | | [`util-workspace-path`](../packages/util/workspace-path) | `util` | — | | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | -| [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | | [`fs-patch`](../packages/fs/fs-patch) | `fs` | — | | [`api-gateway`](../packages/api/gateway) | `api` | — | @@ -1586,6 +1587,7 @@ flowchart TD | [`client-resources`](../packages/client/resources) | `client` | — | | [`client-shortcuts`](../packages/client/shortcuts) | `client` | — | | [`client-store`](../packages/client/store) | `client` | — | +| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — | | [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — | | [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — | | [`client-ui-approval`](../packages/client/ui-approval) | `client` | — | @@ -1593,6 +1595,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | @@ -1606,7 +1609,6 @@ flowchart TD | [`client-ui-input-trigger`](../packages/client/ui-input-trigger) | `client` | — | | [`client-ui-jobs`](../packages/client/ui-jobs) | `client` | — | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | — | -| [`client-ui-mcp-account`](../packages/client/ui-mcp-account) | `client` | — | | [`client-ui-message-feedback`](../packages/client/ui-message-feedback) | `client` | — | | [`client-ui-model-selection`](../packages/client/ui-model-selection) | `client` | — | | [`client-ui-open-in-app`](../packages/client/ui-open-in-app) | `client` | — | @@ -1680,6 +1682,7 @@ flowchart TD | [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | — | | [`host-open-in-app`](../packages/host/open-in-app) | `host` | — | | [`host-webserver`](../packages/host/webserver) | `host` | — | +| [`mcp-account`](../packages/mcp/mcp-account) | `mcp` | — | | [`message-quotes`](../packages/session/message-quotes) | `session` | — | | [`session-format`](../packages/session/session-format) | `session` | — | | [`session-format-v0-to-v1`](../packages/session/session-format-v0-to-v1) | `session` | — | @@ -1693,44 +1696,38 @@ flowchart TD | [`typert-generator`](../packages/typert/generator) | `typert` | — | | [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | +| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | -| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | -| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | -| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) | | [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) | -| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | | [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | -| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | -| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | +| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | +| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | +| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | -| [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | +| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | -| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | -| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | -| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | +| [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-format-catalog`](../packages/session/session-format-catalog) | `session` | [`session`](../packages/core/session) | | [`session-log-deepseek`](../packages/session/session-log-deepseek) | `session` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | @@ -1740,14 +1737,21 @@ flowchart TD | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | | [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | +| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) | +| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | +| [`deliverable-file-references`](../packages/deliverables/deliverable-file-references) | `deliverables` | [`system-prompt`](../packages/core/system-prompt) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | | [`experimental-translator`](../packages/experimental/translator) | `experimental` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | +| [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`typert-protocol`](../packages/typert/protocol) | +| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | +| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | +| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | | [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) | | [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | @@ -1776,16 +1780,16 @@ flowchart TD | [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | -| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) | +| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) | | [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | -| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | +| [`jobs`](../packages/jobs/jobs) | `jobs` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`session`](../packages/core/session), [`workspace`](../packages/workspace/workspace) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | -| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand) | +| [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | @@ -1793,9 +1797,7 @@ flowchart TD | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | -| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | | [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 104e05f322..a5fb682b48 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1308,8 +1308,8 @@ en: 0080c345c319a4b5 zh: de1a8b3ed621ce21 /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: d70be5d46cb1ef7d - zh: d3d5a05d62e443fe + en: b2488366535b5fdc + zh: b64d50345521eb99 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 2258683c3cfa4ce3 zh: 5663aa76c911761b diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index d3dfc94def..6b80fbbc99 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5269,7 +5269,7 @@ Sources: [`packages/llm/llm/src/types.ts:134`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/contracts.ts:376`](../packages/core/tools/src/contracts.ts) +Sources: [`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index ed4eb4146e..c73b594c28 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5271,7 +5271,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/contracts.ts:376`](../packages/core/tools/src/contracts.ts) +来源:[`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index ee1c05456d..3a1b058f36 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -223,7 +223,7 @@ {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, - {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:376"]}, + {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, {"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]}, {"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]}, {"digest":"3e2ece4967cfebe95f450a93f45523dff99d6749f6269f2f60f84dfecfcf3693","names":[],"sources":[]}, diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 2ef55a4f5c..5c131881f7 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote async start(key: string, operation: string): Promise + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` @@ -195,33 +239,6 @@ async reconcileProfile(requiredIds: readonly string[] = []): Promise - -### `ctx.mcpAccounts` — `McpAccounts` - -Holds the registered accounts and serves them, with their servers' manager views, to the Plugins page. - -```ts cordis-catalog -/** - * Show one account on the Plugins page for as long as the returned disposer has not run. - * @param registration - the server name, the bundle package, and the connector's text. - * @returns an idempotent disposer that withdraws the account. - * @throws when another account already uses the package or the server. - */ -register(registration: McpAccountRegistration): () => void - -/** - * Follow every registered account with the manager's view of its server. - * @param signal - the Client's observation lifetime; disposal also ends the stream. - * @returns the accounts once the manager lists its servers, then after each change of either, coalescing changes that - * arrive before the next read; ends with the manager's stream. - * @throws what the manager's stream throws. - */ -@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/client/ui-mcp-account/src/index.ts`](../../packages/client/ui-mcp-account/src/index.ts) - ### `ctx.pluginManager` — `PluginManager` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 3aa64741c2..0a48541725 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote async start(key: string, operation: string): Promise + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` @@ -195,33 +239,6 @@ async reconcileProfile(requiredIds: readonly string[] = []): Promise - -### `ctx.mcpAccounts` — `McpAccounts` - -Holds the registered accounts and serves them, with their servers' manager views, to the Plugins page. - -```ts cordis-catalog -/** - * Show one account on the Plugins page for as long as the returned disposer has not run. - * @param registration - the server name, the bundle package, and the connector's text. - * @returns an idempotent disposer that withdraws the account. - * @throws when another account already uses the package or the server. - */ -register(registration: McpAccountRegistration): () => void - -/** - * Follow every registered account with the manager's view of its server. - * @param signal - the Client's observation lifetime; disposal also ends the stream. - * @returns the accounts once the manager lists its servers, then after each change of either, coalescing changes that - * arrive before the next read; ends with the manager's stream. - * @throws what the manager's stream throws. - */ -@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable -``` - -Source: [`packages/client/ui-mcp-account/src/index.ts`](../../packages/client/ui-mcp-account/src/index.ts) - ### `ctx.pluginManager` — `PluginManager` diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index dbf1b7ddc3..5d6db1a53a 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/computer-use.md /computer-use: - en: 38cfa2a698be898f - zh: 60961256fee5ef21 + en: e02a2e4cc9970cba + zh: 29aac6c0530a582f /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index 08888a044c..7b1dbee236 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -14,9 +14,11 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys |---|---| | `CuaApplicationId`, `CuaApplicationGrant` | A platform-provided application identity and its displayed saved decision. | | `CuaSystemPermission` | Accessibility or Screen Recording, selected by the human. | -| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native privilege checks, observed helper/parent processes, and the application identified by macOS process responsibility at helper startup. The independent helper uses its own bundle when system attribution is unavailable; application metadata is absent if neither bundle can be identified. | +| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native access observations tagged `darwin` or `win32`, with helper process identity. macOS includes permission checks, parent identity and responsible-application metadata when available (falling back to the helper’s own bundle); Windows includes desktop lock, capture availability and elevation status. | | `CuaApplicationState` | Saved grants, refused applications, and whether persistence is available. Session-only grants remain internal to the provider. System observations and application icons are queried separately so the page can display each result as it arrives. | +The [shared object API](../../packages/experimental/cua/README.md) uses `connectCua` to select an application, then `app.getWindows()` and `app.getWindow(windowId)` to select a window for screenshots and pointer input. Accessibility operations use element IDs from the latest tree for that application handle. Providers declare keyboard scopes and application-level accessibility in `getCapabilities()`. + ## Choose a provider Mount [`dsh-computer-use`](../../packages/computer-use/computer-use/README.md) and one provider in the same composition. Both Cua Driver providers are experimental public npm packages and require explicit activation. @@ -92,7 +94,7 @@ Browser controls for provider-owned native permission and application decisions. /** * Inspect system privileges independently of application decisions and icons. - * @returns Fresh native preflight and launch metadata. + * @returns Platform-tagged access observations and native process metadata. */ @Remote async systemStatus(): Promise diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 28fdc9b794..1c35045383 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -14,9 +14,11 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 |---|---| | `CuaApplicationId`、`CuaApplicationGrant` | 平台提供的应用身份,以及显示给用户的已保存决定。 | | `CuaSystemPermission` | 用户选择申请的辅助功能或屏幕录制权限。 | -| `CuaPermissionProcess`、`CuaSystemPermissionState` | 观测到的 helper、父进程和原生权限状态,以及 helper 启动时由 macOS 责任进程记录识别出的应用。系统归属信息不可用时,独立 helper 使用自身 bundle;两者都无法识别时才省略应用信息。 | +| `CuaPermissionProcess`、`CuaSystemPermissionState` | 以 `darwin` 或 `win32` 标记的原生访问状态和 helper 进程身份。macOS 包含权限检查、父进程身份和责任应用信息(系统无法识别时使用 helper 自身的应用包);Windows 包含桌面锁定、截图可用性和提权状态。 | | `CuaApplicationState` | 持久授权、拒绝记录,以及能否持久保存。会话授权只保留在 provider 内部。系统权限和应用图标分别查询,页面在各项结果返回后分别显示。 | +调用[共享对象 API](../../packages/experimental/cua/README.zh.md) 时,通过 `connectCua` 连接,选择应用后用 `app.getWindows()` 和 `app.getWindow(windowId)` 选择要截图或进行鼠标操作的窗口。辅助功能操作使用该应用句柄最近一次读取的树中的元素 ID。提供方通过 `getCapabilities()` 声明键盘输入支持的范围,以及是否支持应用级辅助功能。 + ## 选择提供方 在同一组合中挂载 [`dsh-computer-use`](../../packages/computer-use/computer-use/README.zh.md) 和一个提供方。两个 Cua Driver 提供方都是公开发布到 npm 的实验性包,均需显式启用。 @@ -92,7 +94,7 @@ Browser controls for provider-owned native permission and application decisions. /** * Inspect system privileges independently of application decisions and icons. - * @returns Fresh native preflight and launch metadata. + * @returns Platform-tagged access observations and native process metadata. */ @Remote async systemStatus(): Promise diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index bad9827407..174bd14fc4 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -12,14 +12,14 @@ en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: f7b09588c0f34952 - zh: 1b93d673c5bf6a80 + en: 60ce885c8cac3082 + zh: 9f1cf7d25119cdda /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb /user-credentials/embedded-platform-credentials: - en: 78240c18fc9a085d - zh: dabf5fae10b54663 + en: 6f80d44cdec8e05a + zh: 658e5e4958f9baa6 /user-credentials/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: 314e5b36f51b2c64 - zh: 0e1cb3fe5adf5ecd + en: 664f0f89d89ac686 + zh: 178263324ad76307 diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..444b2b8a52 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -32,13 +32,12 @@ interface ResolvedCredential { ## Description -`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. +`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The optional `masked` field carries a provider-generated preview without the full credential. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** - * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * Configuration facts and an optional provider-masked preview for one + * reference. The full credential is never part of this view. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ @@ -47,6 +46,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Provider-generated masked preview of a stored value; never the full value. */ + masked?: string } ``` @@ -56,7 +57,7 @@ interface CredentialInfo { ## Embedded Platform credentials -PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account-controller RPC, AccountView, and AccountDetails. +PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. @@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise /** * Describe one reference for configuration surfaces without exposing the - * value. + * full value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional masked preview. */ abstract describe(ref: CredentialRef): Promise @@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent ### `ctx.credentialsController` — `CredentialsController` -Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one. +Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one. ```ts cordis-catalog /** @@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - + -### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam) +### `ctx.deepseekAccount` — `DeepSeekAccount` -Account operations; only Host consumers can obtain a request credential. +Account login, credentials, and client-safe Remote operations. ```ts cordis-catalog /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ -abstract getState(): Promise +@Remote async getState(): Promise /** * Query Platform profile independently of wallet balances. @@ -281,30 +282,65 @@ abstract getState(): Promise * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ -abstract getProfile(client: AccountClientMetadata): Promise +@Remote async getProfile(client: AccountClientMetadata): Promise /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ -abstract getBalance(client: AccountClientMetadata): Promise +@Remote getBalance(client: AccountClientMetadata): Promise /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ -abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise +@Remote async getNotifications(client: AccountClientMetadata): Promise /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ -abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise /** * Join an active attempt or start browser authorization. @@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ -abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ -abstract cancelSignIn(id: SignInAttemptId): Promise +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ -abstract signOut(client: AccountClientMetadata): Promise +@Remote signOut(client: AccountClientMetadata): Promise /** - * Subscribe to snapshots including a complete initial state. + * Inspect running work before sign-out. + * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ -abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ -abstract resolveToken(url: string): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -abstract rejectToken(token: string): Promise - -/** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -abstract getPlatformSession(): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable ``` Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) @@ -488,6 +517,6 @@ Local grant removal has completed. Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) -The account Service Definition exposes getState, getProfile, getBalance, getUnnotifiedBonuses, ackBonusNotified, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. See [the account package](../../packages/credentials/deepseek-account/README.md). +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/credentials/deepseek-account/README.md). `AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..ce9fbdadd5 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -32,13 +32,12 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 +`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。可选的 `masked` 字段携带提供方生成的脱敏预览,不包含完整凭据。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** - * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * Configuration facts and an optional provider-masked preview for one + * reference. The full credential is never part of this view. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ @@ -47,6 +46,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Provider-generated masked preview of a stored value; never the full value. */ + masked?: string } ``` @@ -56,7 +57,7 @@ interface CredentialInfo { ## 内嵌 Platform 凭证 -PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号控制器 RPC、AccountView 和 AccountDetails 均不包含此快照。 +PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 @@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise /** * Describe one reference for configuration surfaces without exposing the - * value. + * full value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional masked preview. */ abstract describe(ref: CredentialRef): Promise @@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent ### `ctx.credentialsController` — `CredentialsController` -Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one. +Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one. ```ts cordis-catalog /** @@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - + -### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam) +### `ctx.deepseekAccount` — `DeepSeekAccount` -Account operations; only Host consumers can obtain a request credential. +Account login, credentials, and client-safe Remote operations. ```ts cordis-catalog /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ -abstract getState(): Promise +@Remote async getState(): Promise /** * Query Platform profile independently of wallet balances. @@ -281,30 +282,65 @@ abstract getState(): Promise * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ -abstract getProfile(client: AccountClientMetadata): Promise +@Remote async getProfile(client: AccountClientMetadata): Promise /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ -abstract getBalance(client: AccountClientMetadata): Promise +@Remote getBalance(client: AccountClientMetadata): Promise /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ -abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise +@Remote async getNotifications(client: AccountClientMetadata): Promise /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ -abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise /** * Join an active attempt or start browser authorization. @@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ -abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ -abstract cancelSignIn(id: SignInAttemptId): Promise +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ -abstract signOut(client: AccountClientMetadata): Promise +@Remote signOut(client: AccountClientMetadata): Promise /** - * Subscribe to snapshots including a complete initial state. + * Inspect running work before sign-out. + * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ -abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ -abstract resolveToken(url: string): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -abstract rejectToken(token: string): Promise - -/** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -abstract getPlatformSession(): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable ``` Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) @@ -488,6 +517,6 @@ Local grant removal has completed. Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) -账号服务定义提供 getState、getProfile、getBalance、getUnnotifiedBonuses、ackBonusNotified、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 `AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/mcp.i18n.yaml b/docs/subsystems/mcp.i18n.yaml index 76c0505b3f..ff63cf00b8 100644 --- a/docs/subsystems/mcp.i18n.yaml +++ b/docs/subsystems/mcp.i18n.yaml @@ -12,8 +12,8 @@ en: 5c0aa5a2e528af97 zh: ae2ba2297294e3de /mcp/configuration: - en: 4a164aa382a55d28 - zh: de7794f817f2cf32 + en: c4bfe77f7b24fc21 + zh: 292b3a96eec955d9 /mcp/responsibilities-and-scope: en: 9aa0df86a35e1a0e zh: 58f5382ef3f11f06 diff --git a/docs/subsystems/mcp.md b/docs/subsystems/mcp.md index fbcc54d228..3b0132c173 100644 --- a/docs/subsystems/mcp.md +++ b/docs/subsystems/mcp.md @@ -23,7 +23,7 @@ Model Context Protocol (MCP) connects the model to tools supplied by external se MCP servers are opt-in. Configure one `@deepseek-ai/dsh-mcp-client` entry per server in the intended Cordis scope. Every shipped profile supplies the [tool registry](tools.md) and mounts the shared resource service once; users configure only client entries. Callers with no visible configured server receive no MCP prompt text or tools in native or PTC mode. -The Web and Desktop profiles also mount the [MCP server manager](../../packages/mcp/mcp-manager/README.md) once. It runs servers configured through Settings and servers that installed plugins register for their own lifetime, and serves their status, restart, and probe operations to Remote clients. A plugin that registers an OAuth server registers its account with `ctx.mcpAccounts` from [`ui-mcp-account`](../../packages/client/ui-mcp-account/README.md) to show it on the **Plugins** page. +The Web and Desktop profiles also mount the [MCP server manager](../../packages/mcp/mcp-manager/README.md) once. It runs servers configured through Settings and servers that installed plugins register for their own lifetime, and serves their status, restart, and probe operations to Remote clients. A plugin that registers an OAuth server registers its account with `ctx.mcpAccounts` from [`dsh-mcp-account`](../../packages/mcp/mcp-account/README.md) to show it on the **Plugins** page. | Choice | Configuration owner | |---|---| @@ -122,6 +122,25 @@ MCP prompt templates, human-input elicitation, task-based execution, and resourc Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.mcpAccounts` — `McpAccounts` + +Shows each connector's MCP server account in the connector account registry. + +```ts cordis-catalog +/** + * Show one connector's server account on its bundle page for as long as the returned disposer has not run. The + * account's key is `mcp:`. + * @param registration - the server name, the bundle package, and the connector's text. + * @returns the registry's idempotent disposer, which withdraws the account. + * @throws when another account already uses the server or the package. + */ +register(registration: McpAccountRegistration): () => void +``` + +Source: [`packages/mcp/mcp-account/src/index.ts`](../../packages/mcp/mcp-account/src/index.ts) + ### `ctx.mcpClientHost` — `McpClientHost` @@ -137,14 +156,14 @@ Validates, mounts, probes, and authorizes MCP servers for the plugin that manage * @throws when the server name, a field, a template token, the reconnect policy, or OAuth beside an Authorization * header is invalid. */ -validate(input: ServerConfigInput, path: readonly string[]): ServerConfig +validate(input: ConfigInput, path: readonly string[]): Config /** * Mount one server instance below the host. The instance registers its tools and holds its `serverName` until disposed. * @param config - resolved server configuration, usually from {@link McpClientHost.validate}. * @returns the instance's activation and disposal. */ -mount(config: ServerConfig): McpServerInstance +mount(config: Config): McpServerInstance /** * Probe a server without mounting it: resolve its templates, connect, list its tools, and close. @@ -153,7 +172,7 @@ mount(config: ServerConfig): McpServerInstance * @returns the connect and list outcome with the cleanup result. * @throws for invalid options, malformed templates, or a missing required credentials provider. */ -probe(config: ServerConfig, options?: McpProbeOptions): Promise +probe(config: Config, options?: McpProbeOptions): Promise /** * Create the explicit OAuth authorization owner of one server. @@ -233,21 +252,21 @@ async probe(name: string, options?: McpProbeOptions): Promise * @param name - configured or registered OAuth entry, including disabled entries. * @returns current attempt progress; absent services, changing entries, or failed cleanup reject. */ -@Remote async startAuthorization(name: string): Promise +async startAuthorization(name: string): Promise /** * Cancel the selected attempt and drain its work; an admitted credential commit completes. * @param name - managed entry. * @param id - selected attempt; stale or absent attempts are ignored. */ -@Remote async cancelAuthorization(name: string, id: McpOAuthAttemptId): Promise +async cancelAuthorization(name: string, id: McpOAuthAttemptId): Promise /** * Drain authorization, probes, and connections before deleting the local grant; retain client registration. * A configuration change before deletion preserves the grant and rejects. * @param name - configured or registered OAuth entry; cleanup failure preserves the grant and blocks replacement. */ -@Remote async signOut(name: string): Promise +async signOut(name: string): Promise ``` Source: [`packages/mcp/mcp-manager/src/index.ts`](../../packages/mcp/mcp-manager/src/index.ts) diff --git a/docs/subsystems/mcp.zh.md b/docs/subsystems/mcp.zh.md index 6dd105b824..87a2a4c2a0 100644 --- a/docs/subsystems/mcp.zh.md +++ b/docs/subsystems/mcp.zh.md @@ -23,7 +23,7 @@ MCP 服务器需要主动配置。在目标 Cordis 作用域中,为每台服务器配置一个 `@deepseek-ai/dsh-mcp-client` 条目。每个随附 profile 都提供[工具注册表](tools.zh.md),并统一挂载共享资源服务一次;用户只需配置客户端条目。调用方没有可见的已配置服务器时,在 native 或 PTC 模式下都不会获得 MCP 提示词文本或工具。 -Web 与 Desktop profile 还统一挂载一次 [MCP 服务器管理器](../../packages/mcp/mcp-manager/README.zh.md)。它运行通过 Settings 配置的服务器,以及已安装插件在自身生命周期内注册的服务器,并向 Remote 客户端提供它们的状态、重启与探测操作。注册 OAuth 服务器的插件通过 [`ui-mcp-account`](../../packages/client/ui-mcp-account/README.zh.md) 的 `ctx.mcpAccounts` 注册账号,使其显示在**插件**页面上。 +Web 与 Desktop profile 还统一挂载一次 [MCP 服务器管理器](../../packages/mcp/mcp-manager/README.zh.md)。它运行通过 Settings 配置的服务器,以及已安装插件在自身生命周期内注册的服务器,并向 Remote 客户端提供它们的状态、重启与探测操作。注册 OAuth 服务器的插件通过 [`dsh-mcp-account`](../../packages/mcp/mcp-account/README.zh.md) 的 `ctx.mcpAccounts` 注册账号,使其显示在**插件**页面上。 | 选择 | 配置维护位置 | |---|---| @@ -122,6 +122,25 @@ interface McpResourceProvider { Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnpm run verify-cordis-catalog` in doc-sync; regenerate with `pnpm run gen-cordis-catalog`) — the language sides differ only in locale-specific paired document paths. Signature blocks use a `ts cordis-catalog` fence and keep the original source JSDoc; dispatch modes are defined in the [primer](../cordis-primer.zh.md#dispatch-modes), and the framework-inherited `ctx` API lives in [cordis-api/inherited.md](../cordis-api/inherited.md). + + +### `ctx.mcpAccounts` — `McpAccounts` + +Shows each connector's MCP server account in the connector account registry. + +```ts cordis-catalog +/** + * Show one connector's server account on its bundle page for as long as the returned disposer has not run. The + * account's key is `mcp:`. + * @param registration - the server name, the bundle package, and the connector's text. + * @returns the registry's idempotent disposer, which withdraws the account. + * @throws when another account already uses the server or the package. + */ +register(registration: McpAccountRegistration): () => void +``` + +Source: [`packages/mcp/mcp-account/src/index.ts`](../../packages/mcp/mcp-account/src/index.ts) + ### `ctx.mcpClientHost` — `McpClientHost` @@ -137,14 +156,14 @@ Validates, mounts, probes, and authorizes MCP servers for the plugin that manage * @throws when the server name, a field, a template token, the reconnect policy, or OAuth beside an Authorization * header is invalid. */ -validate(input: ServerConfigInput, path: readonly string[]): ServerConfig +validate(input: ConfigInput, path: readonly string[]): Config /** * Mount one server instance below the host. The instance registers its tools and holds its `serverName` until disposed. * @param config - resolved server configuration, usually from {@link McpClientHost.validate}. * @returns the instance's activation and disposal. */ -mount(config: ServerConfig): McpServerInstance +mount(config: Config): McpServerInstance /** * Probe a server without mounting it: resolve its templates, connect, list its tools, and close. @@ -153,7 +172,7 @@ mount(config: ServerConfig): McpServerInstance * @returns the connect and list outcome with the cleanup result. * @throws for invalid options, malformed templates, or a missing required credentials provider. */ -probe(config: ServerConfig, options?: McpProbeOptions): Promise +probe(config: Config, options?: McpProbeOptions): Promise /** * Create the explicit OAuth authorization owner of one server. @@ -233,21 +252,21 @@ async probe(name: string, options?: McpProbeOptions): Promise * @param name - configured or registered OAuth entry, including disabled entries. * @returns current attempt progress; absent services, changing entries, or failed cleanup reject. */ -@Remote async startAuthorization(name: string): Promise +async startAuthorization(name: string): Promise /** * Cancel the selected attempt and drain its work; an admitted credential commit completes. * @param name - managed entry. * @param id - selected attempt; stale or absent attempts are ignored. */ -@Remote async cancelAuthorization(name: string, id: McpOAuthAttemptId): Promise +async cancelAuthorization(name: string, id: McpOAuthAttemptId): Promise /** * Drain authorization, probes, and connections before deleting the local grant; retain client registration. * A configuration change before deletion preserves the grant and rejects. * @param name - configured or registered OAuth entry; cleanup failure preserves the grant and blocks replacement. */ -@Remote async signOut(name: string): Promise +async signOut(name: string): Promise ``` Source: [`packages/mcp/mcp-manager/src/index.ts`](../../packages/mcp/mcp-manager/src/index.ts) diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index c155ec4cb6..7259adff93 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: 0baa3a0d6fb8d3be - zh: 3583d70d2507cac8 + en: 0900eea6efe5a500 + zh: 13fa6eb7dbd8c9dd /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 02b213abdb..bc2aadbeca 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -455,7 +455,7 @@ interface ToolDispatchExecution extends Omit { `ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. -A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type deliberately has no allow result: `undefined` preserves the waterfall decision, while a returned reason can only reduce permission, so a later listener cannot undo it. +A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type deliberately has no allow result: `undefined` preserves the waterfall decision, while a returned reason or `ToolGuardDenial` can only reduce permission, so a later listener cannot undo it. A denial's optional `info` becomes the failed result's structured error identity. ```ts type-equiv /** @@ -464,9 +464,19 @@ A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type delibera * returning `undefined` leaves it unchanged. Because guards have no allow * result, listener ordering cannot turn a denial back into permission. * @param execution - the identity-protected call after extensible pre-execute policy completed. - * @returns a final denial reason, or `undefined` to leave the call allowed. + * @returns a final denial reason, a denial with structured error identity, or `undefined` to leave the call allowed. */ -type ToolGuard = (execution: Readonly) => string | undefined +type ToolGuard = (execution: Readonly) => string | ToolGuardDenial | undefined +``` + +```ts type-equiv +/** A guard denial: the model-facing reason and optional structured error identity recorded on the result. */ +interface ToolGuardDenial { + /** Model-facing reason rendered as the failed call's content. */ + readonly reason: string + /** Structured error identity persisted beside the reason. */ + readonly info?: ToolErrorInfo +} ``` ```ts type-equiv @@ -522,7 +532,7 @@ interface ToolErrorInfo { } ``` -The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, guard denial, approval rejection, or post-execute block produces an `error` without `info`. +The result carries only the outcome. Call identity remains on the immutable `ToolExecution` that accompanies it through every hook and on the durable `tool/call` / `tool/result` session events, so wrappers cannot create a second, disagreeing identity. The canonical `value` is execution-local: the loop persists only `content`, `error`, and `meta`, while `tool/ptc-dispatch` stores the sub-call's rendered `content`, `isError`, optional structured `error`, and presentation `meta`. Replay reproduces presentation but cannot reconstruct canonical intermediate values. Optional `ToolErrorInfo.reason` retains raw user-facing detail without adding it to model-facing content. The registry sets `info` from a thrown `HarnessError` (its `name` and `code`), from a pre-execute `deny` that supplies it, and on its own cancellation results (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`); when a started body throws the signal's reason or an `Error` named `AbortError` after cancellation, the result keeps that message and carries `AbortError` with `ABORTED`; a `tools/execute` wrapper may also return a result with `info`, such as the timeout policy's `TOOL_TIMEOUT`. An `ask` that approval does not grant becomes a denial with the name `ApprovalError`, which identifies the registry's denial and is not a thrown class, and `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`. A guard denial or post-execute block carries `info` only when it supplies one; any other thrown value produces an `error` without `info`. On success the registry snapshots and validates the body value, freezes it, and invokes the pure renderer plus the optional presentation metadata projector for native and nested calls. It separately materializes the durable presentation fields immediately before `tools/result`; an invalid value, renderer/projector failure, or non-JSON presentation becomes a JSON-safe `isError`. The final live observer therefore sees the exact execution-local value beside fields safe for the later durable append. @@ -550,17 +560,18 @@ type PreToolDecision = ```ts type-equiv /** * Post-dispatch decision: accept, replace one projection, attach context for the - * next request, or block by turning corrective feedback into an error result. + * next request, or block by turning corrective feedback into an error result + * whose optional `info` is its structured error identity. */ type PostToolDecision = | { kind: 'accept'; content?: ContentBlock[]; value?: never; additionalContexts?: UserMessage[] } | { kind: 'accept'; value: JsonValue; content?: never; additionalContexts?: UserMessage[] } - | { kind: 'block'; feedback: ContentBlock[]; additionalContexts?: UserMessage[] } + | { kind: 'block'; feedback: ContentBlock[]; info?: ToolErrorInfo; additionalContexts?: UserMessage[] } ``` Call `next()` for the default or return a decision to short-circuit. Pre-policy may deny or ask; only `allowed-once` proceeds, while a non-grant, missing approval channel or service, or agent-less request becomes a denial. A deny may attach structured identity and user-facing detail without changing its model-facing reason. Guards may still impose a final denial. Arguments cannot be rewritten because history, audit, UI, and execution must agree. -Post-policy may replace either content or value, never both. Content replacement preserves the canonical value and existing metadata; value replacement is revalidated and recomputes content/metadata; a block removes the value and becomes an `isError` containing corrective feedback. Content replacement is presentation policy, not confidentiality policy: a listener that must hide the programmatic value blocks or replaces it. `tools/result` receives the frozen execution and result after normalization; observers cannot transform them, and observer failures are contained. Unknown and throwing tools both become structured errors (`ToolNotFoundError` maps to `UNKNOWN_TOOL`), so the call fails without ending the turn. +Post-policy may replace either content or value, never both. Content replacement preserves the canonical value and existing metadata; value replacement is revalidated and recomputes content/metadata; a block removes the value and becomes an `isError` containing corrective feedback. Content replacement is presentation policy, not confidentiality policy: a listener that must hide the programmatic value blocks or replaces it. `tools/result` receives the frozen execution and result after normalization; observers cannot transform them, and observer failures are contained. Unknown and throwing tools both become structured errors (`ToolNotFoundError` maps to `UNKNOWN_TOOL`), so the call fails without ending the turn. A tool body whose composition or call lacks a required Agent, service, or open turn throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`). ## The enforced raw JSON Schema subset @@ -733,9 +744,9 @@ guard(guard: ToolGuard): () => void /** * Check global and inherited guards after pre-execute policy and approval resolve. * @param exec - invocation whose guards are checked before dispatch. - * @returns the first denial reason, or undefined when no guard denies. + * @returns the first denial with its optional structured identity, or undefined when no guard denies. */ -checkGuards(exec: ToolExecution): string | undefined +checkGuards(exec: ToolExecution): ToolGuardDenial | undefined ``` Types: [ScopeKey](scope.md) diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 32e333c298..0edd8063a6 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -455,7 +455,7 @@ interface ToolDispatchExecution extends Omit { `ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 -`ToolGuard` 是感知作用域的最终预分派策略。其返回类型有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 只能缩减权限,因此后续监听器无法撤销它。 +`ToolGuard` 是感知作用域的最终预分派策略。其返回类型有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 或 `ToolGuardDenial` 只能缩减权限,因此后续监听器无法撤销它。拒绝中可选的 `info` 会成为失败结果的结构化错误身份。 ```ts type-equiv /** @@ -464,9 +464,19 @@ interface ToolDispatchExecution extends Omit { * returning `undefined` leaves it unchanged. Because guards have no allow * result, listener ordering cannot turn a denial back into permission. * @param execution - the identity-protected call after extensible pre-execute policy completed. - * @returns a final denial reason, or `undefined` to leave the call allowed. + * @returns a final denial reason, a denial with structured error identity, or `undefined` to leave the call allowed. */ -type ToolGuard = (execution: Readonly) => string | undefined +type ToolGuard = (execution: Readonly) => string | ToolGuardDenial | undefined +``` + +```ts type-equiv +/** A guard denial: the model-facing reason and optional structured error identity recorded on the result. */ +interface ToolGuardDenial { + /** Model-facing reason rendered as the failed call's content. */ + readonly reason: string + /** Structured error identity persisted beside the reason. */ + readonly info?: ToolErrorInfo +} ``` ```ts type-equiv @@ -522,7 +532,7 @@ interface ToolErrorInfo { } ``` -结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。其他抛出值、guard 拒绝、审批拒绝和 post-execute block 产生的 `error` 都不含 `info`。 +结果仅承载产出。调用身份保留在不可变的 `ToolExecution` 上,后者伴随结果经过每个钩子,并出现在持久化的 `tool/call` / `tool/result` 会话事件上,因此包装层无法创建第二个相互矛盾的身份。规范的 `value` 仅存在于执行期间:循环只持久化 `content`、`error` 和 `meta`,`tool/ptc-dispatch` 则存储子调用渲染后的 `content`、`isError`、可选结构化 `error` 和展示 `meta`。回放可以重现展示,却无法重建规范的中间值。可选的 `ToolErrorInfo.reason` 保留面向用户的原始详情,不将其加入模型可见内容。注册表会在以下情况设置 `info`:抛出的是 `HarnessError`(取其 `name` 和 `code`)、pre-execute 的 `deny` 自带 `info`,以及注册表自己生成的取消结果(`AbortError`,code 为 `ABORTED` 或 `ABORTED_BEFORE_DISPATCH`);已开始的工具主体在取消后抛出 signal 的 reason 或 name 为 `AbortError` 的 `Error` 时,结果保留其 message,并带上 `AbortError` 与 `ABORTED`;`tools/execute` 包装器也可能返回带 `info` 的结果,例如超时策略的 `TOOL_TIMEOUT`。审批未授予的 `ask` 会变成 name 为 `ApprovalError` 的拒绝(该 name 标识注册表的拒绝,并不对应可抛出的类),code 为 `APPROVAL_REJECTED`、`APPROVAL_CANCELLED` 或 `APPROVAL_UNAVAILABLE`。guard 拒绝或 post-execute block 只有自带 `info` 时才会携带它;其他抛出值产生的 `error` 不含 `info`。 成功时,注册表会快照并校验函数体返回值,将其冻结,然后调用纯渲染器,并为原生与嵌套调用执行可选的展示元数据投影器。注册表会在 `tools/result` 之前另行物化持久展示字段;无效值、渲染器/投影器失败或非 JSON 展示都会转为 JSON 安全的 `isError`。因此,最终实时观察者能看到精确的执行期值,以及可安全用于后续持久追加的字段。 @@ -550,17 +560,18 @@ type PreToolDecision = ```ts type-equiv /** * Post-dispatch decision: accept, replace one projection, attach context for the - * next request, or block by turning corrective feedback into an error result. + * next request, or block by turning corrective feedback into an error result + * whose optional `info` is its structured error identity. */ type PostToolDecision = | { kind: 'accept'; content?: ContentBlock[]; value?: never; additionalContexts?: UserMessage[] } | { kind: 'accept'; value: JsonValue; content?: never; additionalContexts?: UserMessage[] } - | { kind: 'block'; feedback: ContentBlock[]; additionalContexts?: UserMessage[] } + | { kind: 'block'; feedback: ContentBlock[]; info?: ToolErrorInfo; additionalContexts?: UserMessage[] } ``` 调用 `next()` 获取默认决策,或直接返回一个决策以短路。前置策略可以 deny 或 ask;只有 `allowed-once` 才继续执行,而未授权、缺少审批通道或服务、或无 agent 的请求都会变为拒绝。拒绝可以附带结构化身份与用户可见详情,而不改变其模型可见原因。Guard 仍可施加最终拒绝。参数不可被改写,因为历史记录、审计、UI 和执行必须保持一致。 -后置策略可以替换内容或值,但不能同时替换两者。替换内容会保留规范值和现有元数据;替换值会重新校验并重新计算内容/元数据;阻止会移除值,并转为包含纠正反馈的 `isError`。内容替换是展示策略,而非保密策略;需要隐藏程序化值的监听器必须阻止或替换该值。`tools/result` 在归一化后接收冻结的执行和结果;观察者无法对其进行变换,观察者的失败也会被隔离。未知工具和抛出异常的工具都会变为结构化错误(`ToolNotFoundError` 映射为 `UNKNOWN_TOOL`),调用失败但不终止当前轮次。 +后置策略可以替换内容或值,但不能同时替换两者。替换内容会保留规范值和现有元数据;替换值会重新校验并重新计算内容/元数据;阻止会移除值,并转为包含纠正反馈的 `isError`。内容替换是展示策略,而非保密策略;需要隐藏程序化值的监听器必须阻止或替换该值。`tools/result` 在归一化后接收冻结的执行和结果;观察者无法对其进行变换,观察者的失败也会被隔离。未知工具和抛出异常的工具都会变为结构化错误(`ToolNotFoundError` 映射为 `UNKNOWN_TOOL`),调用失败但不终止当前轮次。工具主体所需的 Agent、服务或进行中的 turn 不存在时,抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)。 ## 已强制执行的原始 JSON Schema 子集 @@ -733,9 +744,9 @@ guard(guard: ToolGuard): () => void /** * Check global and inherited guards after pre-execute policy and approval resolve. * @param exec - invocation whose guards are checked before dispatch. - * @returns the first denial reason, or undefined when no guard denies. + * @returns the first denial with its optional structured identity, or undefined when no guard denies. */ -checkGuards(exec: ToolExecution): string | undefined +checkGuards(exec: ToolExecution): ToolGuardDenial | undefined ``` Types: [ScopeKey](scope.zh.md) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml new file mode 100644 index 0000000000..af6b5ec552 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md +/: + en: 8436a6f26fab028f + zh: 38236167b791e6cc +/update-account-notification-consumers: + en: bd380bec124f847c + zh: fcdb87325050b311 +/update-account-notification-consumers/change: + en: 035a33041e86f008 + zh: fa1e62eba84f58ec +/update-account-notification-consumers/migration: + en: 914732f69a48d226 + zh: 251e69c9618f7445 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md new file mode 100644 index 0000000000..d2aefe105b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "Generic account notification APIs replace bonus-specific methods and notification requests use the Harness domain." +--- + +# Update account notification consumers + +English | [中文](guide.zh.md) + +## Change + +`DeepSeekAccount.getNotifications()` and `account/getNotifications` replace `getUnnotifiedBonuses()`. They return `AccountNotificationBatch.notifications` with opaque string `id`, `createdAt`, nullable `displayUntil`, localized `title` and `body`, ordered `actions`, and optional JSON `data`. The batch also requires `nextPollAfterSeconds`, projected from the wire field `next_poll_after`. Bonus metadata belongs in `data`; the bonus-specific types and fields are removed. `reportNotificationEvent()` replaces `ackBonusNotified()` and takes `(id, event, client)` to report `displayed`, `cta_clicked`, or `dismissed` using the notification ID. `getNotificationContent()` reads localized content by notification ID, including consumed notifications, without changing consumption. + +`DeepSeekAccount.watch()` and `account/watch` emit `AccountUpdate` items containing `type` and the complete `state`. Initial subscription and login progress use `snapshot`; credential writes and removal use `credentials-changed`. + +The account provider adds `harnessOrigin`, defaulting to `https://harness.deepseek.com`, for notification list, content, and events. `platformOrigin` retains its `https://platform.deepseek.com` default for login, profile, balance, logout, external navigation, and native embedded pages. Grant issuer checks still use `platformOrigin`. + +`ui-account-notifications` owns notifications; `ui-settings-account` supplies its account state, refresh events, and presentation slot. + +## Migration + +1. Read account state from `update.state`. A `credentials-changed` event or new Remote-stream generation clears notification state and restarts polling when signed in; progress snapshots retain it. Update providers, Remote consumers, and fixtures to use the new fields, opaque string IDs, and required delay in seconds. List decoding skips malformed or unsupported notifications individually; malformed envelopes still fail the request. +2. Remove notification account-ID arguments and the batch accountId field. `getNotificationContent(id, client)` and `reportNotificationEvent(id, event, client)` use the current token directly, without a profile preflight. Credential changes end old requests, cards, and polls; late replies are discarded. Report each event once; valid `acked: true` and `acked: false` responses both finish the attempt. Failed reports keep local card state and are not retried. Report `displayed` after presentation, `cta_clicked` for every non-dismiss action with no action ID, and only `dismissed` after explicit close. Action clicks retain the card and execute without waiting for the report; closing before presentation does not generate a display event; expiry and account cleanup do not count as dismissal. Refresh current cards through `getNotificationContent()` when the language changes; retain their position and avoid another display event. +3. Remove `bonusAckRetryDelayMs` and `bonusAckRetryMaxDelayMs` from `ui-settings-account` configuration; event reporting has no retry settings. A failed report does not undo the current interaction or retry that report. If a later list offers a closed notification again, the client displays it again. +4. Keep existing `platformOrigin` configuration. Private deployments and loopback fixtures set `harnessOrigin` to their notification service origin. Confirm only list, content, and events use that origin; login, profile, balance, logout, and pages retain `platformOrigin`. +5. Load `@deepseek-ai/dsh-client-ui-account-notifications` beside account settings. Set its new `notificationPollIntervalMs` option when the ten-minute initial interval is unsuitable. Move notification-state and reporting consumers to the new plugin. Verify both plugins share one account stream, including after notification-plugin reload. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md new file mode 100644 index 0000000000..8dc5b00039 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "通用账号通知 API 替换赠金专用方法,通知请求改用 Harness 域名。" +--- + +# 更新账号通知使用方 + +[English](guide.md) | 中文 + +## 变更 + +`DeepSeekAccount.getNotifications()` 和 `account/getNotifications` 替换 `getUnnotifiedBonuses()`,返回的 `AccountNotificationBatch.notifications` 包含不透明字符串 `id`、`createdAt`、可为 null 的 `displayUntil`、本地化的 `title` 与 `body`、有序的 `actions`,以及可选 JSON `data`。批次还要求提供 `nextPollAfterSeconds`,由接口字段 `next_poll_after` 投影。赠金元数据放入 `data`;赠金专用类型和字段移除。`reportNotificationEvent()` 替换 `ackBonusNotified()`,接收 `(id, event, client)`,以通知 ID 上报 `displayed`、`cta_clicked` 或 `dismissed` 事件。`getNotificationContent()` 按通知 ID 读取本地化内容,支持已消费通知,不改变消费状态。 + +`DeepSeekAccount.watch()` 和 `account/watch` 发出包含 `type` 和完整 `state` 的 `AccountUpdate`。首次订阅和登录进度使用 `snapshot`;凭据写入和删除使用 `credentials-changed`。 + +账号提供者新增 `harnessOrigin`,默认值为 `https://harness.deepseek.com`,用于通知 list、content 和 events。`platformOrigin` 保留 `https://platform.deepseek.com` 默认值,用于登录、资料、余额、退出登录、外部导航和原生内嵌页面。授权来源仍按 `platformOrigin` 校验。 + +`ui-account-notifications` 负责通知;`ui-settings-account` 提供已有账号状态、刷新事件和展示插槽。 + +## 迁移 + +1. 从 `update.state` 读取账号状态。收到 `credentials-changed` 事件或 Remote 流进入新一代连接时,清空通知状态,已登录时重启轮询;进度快照保留当前轮询。更新提供者、Remote 使用方和测试夹具,使用新字段、不透明字符串 ID 和必填的秒数间隔。列表解码逐条跳过格式错误或不支持的通知;列表外层格式错误仍使请求失败。 +2. 移除通知方法的账号 ID 参数和批次的 accountId 字段。`getNotificationContent(id, client)` 和 `reportNotificationEvent(id, event, client)` 直接使用当前 token,不前置查询资料。凭据变化后终止旧请求、卡片与轮询,并丢弃迟到的响应。每次事件只上报一次;有效的 `acked: true` 和 `acked: false` 均结束本次尝试。上报失败保留本地卡片状态,不重试。展示后上报 `displayed`,所有非 dismiss 操作点击都上报 `cta_clicked`,不携带 action ID,主动关闭仅上报 `dismissed`。点击业务按钮保留卡片并立即执行操作,不等待上报;尚未展示就关闭时不补报展示事件;过期和账号清理不计为主动关闭。切换语言时,通过 `getNotificationContent()` 刷新当前卡片,保留位置,不重复上报展示事件。 +3. 从 `ui-settings-account` 配置中移除 `bonusAckRetryDelayMs` 和 `bonusAckRetryMaxDelayMs`;事件上报没有重试配置。上报失败不撤销当前交互,也不重试该次上报。后续列表再次返回已关闭通知时,客户端会再次展示。 +4. 保留已有的 `platformOrigin` 配置。私有部署和本机测试夹具将 `harnessOrigin` 设为各自的通知服务来源。确认仅 list、content 和 events 使用该来源;登录、资料、余额、退出登录和页面保留 `platformOrigin`。 +5. 在账号设置旁加载 `@deepseek-ai/dsh-client-ui-account-notifications`。初始十分钟间隔不适用时,设置其新增的 `notificationPollIntervalMs` 选项。将通知状态及上报使用方迁移到新插件。确认两个插件共用一条账号流,包括重载通知插件之后。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml new file mode 100644 index 0000000000..91613be43b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md +/: + en: 561965d845c4ae75 + zh: 169f6d5fe2d6d3e4 +/account-service-and-remote-imports: + en: ac80b8c714afec7b + zh: 62e1e73b51c3ea1d +/account-service-and-remote-imports/change: + en: 7839978713aa24da + zh: 0225e3baa4425c46 +/account-service-and-remote-imports/migration: + en: fcaddf93cb778db9 + zh: 4921e5ef8d75ea9e diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md new file mode 100644 index 0000000000..fe31535ab3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Move account plugin composition and Remote imports to the concrete deepseek-account service." +--- + +# Account service and Remote imports + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-deepseek-account` is a concrete `DeepSeekAccount` service owning browser login, stored credentials, and the `account` Remote namespace. The abstract account class, `@deepseek-ai/dsh-deepseek-account-platform`, and `@deepseek-ai/dsh-api-account-controller` are removed. Existing `ctx.deepseekAccount` and `ctx.remote.account` operations retain their names and arguments. Host-only credential methods are not Remote operations. The `/types` entry remains available without loading the service implementation. + +Stored credentials keep the `deepseek-account-platform/default` and `deepseek-account-platform/device` keys; this package change does not require signing in again. + +## Migration + +1. Replace `@deepseek-ai/dsh-deepseek-account-platform` with `@deepseek-ai/dsh-deepseek-account` in custom plugin rows and dependencies. Keep the existing `deepseek-account` row id and configuration. Remove any `account-controller` row and its package dependency. +2. Import `DeepSeekAccount` instead of `PlatformAccount`. The class is concrete; custom subclasses of the former abstract account definition must be updated. Existing imports of shared types from `@deepseek-ai/dsh-deepseek-account/types` remain valid. +3. Replace old provider or controller `/remote` and `/typert` imports with `@deepseek-ai/dsh-deepseek-account/remote` and `@deepseek-ai/dsh-deepseek-account/typert`. +4. Import Platform header and cookie helpers from `@deepseek-ai/dsh-deepseek-account/client-metadata`. Read the configuration schema from `DeepSeekAccount.Config`. Stop calling `installAccountTaskCancellation` directly: mounting the service installs it. `isRunningAccountTask` is internal. +5. Rebuild custom compositions and verify login, notification queries, sign-out, and cancellation of account state subscriptions. Confirm that Remote exports omit `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md new file mode 100644 index 0000000000..ce523bd32a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "将账号插件组合与 Remote 导入迁移到具体的 deepseek-account 服务。" +--- + +# 账号服务与 Remote 导入 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-deepseek-account` 是具体的 `DeepSeekAccount` 服务,拥有浏览器登录、已存储凭证和 `account` Remote 命名空间。抽象账号类、`@deepseek-ai/dsh-deepseek-account-platform` 和 `@deepseek-ai/dsh-api-account-controller` 被移除。已有 `ctx.deepseekAccount` 和 `ctx.remote.account` 操作保留名称和参数。凭据相关的 Host 专用方法不会成为 Remote 操作。`/types` 出口仍可用,且不会加载服务实现。 + +已存储凭证保留 `deepseek-account-platform/default` 和 `deepseek-account-platform/device` key;这次包变更不要求重新登录。 + +## 迁移 + +1. 将自定义插件行和依赖中的 `@deepseek-ai/dsh-deepseek-account-platform` 替换为 `@deepseek-ai/dsh-deepseek-account`。保留现有 `deepseek-account` 行 id 和配置。移除所有 `account-controller` 行及其包依赖。 +2. 将 `PlatformAccount` 导入改为 `DeepSeekAccount`。该类为具体实现;继承原抽象账号定义的自定义子类需要调整。从 `@deepseek-ai/dsh-deepseek-account/types` 导入共享类型的现有代码保持有效。 +3. 将旧服务或 controller 的 `/remote`、`/typert` 导入替换为 `@deepseek-ai/dsh-deepseek-account/remote` 和 `@deepseek-ai/dsh-deepseek-account/typert`。 +4. 从 `@deepseek-ai/dsh-deepseek-account/client-metadata` 导入 Platform 请求头和 Cookie 辅助函数。从 `DeepSeekAccount.Config` 读取配置 schema。不再直接调用 `installAccountTaskCancellation`:挂载服务时会安装该逻辑。`isRunningAccountTask` 为内部函数。 +5. 重新构建自定义组合,验证登录、通知查询、退出和账号状态订阅取消。确认 Remote 导出不包含 `resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity`。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml new file mode 100644 index 0000000000..8d9654901c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +/: + en: 3938944aa9e69309 + zh: 82f148f46c1e50cf +/native-cua-application-and-window-api: + en: 207c515390c5e529 + zh: bd4d90881efb011d +/native-cua-application-and-window-api/change: + en: e5d1027faa55adba + zh: 4b88ad6a70977fb3 +/native-cua-application-and-window-api/migration: + en: 6cabae699a340845 + zh: f2256751518c5e36 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md new file mode 100644 index 0000000000..5023ac9ff0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "Migrate CUA scripts and custom native providers to scoped window input, string element IDs, and platform capabilities." +--- + +# Native CUA application and window API + +English | [中文](guide.zh.md) + +## Change + +CUA scripts use an explicit window for screenshots and pointer input. App and Window objects share the latest accessibility snapshot for their application handle. Their identifiers are `appHandle` and `windowId` respectively. Application discovery still reports the PID of a running match. + +Providers supply startup capabilities alongside their platform guidance. The native helper reports runtime permissions and session lock state. The Host combines both in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `win32` platform tag. + +## Migration + +1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. +2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. +3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. +5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. +6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md new file mode 100644 index 0000000000..880034fbd8 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "迁移 CUA 脚本和自定义原生提供方,使用显式窗口、字符串元素 ID 和平台能力声明。" +--- + +# 原生 CUA 应用和窗口 API + +[English](guide.md) | 中文 + +## 变更 + +CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享同一应用句柄最近读取的辅助功能快照。App 用 `appHandle` 标识,Window 用 `windowId` 标识。查找应用时,运行中的匹配项仍提供 PID。 + +提供方在安装时声明固定的平台能力并提供操作指引。原生 helper 返回实际的权限和会话锁定状态。Host 合并两者,作为 `getCapabilities()` 的结果。供权限页面使用的响应带有 `darwin` 或 `win32` 平台标记。 + +## 迁移 + +1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。 +2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 +3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 +5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 +6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index b04aada43b..fb0f9c5069 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,11 +9,11 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: f6fb44a85dc5e4dd - zh: 2b86ea4492c32ed7 + en: ed03fba6cf4739af + zh: b0fd9221047e1c89 /configure-models/add-a-custom-model-api: - en: 17867305a3e1b52a - zh: 876fedf1f6f563e4 + en: 1f55d7d94cbfbd80 + zh: 94e5a8bc7625d760 /configure-models/add-a-custom-model-api/discover-models: en: ec10ba53a00eddc6 zh: 857373a4e0fefee4 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index fe831bcaf9..78d7807212 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,13 +20,13 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential uses the placeholder **Leave blank to use saved credentials**, with no status text below the input. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays a masked preview in the input and a green hint that the saved key will be used. The preview retains the identifier before the first hyphen or underscore, then five leading and four trailing key characters, only when at least eight middle characters stay hidden; otherwise the entire key and identifier become dots. Counts use Unicode code points. Saved keys have no eye button and cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Apply**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Apply** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. -A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Stored credentials remain write-only. +An editable, nonempty key draft has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. ## Add a custom model API -Switch the card to **Custom model API** for a relay, a company gateway, a self-hosted server, or any provider absent from the installed catalog. Supply a lowercase Provider ID, base URL, API protocol, credential, and at least one model. The **API protocol** must be the one your gateway speaks, and the picker offers three: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages, stored in the active profile's `cordis.patch.yml` as `openai-completions`, `openai-responses`, and `anthropic-messages`. A provider speaks one protocol, so a gateway that serves two needs two providers. +Switch the card to **Custom model API** for a relay, a company gateway, a self-hosted server, or any provider absent from the installed catalog. Supply a lowercase Provider ID, base URL, API protocol, credential, and at least one model. The **API protocol** must be the one your gateway speaks, and the picker offers four: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, and Gemini API, stored in the active profile's `cordis.patch.yml` as `openai-completions`, `openai-responses`, `anthropic-messages`, and `google-generative-ai`. A Gemini API base URL includes the API version, such as `https://gateway.example/v1beta`. A provider speaks one protocol, so a gateway that serves two needs two providers. ![The custom model API form: Provider ID, display name, base URL, API protocol, and API key](providers-custom-form.png) diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index bb518c42b9..9eeef277b4 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,13 +20,13 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据使用**留空使用已保存凭据**占位文字,输入框下方不显示状态文字。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中显示脱敏预览,下方显示绿色的使用已保存密钥提示。预览保留第一个连字符或下划线之前的标识,以及密钥的前五、后四个字符,但中间必须至少隐藏八个字符;否则整串和标识全部显示为点。计数使用 Unicode 码点。已保存密钥不显示眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 -密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。已保存凭据仍保持只写。 +可编辑的密钥草稿非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 ## 添加自定义模型 API -对于中转站、公司网关、自建服务器或已安装目录中不存在的提供商,把卡片切换到**自定义模型 API**。提供小写 Provider ID、基础 URL、API 协议、凭据和至少一个模型。**API 协议**必须选网关实际使用的那一种,选择框提供三种:OpenAI Chat Completions、OpenAI Responses 和 Anthropic Messages,在当前 profile 的 `cordis.patch.yml` 中分别存为 `openai-completions`、`openai-responses` 和 `anthropic-messages`。一个提供商只使用一种协议,网关同时提供两种时需要建两个提供商。 +对于中转站、公司网关、自建服务器或已安装目录中不存在的提供商,把卡片切换到**自定义模型 API**。提供小写 Provider ID、基础 URL、API 协议、凭据和至少一个模型。**API 协议**必须选网关实际使用的那一种,选择框提供四种:OpenAI Chat Completions、OpenAI Responses、Anthropic Messages 和 Gemini API,在当前 profile 的 `cordis.patch.yml` 中分别存为 `openai-completions`、`openai-responses`、`anthropic-messages` 和 `google-generative-ai`。Gemini API 的基础 URL 包含 API 版本,例如 `https://gateway.example/v1beta`。一个提供商只使用一种协议,网关同时提供两种时需要建两个提供商。 ![自定义模型 API 表单:Provider ID、显示名称、API 地址、API 协议、API 密钥](providers-custom-form.zh.png) diff --git a/packages/acp/acp/tests/mcp.spec.ts b/packages/acp/acp/tests/mcp.spec.ts index 7455707fd8..ffbe3d818a 100644 --- a/packages/acp/acp/tests/mcp.spec.ts +++ b/packages/acp/acp/tests/mcp.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' import type { McpServer } from '@agentclientprotocol/sdk' -import type { ServerConfig as McpClientConfig } from '@deepseek-ai/dsh-mcp-client' +import type { Config as McpClientConfig } from '@deepseek-ai/dsh-mcp-client' import { mountAcpMcpServers } from '../src/mcp.ts' /** Context stand-in that captures validated MCP configs without opening transports. */ diff --git a/packages/api/account-controller/README.i18n.yaml b/packages/api/account-controller/README.i18n.yaml deleted file mode 100644 index f678c0c9f0..0000000000 --- a/packages/api/account-controller/README.i18n.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/api/account-controller/README.md -/: - en: 7ba95936e0bd5c50 - zh: 6ded94fff9da8cbe -/deepseek-ai-dsh-api-account-controller: - en: 8a461bd0ed327ba1 - zh: 456b7cea744b1f3a -/deepseek-ai-dsh-api-account-controller/summary: - en: 76e317532dcd45a4 - zh: 4571ca03d06f04a1 -/deepseek-ai-dsh-api-account-controller/table-of-contents: - en: af856ba79fe31b8e - zh: 15b7d1a5d1856de2 -/deepseek-ai-dsh-api-account-controller/use-this-package: - en: 5ad12300bbc151ef - zh: 3ccfb6046ab423ef -/deepseek-ai-dsh-api-account-controller/understand-the-implementation: - en: d76d0fa4dc48033d - zh: e193caafd78250e9 -/deepseek-ai-dsh-api-account-controller/further-exploration: - en: e5d7405e19fb6d00 - zh: f92bdfe5247d758b -/deepseek-ai-dsh-api-account-controller/model-experience: - en: ee1df7ca3467ee3f - zh: 84904a5148da3862 -/deepseek-ai-dsh-api-account-controller/model-experience/kv-cache-effect: - en: ca3015e252db0114 - zh: ebca9253cf15e8e9 -/deepseek-ai-dsh-api-account-controller/known-limitations-and-deferred-work: - en: ae26f88d13444103 - zh: d875f0909e03e160 -/deepseek-ai-dsh-api-account-controller/known-limitations-and-deferred-work/dev-note: - en: 68dabcdc229fcb50 - zh: 85514a7f6087abc3 diff --git a/packages/api/account-controller/README.md b/packages/api/account-controller/README.md deleted file mode 100644 index 3e7ff7b0bc..0000000000 --- a/packages/api/account-controller/README.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -description: "Account screens use authenticated Remote commands and a snapshot stream. The controller exposes login state without returning tokens or PKCE secrets." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-api-account-controller - -English | [中文](README.zh.md) - -## Summary - -Account screens use authenticated Remote commands and a snapshot stream. The controller exposes login state without returning tokens or PKCE secrets. - -## Table of Contents - -- [Use this package](#use-this-package) -- [Model Experience](#model-experience) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - - -## Use this package - -The account namespace exposes getState, getProfile / getBalance, getUnnotifiedBonuses, ackBonusNotified, startSignIn, cancelSignIn, signOut, and watch. watch emits an initial complete state and subsequent complete states; disconnecting stops observation, not the login attempt. Cancellation names the attempt ID so a stale screen cannot cancel a newer login. getUnnotifiedBonuses returns null and ackBonusNotified returns false while the account is absent or has changed; failures the caller should retry arrive as thrown Remote errors. - -Every operation that reaches Platform takes the calling UI's `AccountClientMetadata` — client version, active language, and UTC offset in seconds — so the Host reports the requesting UI rather than the last caller it saw. Cancellation and watch remain identity-free because they never reach Platform. - -`watchExpiry` delivers live credential-expiry notifications without an initial item or replay. Desktop uses this stream to hand off a one-shot toast when switching to Welcome. - -`hasRunningAccountTasks` checks running Agents through the account-owned predicate over their latest logged request context, including tools and retries. Idle Agents and API-key contexts are excluded. The account provider independently cancels matching tasks when credentials are removed. - - -## Understand the implementation - -The controller forwards operations to the account service and maintains no independent account state. - - -## Further Exploration - -The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. - - -## Model Experience - -None, as account credentials affect HTTP authentication and never enter model prompts, Session logs, or tool results. - -#### KV Cache effect - -No model request prefix changes. - -## Known Limitations and Deferred Work - - - -- A disconnected UI can recover account state through watch, but cannot resume an attempt after the Host exits. Credentials and request-token resolution are not Remote operations. - - -### Dev Note - -The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. diff --git a/packages/api/account-controller/README.zh.md b/packages/api/account-controller/README.zh.md deleted file mode 100644 index 7007cfdd6f..0000000000 --- a/packages/api/account-controller/README.zh.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -description: "账号页面使用经过认证的 Remote 操作和快照流。控制器提供登录状态,不返回 token 或 PKCE 私密数据。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-api-account-controller - -[English](README.md) | 中文 - -## 概述 - -账号页面使用经过认证的 Remote 操作和快照流。控制器提供登录状态,不返回 token 或 PKCE 私密数据。 - -## 目录 - -- [使用此包](#use-this-package) -- [模型体验](#model-experience) -- [已知限制与后续工作](#known-limitations-and-deferred-work) - - -## 使用此包 - -account 命名空间提供 getState、getProfile / getBalance、getUnnotifiedBonuses、ackBonusNotified、startSignIn、cancelSignIn、signOut 和 watch。watch 先发送完整初始状态,随后发送完整状态变化;断开连接只停止观察,不取消登录。取消操作必须指定尝试 ID,防止旧页面取消新登录。账号缺失或已切换时 getUnnotifiedBonuses 返回 null、ackBonusNotified 返回 false;需要调用方重试的失败以抛出的 Remote 错误返回。 - -到达 Platform 的每个操作都接收调用界面的 `AccountClientMetadata`——客户端版本、当前语言和以秒为单位的 UTC 偏移——因此 Host 报告的是发起请求的界面,而不是它上一次见到的调用方。取消和 watch 不接该参数,因为它们不会到达 Platform。 - -`watchExpiry` 仅发送实时凭据失效通知,不发送初始值,也不重放历史通知。桌面端通过该流,在切换到 Welcome 时交接一次性 toast。 - -`hasRunningAccountTasks` 通过账号模块的判断函数,检查运行中 Agent 最近记录的请求上下文,包括工具和重试阶段。空闲 Agent 及 API key 上下文不计入。移除凭据时,账号提供方独立取消匹配任务。 - - -## 理解实现 - -控制器向账号服务转发操作,不维护独立的账号状态。 - - -## 深入探索 - -[凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 - - -## 模型体验 - -无,因为账号凭证只影响 HTTP 认证,不进入模型提示、Session 日志或工具结果。 - -#### KV Cache effect - -不改变模型请求前缀。 - -## 已知限制与后续工作 - - - -- UI 断线后可通过 watch 恢复状态,但不能在 Host 退出后恢复登录尝试。凭证和请求 token 解析不对 Remote 暴露。 - - -### 开发备注 - -[桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 diff --git a/packages/api/account-controller/locale/de.json b/packages/api/account-controller/locale/de.json deleted file mode 100644 index f1e7b8ca6c..0000000000 --- a/packages/api/account-controller/locale/de.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Benutzeroberfläche für den Kontobetrieb", - "description": "Bieten Sie authentifizierten Clients Kontoverwaltungsfunktionen." - } -} diff --git a/packages/api/account-controller/locale/en.json b/packages/api/account-controller/locale/en.json deleted file mode 100644 index 4c7e6dd036..0000000000 --- a/packages/api/account-controller/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "api-account-controller" - } -} diff --git a/packages/api/account-controller/locale/es.json b/packages/api/account-controller/locale/es.json deleted file mode 100644 index 7bfaac6431..0000000000 --- a/packages/api/account-controller/locale/es.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interfaz de operación de cuenta", - "description": "Proporcionar capacidades de operación de cuentas a clientes autenticados." - } -} diff --git a/packages/api/account-controller/locale/fr.json b/packages/api/account-controller/locale/fr.json deleted file mode 100644 index a77bd7e7a1..0000000000 --- a/packages/api/account-controller/locale/fr.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface d'opération de compte", - "description": "Fournir des capacités d’exploitation de compte aux clients authentifiés." - } -} diff --git a/packages/api/account-controller/locale/ja.json b/packages/api/account-controller/locale/ja.json deleted file mode 100644 index 7ffcd54dda..0000000000 --- a/packages/api/account-controller/locale/ja.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "アカウント操作 API", - "description": "認証済みクライアントにアカウント操作機能を提供します。" - } -} diff --git a/packages/api/account-controller/locale/pt.json b/packages/api/account-controller/locale/pt.json deleted file mode 100644 index 22670a3e3b..0000000000 --- a/packages/api/account-controller/locale/pt.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface de operação da conta", - "description": "Fornece recursos de operação de conta para clientes autenticados." - } -} diff --git a/packages/api/account-controller/locale/ru.json b/packages/api/account-controller/locale/ru.json deleted file mode 100644 index dd3e515e30..0000000000 --- a/packages/api/account-controller/locale/ru.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Интерфейс работы со счетом", - "description": "Предоставьте возможности управления учетной записью аутентифицированным клиентам." - } -} diff --git a/packages/api/account-controller/locale/zh.json b/packages/api/account-controller/locale/zh.json deleted file mode 100644 index f404257eaa..0000000000 --- a/packages/api/account-controller/locale/zh.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "账号操作接口", - "description": "向已认证的客户端提供账号操作能力。" - } -} diff --git a/packages/api/account-controller/package.json b/packages/api/account-controller/package.json deleted file mode 100644 index 7731b7150d..0000000000 --- a/packages/api/account-controller/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-api-account-controller", - "description": "Expose safe account operations over authenticated Remote", - "version": "0.2.2-rc.1", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/api/account-controller" - }, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./types": { - "types": "./lib/types/types.d.ts", - "default": "./lib/types/types.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json", - "./typert": { - "types": "./lib/typert.host.d.ts", - "default": "./lib/typert.host.js" - }, - "./remote": { - "types": "./lib/typert.remote-client.d.ts", - "default": "./lib/typert.remote-client.js" - }, - "./locale/*.json": "./locale/*.json" - }, - "files": [ - "locale/*.json", - "lib/index.js", - "lib/types/**/*.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "lib/**/*.js.map", - "lib/typert.host.js", - "lib/typert.host.d.ts", - "lib/typert.remote-client.js", - "lib/typert.remote-client.d.ts", - "lib/typert.remote-client.d.ts.map", - "src" - ], - "license": "MIT", - "dependencies": { - "zod": "4.6.6" - }, - "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*" - }, - "devDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*" - } -} diff --git a/packages/api/account-controller/src/index.ts b/packages/api/account-controller/src/index.ts deleted file mode 100644 index ff065388b0..0000000000 --- a/packages/api/account-controller/src/index.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** Authenticated Remote operations for account UI consumers. */ -import { Context } from '@deepseek-ai/cordis' -import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import { isRunningAccountTask } from '@deepseek-ai/dsh-deepseek-account' -import type {} from '@deepseek-ai/dsh-agent' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import type { AccountView, SignInAttemptId } from './types.ts' - -/** Account commands and reconnect-safe state stream. */ -export class AccountController extends TypertRemoteService { - static inject = ['deepseekAccount', 'agents'] - /** @param ctx - Host with the account provider mounted. */ - constructor(ctx: Context) { super(ctx, 'accountController', { namespace: 'account' }) } - /** - * Read the safe account projection. - * @returns current account and attempt state. - */ - @Remote - getState(): Promise { return this.ctx.deepseekAccount.getState() } - /** - * Query display-safe Platform profile data. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns profile outcome, or null when the account grant is absent or changed. - */ - @Remote - getProfile(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getProfile(client) - } - /** - * Query Platform recharge-wallet balances. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns balance outcome, or null when the account grant is absent or changed. - */ - @Remote - getBalance(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getBalance(client) - } - /** - * Query the granted bonuses Platform has not yet recorded as displayed. - * @param client - identity of the requesting UI; its language selects the server-authored message. - * @returns bonuses with their account, or null when the account grant is absent or changed. - */ - @Remote - getUnnotifiedBonuses(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getUnnotifiedBonuses(client) - } - /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns true once Platform records the acknowledgement; false when the account is absent or changed. - */ - @Remote - ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.ackBonusNotified(accountId, orderId, client) - } - /** - * Begin browser sign-in. - * @param client - identity of the requesting UI, captured by a new attempt. - * @param callbackOrigin - browser-accessible loopback HTTP origin. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns a new or already-active login attempt. - */ - @Remote - startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { - return this.ctx.deepseekAccount.startSignIn(client, callbackOrigin, loginSource) - } - /** - * Cancel the named local attempt. - * @param attemptId - attempt to cancel. - * @returns settled cancellation or commit state. - */ - @Remote - cancelSignIn(attemptId: SignInAttemptId): Promise { return this.ctx.deepseekAccount.cancelSignIn(attemptId) } - /** - * Inspect the latest logged request providers of running tasks, including tools and retries. - * @returns whether running work has a latest request context on the account route. - */ - @Remote - hasRunningAccountTasks(): boolean { - return this.ctx.agents.list().some(isRunningAccountTask) - } - /** - * Remove the local account grant and revoke it through Platform in the background, without deleting API keys. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns state after removing the local account grant. - */ - @Remote - signOut(client: AccountClientMetadata): Promise { return this.ctx.deepseekAccount.signOut(client) } - /** - * Subscribe to credential expiry without replaying prior notifications. - * @param signal - stream lifetime. - * @returns notifications emitted while subscribed. - */ - @Remote({ mode: 'stream' }) - async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> { - let pending = 0 - let wake: (() => void) | undefined - const stop = this.ctx.on('deepseek-account/session-expired', () => { pending++; wake?.() }) - const abort = (): void => { wake?.() } - signal.addEventListener('abort', abort, { once: true }) - try { - while (!signal.aborted) { - if (pending > 0) { pending--; yield 'session-expired'; continue } - await new Promise((resolve) => { wake = resolve }) - } - } finally { - stop() - signal.removeEventListener('abort', abort) - } - } - /** - * Stream the safe account projection. - * @param signal - stream lifetime. - * @returns initial snapshot and subsequent changes. - */ - @Remote({ mode: 'stream' }) - watch(signal: AbortSignal): AsyncIterable { return this.ctx.deepseekAccount.watch(signal) } -} -export default AccountController diff --git a/packages/api/account-controller/src/types.ts b/packages/api/account-controller/src/types.ts deleted file mode 100644 index 3d105804f8..0000000000 --- a/packages/api/account-controller/src/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Account Remote values contain no credential payloads. */ -export type { AccountBonusBatch, AccountBonusNotification, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountProfile, AccountUserId, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' diff --git a/packages/api/account-controller/tests/controller.spec.ts b/packages/api/account-controller/tests/controller.spec.ts deleted file mode 100644 index 2360bdc84e..0000000000 --- a/packages/api/account-controller/tests/controller.spec.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** Account Remote delegation preserves provider results, failures, and stream lifetime. */ -import { Context } from '@deepseek-ai/cordis' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import type { AccountView, SignInAttemptId } from '../src/types.ts' -import { afterEach, expect, it, vi } from 'vitest' -import AccountController from '../src/index.ts' - -const roots: Context[] = [] -afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) }) -const state: AccountView = { status: 'signed-out', links: { usageUrl: 'https://platform.example/usage', topUpUrl: 'https://platform.example/top_up' }, attempt: null } -const client: AccountClientMetadata = { version: '0.0.0-test', locale: 'zh-CN', timezoneOffsetSeconds: 28_800 } - -function fixture() { - const ctx = new Context() - roots.push(ctx) - const provider = { - getState: vi.fn().mockResolvedValue(state), - getProfile: vi.fn().mockResolvedValue({ status: 'failed' }), - getBalance: vi.fn().mockResolvedValue(null), - getUnnotifiedBonuses: vi.fn().mockResolvedValue(null), - ackBonusNotified: vi.fn().mockResolvedValue(false), - startSignIn: vi.fn().mockResolvedValue(state), - cancelSignIn: vi.fn().mockResolvedValue(state), - signOut: vi.fn().mockResolvedValue(state), - watch: vi.fn(), - } - ctx.provide('deepseekAccount', provider as never) - return { ctx, provider, controller: new AccountController(ctx) } -} - -it('delegates account operations without coupling profile and balance queries', async () => { - const { provider, controller } = fixture() - expect(await controller.getState()).toBe(state) - expect(await controller.getProfile(client)).toEqual({ status: 'failed' }) - expect(provider.getBalance).not.toHaveBeenCalled() - expect(await controller.getBalance(client)).toBeNull() - expect(await controller.startSignIn(client, 'http://127.0.0.1:8080', 'desktop')).toBe(state) - expect(provider.startSignIn).toHaveBeenCalledExactlyOnceWith(client, 'http://127.0.0.1:8080', 'desktop') - const id = 'attempt' as SignInAttemptId - expect(await controller.cancelSignIn(id)).toBe(state) - expect(provider.cancelSignIn).toHaveBeenCalledExactlyOnceWith(id) - expect(await controller.signOut(client)).toBe(state) - expect(provider.signOut).toHaveBeenCalledExactlyOnceWith(client) - const failure = new Error('storage unavailable') - provider.signOut.mockRejectedValueOnce(failure) - await expect(controller.signOut(client)).rejects.toBe(failure) -}) - -it('delegates bonus reads and acknowledgements without altering their values', async () => { - const { provider, controller } = fixture() - const accountId = 'account' as AccountUserId - const orderId = 'order' as AccountBonusOrderId - const batch: AccountBonusBatch = { accountId, bonuses: [{ orderId, expiresAt: '2026-10-21T12:00:00Z', message: '已赠送您 5.00 元 DSH 体验赠金。' }] } - provider.getUnnotifiedBonuses.mockResolvedValueOnce(batch) - expect(await controller.getUnnotifiedBonuses(client)).toBe(batch) - expect(provider.getUnnotifiedBonuses).toHaveBeenCalledExactlyOnceWith(client) - provider.ackBonusNotified.mockResolvedValueOnce(true) - expect(await controller.ackBonusNotified(accountId, orderId, client)).toBe(true) - expect(provider.ackBonusNotified).toHaveBeenCalledExactlyOnceWith(accountId, orderId, client) - const failure = new Error('unavailable') - provider.getUnnotifiedBonuses.mockRejectedValueOnce(failure) - await expect(controller.getUnnotifiedBonuses(client)).rejects.toBe(failure) -}) - -it('passes the subscriber lifetime to the provider and returns its state stream', async () => { - const { provider, controller } = fixture() - const lifetime = new AbortController() - const stream: AsyncIterable = { async *[Symbol.asyncIterator]() { yield state } } - provider.watch.mockReturnValue(stream) - expect(controller.watch(lifetime.signal)).toBe(stream) - expect(provider.watch).toHaveBeenCalledExactlyOnceWith(lifetime.signal) - const received: AccountView[] = [] - for await (const value of stream) received.push(value) - expect(received).toEqual([state]) -}) - -it('delivers expiry only to current subscribers and stops on disconnect', async () => { - const { ctx, controller } = fixture() - ctx.emit('deepseek-account/session-expired') - const lifetime = new AbortController() - const iterator = controller.watchExpiry(lifetime.signal)[Symbol.asyncIterator]() - const first = iterator.next() - ctx.emit('deepseek-account/session-expired') - expect(await first).toEqual({ done: false, value: 'session-expired' }) - const next = iterator.next() - lifetime.abort() - expect(await next).toEqual({ done: true, value: undefined }) - const reconnect = new AbortController() - const reopened = controller.watchExpiry(reconnect.signal)[Symbol.asyncIterator]().next() - reconnect.abort() - expect(await reopened).toEqual({ done: true, value: undefined }) -}) diff --git a/packages/api/account-controller/tests/signout-impact.spec.ts b/packages/api/account-controller/tests/signout-impact.spec.ts deleted file mode 100644 index 837deddd27..0000000000 --- a/packages/api/account-controller/tests/signout-impact.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** Sign-out impact follows the latest logged provider of running tasks. */ -import { Context } from '@deepseek-ai/cordis' -import { expect, it } from 'vitest' -import type { Agent } from '@deepseek-ai/dsh-agent' -import { AccountController } from '../src/index.ts' - -it('reports running account requests and excludes idle or unbound tasks', async () => { - const ctx = new Context() - const active: Array> = [] - const task = (status: Agent['status'], provider?: string): Pick => ({ - status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], - }) - ctx.provide('agents', { list: () => active } as Context['agents']) - const controller = new AccountController(ctx) - try { - expect(controller.hasRunningAccountTasks()).toBe(false) - active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) - expect(controller.hasRunningAccountTasks()).toBe(false) - active.push(task('running', 'deepseek-account')) - expect(controller.hasRunningAccountTasks()).toBe(true) - active.pop() - expect(controller.hasRunningAccountTasks()).toBe(false) - } finally { await ctx.fiber.dispose() } -}) diff --git a/packages/api/account-controller/tsconfig.json b/packages/api/account-controller/tsconfig.json deleted file mode 100644 index 539e4ec237..0000000000 --- a/packages/api/account-controller/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../../credentials/deepseek-account" - }, - { - "path": "../../typert/protocol" - }, - { - "path": "../../core/agent" - } - ] -} diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index 4178adfa26..b05bc795e0 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -15,8 +15,8 @@ en: a7a78c6d1aeebeb3 zh: 4bb69f32d8b05ba3 /deepseek-ai-dsh-api-remotes/use-this-package: - en: 5e5770cc1cbf49db - zh: b9ee3c309d0cd93c + en: d8622091b217f050 + zh: c36cb87f10e7802a /deepseek-ai-dsh-api-remotes/forwarded-host-events: en: 1dea001229f8c06a zh: 3acb1fa1c5d24f8c diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 71e5dc385f..a01a776f3e 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -29,7 +29,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package selects and mounts that generated Session contribution without a direct runtime dependency on `@deepseek-ai/dsh-session`; activation policy stays with Session Controller. -The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, connector accounts, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index 5bef7cb29c..cc3c407f49 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包选择并挂载生成的会话 contribution,无需直接依赖 `@deepseek-ai/dsh-session` 的运行时;激活策略由会话控制器负责。 -Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、连接器账号、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index bf7dbbfa08..ffc73c917b 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -98,9 +98,9 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-plugin-market": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", - "@deepseek-ai/dsh-api-account-controller": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-agent-team": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 88a41e3830..ade29eff4e 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -8,7 +8,7 @@ import userQuestionsRemote from '@deepseek-ai/dsh-user-questions/remote' import commandsRemote from '@deepseek-ai/dsh-commands/remote' import agentTeamsRemote from '@deepseek-ai/dsh-agent-team/remote' export type {} from '@deepseek-ai/dsh-agent-team/remote' -import accountRemote from '@deepseek-ai/dsh-api-account-controller/remote' +import accountRemote from '@deepseek-ai/dsh-deepseek-account/remote' import settingsControllerRemote from '@deepseek-ai/dsh-api-settings-controller/remote' import officeKitRemote from '@deepseek-ai/dsh-office-kit/remote' import goalsRemote from '@deepseek-ai/dsh-goal/remote' @@ -19,6 +19,7 @@ import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote' import mcpManagerRemote from '@deepseek-ai/dsh-mcp-manager/remote' import toolResultsRemote from '@deepseek-ai/dsh-client-ui-trajectory/remote' import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +import connectorAccountsRemote from '@deepseek-ai/dsh-client-ui-connector-account/remote' import pluginMarketRemote from '@deepseek-ai/dsh-plugin-market/remote' import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote' import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote' @@ -48,6 +49,7 @@ export type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/ export type {} from '@deepseek-ai/dsh-plugin-manager/remote' export type {} from '@deepseek-ai/dsh-mcp-manager/remote' export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +export type {} from '@deepseek-ai/dsh-client-ui-connector-account/remote' export type {} from '@deepseek-ai/dsh-client-ui-trajectory/remote' export type {} from '@deepseek-ai/dsh-plugin-market/remote' export type { @@ -60,7 +62,7 @@ export type {} from '@deepseek-ai/dsh-user-questions/remote' export type {} from '@deepseek-ai/dsh-commands/remote' export type {} from '@deepseek-ai/dsh-web/remote' export type {} from '@deepseek-ai/dsh-api-settings-controller/remote' -export type {} from '@deepseek-ai/dsh-api-account-controller/remote' +export type {} from '@deepseek-ai/dsh-deepseek-account/remote' export type {} from '@deepseek-ai/dsh-goal/remote' export type {} from '@deepseek-ai/dsh-schedule/remote' export type {} from '@deepseek-ai/dsh-office-kit/remote' @@ -200,6 +202,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, scheduleRemote, pluginInventoryRemote, pluginManagerRemote, mcpManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote, + connectorAccountsRemote, toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 165661a57e..2e82590c7a 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -112,9 +112,6 @@ { "path": "../../document/office-kit" }, - { - "path": "../account-controller" - }, { "path": "../../credentials/deepseek-account" }, diff --git a/packages/api/remotes/tsconfig.host.json b/packages/api/remotes/tsconfig.host.json index 7c0421f641..33a538658d 100644 --- a/packages/api/remotes/tsconfig.host.json +++ b/packages/api/remotes/tsconfig.host.json @@ -89,9 +89,6 @@ { "path": "../../host/plugin-inventory" }, - { - "path": "../account-controller" - }, { "path": "../../credentials/deepseek-account" }, diff --git a/packages/api/settings-controller/README.i18n.yaml b/packages/api/settings-controller/README.i18n.yaml index 4b3f0d24d3..1077f9d6bd 100644 --- a/packages/api/settings-controller/README.i18n.yaml +++ b/packages/api/settings-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 3a654e12f423946b zh: 4e3a19aaee58f8a7 /settings-controller/use-this-package: - en: cf2f4de5bee8be55 - zh: b2630dcba4be5ae8 + en: 40b15565ed552a0e + zh: 3b0f125e3308aa13 /settings-controller/configuration: en: e0297f144b649af7 zh: e70ed56edffd97f0 diff --git a/packages/api/settings-controller/README.md b/packages/api/settings-controller/README.md index b38072546d..e85a4d12f1 100644 --- a/packages/api/settings-controller/README.md +++ b/packages/api/settings-controller/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) Mount this package as a Loader entry in a profile that serves browser configuration. The entry registers both namespaces independently of their providers so a missing provider produces a named configuration error at invocation. Its generated descriptors enter the strict Typert registry, while the settings and credential Definitions remain plain Cordis Services with no wire obligations of their own. -`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Secret values cross in this direction only: no method here returns one. +`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. The view may include a provider-generated `masked` preview, never the full stored value. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Full secret values cross in this direction only: no method here returns one. `settings.describe()` returns deployment facts and every namespace under `redactSecrets: true`. `settings.update`, `settings.replace`, and `settings.mutate` expose the settings service's three write operations and return the namespace's new redacted view; stale writes use `settings-conflict` and other provider refusals use `settings-rejected`. diff --git a/packages/api/settings-controller/README.zh.md b/packages/api/settings-controller/README.zh.md index 3c9e876740..c7d324b98e 100644 --- a/packages/api/settings-controller/README.zh.md +++ b/packages/api/settings-controller/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" 请把本包作为 Loader entry 挂载到提供浏览器配置的 profile 中。本 entry 不依赖提供方是否存在而注册两个 namespace,因此缺少提供方会在调用时产生具名配置错误。它生成的 descriptor 进入严格 Typert 注册表,而 settings 与凭据 Definition 仍是普通 Cordis 服务,自身不承担任何 wire 义务。 -`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 +`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。视图可包含提供方生成的 `masked` 预览,不包含完整的已保存值。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。完整机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 `settings.describe()` 返回部署信息,以及在 `redactSecrets: true` 下读取的所有 namespace。`settings.update`、`settings.replace` 与 `settings.mutate` 暴露 settings 服务的三种写入操作,并返回该 namespace 的新脱敏视图;陈旧写入使用 `settings-conflict`,其他提供方拒绝使用 `settings-rejected`。 diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 3889669048..038239ab49 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -47,6 +47,7 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo { configured: info.configured, ...info.source === undefined ? {} : { source: info.source }, writable: info.writable, + ...info.masked === undefined ? {} : { masked: info.masked }, } } @@ -61,7 +62,7 @@ declare module '@deepseek-ai/cordis' { * Host service backing the generated `ctx.remote.credentials` namespace. It * carries every wire obligation the credential seam itself does not: the batch * fan-out bound, the field-by-field view projection, the reference-grammar - * guard, and the refusal mapping. Secret values cross in one direction only — + * guard, and the refusal mapping. Full secret values cross in one direction only — * no method here returns one. */ export class CredentialsController extends TypertRemoteService { diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 5eeb190385..14f2ea2923 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -9,7 +9,7 @@ import { MemoryCredentials } from '../../../credentials/credentials/tests/memory class LeakyCredentials extends MemoryCredentials { override describe(): Promise { return Promise.resolve( - { configured: true, source: 'memory', writable: true, value: 'sk-leaked' } as CredentialInfo, + { configured: true, source: 'memory', writable: true, masked: '•'.repeat(9), value: 'sk-leaked', preview: 'sk…ed' } as CredentialInfo, ) } } @@ -101,8 +101,9 @@ describe('the credentials Remote namespace a configuration surface calls', () => it('answers only the fields the view declares, whatever a provider returns', async () => { const controller = await boot({}, LeakyCredentials) const described = await controller.describe(['DEEPSEEK_API_KEY']) - expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true }) + expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true, masked: '•'.repeat(9) }) expect(JSON.stringify(described)).not.toContain('sk-leaked') + expect(JSON.stringify(described)).not.toContain('sk…ed') }) it('stores and removes through the same references the batch describes', async () => { diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 98cb511540..ba1cfc5bda 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -24,8 +24,8 @@ en: 65bf2834b81f87da zh: c864ac60a3005b99 /deepseek-ai-dsh-app-boot/use-this-package/profiles: - en: a9c82cd220ae8d59 - zh: 8c7c1c97efcdfc25 + en: 18c32e4ba60713e6 + zh: 4f247fce2f4056bf /deepseek-ai-dsh-app-boot/use-this-package/previewing-the-effective-configuration: en: 646a0ccdd7881ad1 zh: e3696acb1573dd7b diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 46fc9be865..9cc3427cc2 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -57,7 +57,7 @@ Admission happens only at composition boundaries DSH owns, and a denied row is d Exact-version exemptions live in the profile's own `compatibility.json`, not in its `package.json`, so an exemption write never touches the dependency manifest, the bundle list, or Cordis patch files. It maps exact `package-name@version` keys to lists of exact DSH runtime versions; neither a plugin upgrade nor a DSH upgrade inherits permission. A missing file means no exemptions. A malformed one never stops the profile from starting: records the reader accepts still apply, each rejected record is reported on stderr beside the plugin denials, and the file is then treated as read-only, so a grant or revocation refuses and asks the user to repair it by hand instead of overwriting their content. [Plugin Manager](../plugin-manager/README.md#version-compatibility-and-exemptions) owns the grant, revocation, and risk confirmation each change requires. `validatePluginVersionExemption(packageVersion, runtimeVersion)` validates canonical exact identities without granting permission; invalid identities throw. -A bundle may declare `dsh.bundle.platforms` as a nonempty list of Node Host platform names, such as `["darwin"]`. The launcher validates this declaration before reading the bundle patch. An unsupported Host skips the entire layer, retains its saved selection, and reports the reason through `skippedBundles`; other layers remain effective. Omission permits every platform. Values must be Node platform names; aliases such as `macos` are invalid. Browser clients do not determine Host support. +A bundle may declare `dsh.bundle.platforms` as a nonempty list of Node Host platform names, such as `["darwin"]`. The additional `wsl` value admits Linux Hosts with WSL process or kernel markers; `linux` continues to admit all Linux Hosts. Admission does not establish Windows interoperation or desktop availability. The launcher validates this declaration before reading the bundle patch. An unsupported Host skips the entire layer, retains its saved selection, and reports the reason through `skippedBundles`; other layers remain effective. Omission permits every platform. Values must be Node platform names or `wsl`; aliases such as `macos` are invalid. Browser clients do not determine Host support. Your machine-local preferences also live in the Harness home: diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 1bc7234f55..81215bb8f7 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -57,7 +57,7 @@ profile 导入插件前,DSH 会将其声明的 DSH 版本要求与 `getDshRunt 精确版本豁免保存在 profile 自己的 `compatibility.json` 中,而不是 `package.json`,因此写豁免不会触及依赖清单、组合包列表或 Cordis patch 文件。它把精确的 `package-name@version` 键映射到精确 DSH 运行时版本列表;插件升级和 DSH 升级都不继承授权。文件缺失表示没有豁免。文件损坏绝不会阻止 profile 启动:读取器接受的记录仍然生效,每条被拒绝的记录会与插件拒绝信息一起输出到 stderr,此后该文件被视为只读,因此授予或撤销会拒绝执行并要求用户手工修复,而不是覆盖用户的内容。[插件管理器](../plugin-manager/README.zh.md#version-compatibility-and-exemptions)负责每次变更所需的授权、撤销与风险确认。`validatePluginVersionExemption(packageVersion, runtimeVersion)` 校验规范的精确身份而不授予权限;身份非法时抛出错误。 -组合包可以用 `dsh.bundle.platforms` 声明非空的 Node Host 平台名称列表,例如 `["darwin"]`。启动器在读取组合包 patch 前验证此声明。Host 不受支持时会跳过整个配置层,保留已保存的选择,并通过 `skippedBundles` 报告原因;其他配置层继续生效。省略此字段时允许所有平台。值必须是 Node 平台名,`macos` 等别名无效。浏览器所在机器的平台不决定 Host 是否受支持。 +组合包可以用 `dsh.bundle.platforms` 声明非空的 Node Host 平台名称列表,例如 `["darwin"]`。 额外的 `wsl` 值允许带有 WSL 进程或内核标记的 Linux Host;`linux` 仍允许所有 Linux Host。平台准入不代表 Windows 互操作或桌面已可用。启动器在读取组合包 patch 前验证此声明。Host 不受支持时会跳过整个配置层,保留已保存的选择,并通过 `skippedBundles` 报告原因;其他配置层继续生效。省略此字段时允许所有平台。值必须是 Node 平台名或 `wsl`,`macos` 等别名无效。浏览器所在机器的平台不决定 Host 是否受支持。 你的机器本地偏好同样位于 harness home 中: diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index 108eb792ee..8437f3debb 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -43,7 +43,8 @@ "js-yaml": "^4.3.2", "node-addon-require-builtin": "^0.1.9", "resolve.exports": "^2.0.3", - "semver": "^7.8.5" + "semver": "^7.8.5", + "@deepseek-ai/dsh-native-command": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis-plugin-group": "workspace:~", diff --git a/packages/boot/app-boot/src/bundle-platform.ts b/packages/boot/app-boot/src/bundle-platform.ts index ba9ab28968..216b1db29e 100644 --- a/packages/boot/app-boot/src/bundle-platform.ts +++ b/packages/boot/app-boot/src/bundle-platform.ts @@ -1,4 +1,5 @@ /** Host operating-system admission for optional bundle layers. */ +import { isWsl, type HostEnvironmentFacts } from '@deepseek-ai/dsh-native-command' const NODE_PLATFORMS: readonly string[] = Object.freeze([ 'aix', 'android', 'darwin', 'freebsd', 'haiku', 'linux', 'openbsd', 'sunos', 'win32', 'cygwin', 'netbsd', @@ -7,7 +8,7 @@ const NODE_PLATFORMS: readonly string[] = Object.freeze([ /** A valid bundle declaration excludes the operating system running DSH. */ export class UnsupportedBundlePlatformError extends Error { /** - * @param platforms Node platform names supported by the bundle. + * @param platforms Node platform names or `wsl` supported by the bundle. * @param platform Operating system of the DSH Host. */ constructor(platforms: readonly string[], platform: string) { @@ -20,13 +21,15 @@ export class UnsupportedBundlePlatformError extends Error { * Validate package metadata and reject an unsupported Host before selecting or composing a bundle. * @param platforms The optional `dsh.bundle.platforms` field read from package.json. * @param platform Operating system of the DSH Host, from Node's `process.platform`. + * @param facts Environment and kernel facts used to admit `wsl` on a Linux Host. * @throws When the declaration is malformed or excludes the Host; omission allows every platform. */ -export function assertBundlePlatform(platforms: unknown, platform: string): void { +export function assertBundlePlatform(platforms: unknown, platform: string, facts: Omit = {}): void { if (platforms === undefined) return if (!Array.isArray(platforms) || platforms.length === 0 - || !platforms.every((value): value is string => typeof value === 'string' && NODE_PLATFORMS.includes(value))) { - throw new Error('dsh.bundle.platforms must be a nonempty list of Node platform names') + || !platforms.every((value): value is string => typeof value === 'string' && (value === 'wsl' || NODE_PLATFORMS.includes(value)))) { + throw new Error('dsh.bundle.platforms must be a nonempty list of Node platform names or wsl') } - if (!platforms.includes(platform)) throw new UnsupportedBundlePlatformError(platforms, platform) + if (!platforms.includes(platform) && !(platforms.includes('wsl') && isWsl({ ...facts, platform }))) + throw new UnsupportedBundlePlatformError(platforms, platform) } diff --git a/packages/boot/app-boot/tests/bundle-platform.spec.ts b/packages/boot/app-boot/tests/bundle-platform.spec.ts index eaaa76c690..92455ac4ff 100644 --- a/packages/boot/app-boot/tests/bundle-platform.spec.ts +++ b/packages/boot/app-boot/tests/bundle-platform.spec.ts @@ -2,6 +2,16 @@ import { expect, it } from 'vitest' import { assertBundlePlatform, UnsupportedBundlePlatformError } from '../src/bundle-platform.ts' +it('admits WSL independently of ordinary Linux and native Windows', () => { + const wsl = { env: {}, osRelease: '6.6.87.2-microsoft-standard-WSL2' } + const linux = { env: {}, osRelease: '6.8.0-generic' } + expect(() =>{ assertBundlePlatform(['win32', 'wsl'], 'linux', wsl) }).not.toThrow() + expect(() =>{ assertBundlePlatform(['win32', 'wsl'], 'linux', linux) }).toThrow(UnsupportedBundlePlatformError) + expect(() =>{ assertBundlePlatform(['wsl'], 'win32', wsl) }).toThrow(UnsupportedBundlePlatformError) + expect(() =>{ assertBundlePlatform(['linux'], 'linux', wsl) }).not.toThrow() + expect(() =>{ assertBundlePlatform(['win32'], 'linux', wsl) }).toThrow(UnsupportedBundlePlatformError) +}) + it.each(['darwin', 'win32', 'linux'])('allows undeclared platforms and an explicit %s Host', (platform) => { expect(() => { assertBundlePlatform(undefined, platform) }).not.toThrow() expect(() => { assertBundlePlatform([platform], platform) }).not.toThrow() diff --git a/packages/boot/app-boot/tsconfig.json b/packages/boot/app-boot/tsconfig.json index b5b42ed67a..bf9741d2df 100644 --- a/packages/boot/app-boot/tsconfig.json +++ b/packages/boot/app-boot/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../../util/atomic-write" + }, + { + "path": "../../util/native-command" } ] } diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index 5a187dc4ac..d27fec562e 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: c4a9acdb98de091d - zh: 417d8bafe75157ec + en: 9dba73eeabe9887f + zh: 19291d764da21077 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 483285658e267dd5 zh: 846bec2daac59a96 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index cccb096c15..3418cd519b 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -41,7 +41,7 @@ A plugin toggle updates only `disabled` in the last matching override in the pro Bundle platform declarations are checked before saving an enabled selection. Unsupported Hosts return `unsupported-platform`. The bundle remains visible with its display metadata and can still be deselected. Automatic activation after a package operation uses the same check. The agent-facing next step asks the user to run the bundle on a supported Host. -`listBundles` retains default-hidden bundles and derives `listedByDefault` from each package’s visibility declaration and Host platform support. Unsupported bundles are hidden from default GUI lists, including More; explicit profile dependencies and saved selections remain manageable with the platform reason and deselection available. The offline Official catalog carries the same package-owned platform declaration, so uninstalled entries are checked without resolving provider code or querying a registry. These checks do not change selection or activation. A non-boolean declaration returns a metadata diagnostic. A selected bundle that cannot load remains in `listBundles` with an `error`; `enabled` records the saved selection, not successful loading. The plugin page shows the error and allows deselection. A broken bundle cannot be enabled. Management bundles remain protected if their files become unreadable. +`listBundles` retains default-hidden bundles and derives `listedByDefault` from each package’s visibility declaration and Host platform support. Unsupported bundles are hidden from default GUI lists, including More; explicit profile dependencies and saved selections remain manageable with the platform reason and deselection available. The offline Official catalog carries the same package-owned platform declaration, so uninstalled entries are checked without resolving provider code or querying a registry. These checks do not change selection or activation. A non-boolean declaration returns a metadata diagnostic, because the launcher does not read it. A selected bundle that cannot load remains in `listBundles` with an `error` and no row carrying an `entryId`; `enabled` records the saved selection, not successful loading. The plugin page marks it as not running and allows deselection. A broken bundle cannot be enabled. Management bundles remain protected if their files become unreadable. `listBundles` includes optional display `meta` for each bundle and its declared plugin rows, including disabled bundles. The Client selects a language from these values. The separate `description` field is the bundle's raw `package.json.description`; a metadata diagnostic does not block management. `source` gives a profile dependency as a spec `pnpm add` accepts: a git address or URL as recorded without the user information of an http(s) URL (a query string stays as recorded), a `file:` or `link:` path made absolute against the profile or the home directory for `~`, and a registry range, tag, or alias after the package name, as is any spec of a package installed under another name; a bundle the installation supplies has none, even when the profile also depends on it, because the installation's copy is the one that loads. The `plugin_manager` tool omits UI display metadata and update eligibility from list results. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index cfc0c99f3a..8cc04bb296 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference" 组合包的平台声明会在保存启用选择前检查。Host 不受支持时返回 `unsupported-platform`。组合包仍保留显示信息,并允许取消选择。包操作后的自动启用执行同一检查。给模型的下一步说明会提示用户在受支持的 Host 上运行该组合包。 -`listBundles` 保留默认隐藏的组合包,根据各包的展示声明和 Host 平台支持范围生成 `listedByDefault`。不支持的组合包默认不出现在主列表或“更多”中;profile 显式安装的依赖和已保存的选择仍可管理,显示平台原因并允许关闭。官方离线目录携带同一份包级平台声明,因此无需解析提供方代码或查询注册表,也能检查未安装的条目。这些检查不改变选择或激活状态。声明不是布尔值时返回元数据诊断。已选择但无法加载的组合包仍会出现在 `listBundles` 中,并携带 `error`;`enabled` 表示保存的选择,不代表加载成功。插件页面显示错误并允许取消选择。损坏的组合包无法启用。管理组合包的文件变得不可读后仍受保护。 +`listBundles` 保留默认隐藏的组合包,根据各包的展示声明和 Host 平台支持范围生成 `listedByDefault`。不支持的组合包默认不出现在主列表或“更多”中;profile 显式安装的依赖和已保存的选择仍可管理,显示平台原因并允许关闭。官方离线目录携带同一份包级平台声明,因此无需解析提供方代码或查询注册表,也能检查未安装的条目。这些检查不改变选择或激活状态。声明不是布尔值时返回元数据诊断,因为启动器不读取该声明。已选择但无法加载的组合包仍会出现在 `listBundles` 中,携带 `error`,且没有带 `entryId` 的行;`enabled` 表示保存的选择,不代表加载成功。插件页面将其标记为未运行,并允许取消选择。损坏的组合包无法启用。管理组合包的文件变得不可读后仍受保护。 `listBundles` 为各组合包及其声明的插件行提供可选的展示 `meta`,包括已禁用的组合包。Client 从这些值中选择语言。单独的 `description` 字段是该组合包原始的 `package.json.description`;元信息诊断不会阻止管理操作。`source` 以 `pnpm add` 接受的 spec 给出 profile 依赖:git 地址或 URL 按记录给出,但去掉 http(s) URL 的 user information(查询字符串保持原样);`file:` 或 `link:` 路径按 profile 目录解析为绝对路径,`~` 展开为主目录;注册表版本范围、标签或别名接在包名的 `@` 之后,以别名安装的包的 spec 也是如此。安装提供的组合包没有该字段,即使 profile 也依赖它,因为实际加载的是安装中的副本。`plugin_manager` 工具的列表结果不包含 UI 展示元信息和更新资格。 diff --git a/packages/boot/plugin-manager/src/index.ts b/packages/boot/plugin-manager/src/index.ts index 86a0f57ca1..a2cdc5e01a 100644 --- a/packages/boot/plugin-manager/src/index.ts +++ b/packages/boot/plugin-manager/src/index.ts @@ -561,14 +561,18 @@ export class PluginManager extends TypertRemoteService { } version = info.version const listedByDefault = info.dsh?.bundle?.listedByDefault - if (listedByDefault !== undefined) { - if (typeof listedByDefault !== 'boolean') throw new Error('dsh.bundle.listedByDefault must be a boolean') - listing = { listedByDefault } - } + // The launcher ignores this display field, so an invalid value is a metadata diagnostic, not a load error. + const listingDiagnostic = listedByDefault === undefined || typeof listedByDefault === 'boolean' + ? undefined + : 'dsh.bundle.listedByDefault must be a boolean' + if (typeof listedByDefault === 'boolean') listing = { listedByDefault } const compatibility = evaluatePluginCompatibility(info, exemptions) if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)]) const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir) - const meta = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href) + const read: BundleInfo['meta'] = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href) + const meta = listingDiagnostic === undefined + ? read + : { ...read, error: read?.error === undefined ? listingDiagnostic : `${read.error}; ${listingDiagnostic}` } let platformError: ManagementError | undefined try { assertBundlePlatform(info.dsh?.bundle?.platforms, process.platform) } catch (error) { platformError = managementError(error) } diff --git a/packages/boot/plugin-manager/src/types.ts b/packages/boot/plugin-manager/src/types.ts index f7655644b6..7181461421 100644 --- a/packages/boot/plugin-manager/src/types.ts +++ b/packages/boot/plugin-manager/src/types.ts @@ -85,7 +85,10 @@ export interface BundleInfo { description?: string /** Default GUI visibility after package and Host checks; selected or profile-installed bundles remain manageable. */ listedByDefault?: boolean - /** Selected in the profile manifest; a load error means its layer was skipped. */ + /** + * Selected in the profile manifest; a selected bundle whose layer was skipped carries the load `error`, and none of + * its `rows` has an `entryId`. + */ enabled: boolean /** Whether the profile declares this dependency; availability separately reports whether its files can be read. */ installed: boolean diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index ae71a3db8f..efe840989a 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -470,8 +470,16 @@ it('projects each bundle\'s default GUI listing without changing its selection, } manifest.dsh.bundle.listedByDefault = 'hidden' writeFileSync(path, JSON.stringify(manifest)) - expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({ enabled: true, - error: { diagnostic: 'dsh.bundle.listedByDefault must be a boolean' } }) + // The launcher ignores the field, so an invalid value is a metadata diagnostic beside the running layer's live row. + const invalid = (await manager.listBundles()).find(row => row.name === 'extra') + expect(invalid).toMatchObject({ enabled: true, meta: { error: 'dsh.bundle.listedByDefault must be a boolean' }, + rows: [{ rowId: 'managed', entryId: 'include:managed' }] }) + expect(invalid?.error).toBeUndefined() + expect(invalid?.listedByDefault).toBeUndefined() + // An unreadable icon keeps its own diagnostic beside the listing one. + writeFileSync(path, JSON.stringify({ ...manifest, icon: 'missing.svg' })) + expect((await manager.listBundles()).find(row => row.name === 'extra')?.meta?.error) + .toMatch(/^Plugin metadata for extra: .+; dsh\.bundle\.listedByDefault must be a boolean$/) }) it('names where each installed bundle comes from as a spec pnpm installs', async () => { diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index d94f5cf2dd..26082074f3 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -118,7 +118,7 @@ name: '@deepseek-ai/dsh-authorization' - id: deepseek-account - name: '@deepseek-ai/dsh-deepseek-account-platform' + name: '@deepseek-ai/dsh-deepseek-account' config: desktopPlatform: !!js "ctx.get('profileContext')?.name === 'desktop' && ['darwin', 'win32'].includes(process.platform) ? process.platform : null" diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index cba883cd57..4ab644e138 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -57,7 +57,7 @@ "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-config-editor": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", - "@deepseek-ai/dsh-deepseek-account-platform": "workspace:*", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 7a16271db2..cef33b6aac 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: fdf38cb6e1b24464 - zh: c14a8bcac9d4e5cd + en: 1f16cd1737256729 + zh: 1d24cd133933ad9e /deepseek-ai-dsh-web-app/understand-the-implementation: en: cc4f6d02a4d11d58 zh: 276e0929502b4fca @@ -53,6 +53,30 @@ /deepseek-ai-dsh-web-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill: + en: 276322084b9659d1 + zh: 759aae367669520a +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/what-the-model-sees: + en: 120d7eb063f9d498 + zh: 4960aab0c5e89535 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/token-effect: + en: a639f2167f49dd3d + zh: 7b627d16829f1c75 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/kv-cache-effect: + en: f4c47481baa2ab03 + zh: 31360e2558fca7f5 +/deepseek-ai-dsh-web-app/model-experience/creator-persona: + en: da4ec024b0def1bd + zh: 79dc1eae53f87aa5 +/deepseek-ai-dsh-web-app/model-experience/creator-persona/what-the-model-sees: + en: e0605965a933e81f + zh: 75473753ced8658b +/deepseek-ai-dsh-web-app/model-experience/creator-persona/token-effect: + en: ba18342fd9e04f77 + zh: 8d7a8af6f07becb0 +/deepseek-ai-dsh-web-app/model-experience/creator-persona/kv-cache-effect: + en: d0825b48e8703dcd + zh: 4afb139ba7da5bbe /deepseek-ai-dsh-web-app/model-experience/web-runtime-variable: en: 623bf8a0bf05599d zh: 398ded2e7b20c1ea diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index e2713f168b..d80b45463d 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -92,6 +92,10 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. +Standard and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. + +The packaged skill uses the custom skill root: a same-named project skill overrides it, and it overrides same-named user skills. One catalog entry wins without an error; see [skill-root priority](../../skill/skill-filesystem/README.md). + ----- @@ -150,6 +154,34 @@ Read these pages when you want to go deeper into the shared core, the browser re ## Model Experience +### DSH documentation skill + +#### What the model sees + +Standard and Creator list `dsh-doc` in the skill catalog. The `skill` tool loads its instructions and directs the agent to references for the current task. Other presets retain their own skill sources. Loading the skill does not modify workspace files or profile settings. + +#### Token effect + +The preset contributes one catalog entry. A session with no other skills also receives the catalog's shared invocation instructions. Skill bodies and reference files enter context only when loaded. + +#### KV Cache effect + +The catalog is logged at the first step and remains stable until its entries change. Loading the skill appends tool output without changing the tool schemas. + +### Creator persona + +#### What the model sees + +The Creator preset adds “You help the user customize DeepSeek Harness itself.” after the shared coding-agent sentence. Plugin implementation and authorization rules remain in the on-demand `dsh-doc` skill. + +#### Token effect + +One fixed sentence is added to Creator requests. Standard requests are unchanged. + +#### KV Cache effect + +The sentence is stable within the Creator preset; switching to a different preset changes the persona prefix. + ### Web runtime variable #### What the model sees diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 994400807e..8952c0d315 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -92,6 +92,10 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 +标准模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 + +打包的 skill 使用自定义 skill 根目录:同名的项目 skill 会覆盖打包的 skill,打包的 skill 又会覆盖同名的用户 skill。skill 目录中只保留优先级最高的一个条目,不会报错;参见 [skill 根目录优先级](../../skill/skill-filesystem/README.zh.md)。 + ----- @@ -150,6 +154,34 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 ## 模型体验 +### DSH 文档 skill + +#### 模型看到什么 + +标准模式和创造模式的 skill 目录都列出 `dsh-doc`。`skill` 工具加载其指令,并引导 agent 查阅当前任务所需的参考资料。其他 preset 保留各自的 skill 来源。加载该 skill 不会修改工作区文件或 profile 设置。 + +#### Token 影响 + +preset 提供一条目录项。没有其他 skill 的会话还会收到目录的通用调用说明。skill 正文和参考文件仅在加载时进入上下文。 + +#### KV Cache 影响 + +目录在第一个步骤写入日志,在条目改变前保持不变。加载 skill 会追加工具输出,不改变工具 schema。 + +### 创造模式角色设定 + +#### 模型看到什么 + +创造模式预设在共享的编码 Agent 描述句之后添加“You help the user customize DeepSeek Harness itself.”。插件实现和授权规则仍保留在按需加载的 `dsh-doc` skill 中。 + +#### Token 影响 + +创造模式请求增加一句固定文本。标准模式请求不变。 + +#### KV Cache 影响 + +该句在创造模式预设内保持稳定;切换到其他预设会改变角色设定前缀。 + ### Web 运行时变量 #### 模型看到什么 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index e124857e13..53f36cf877 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -140,20 +140,12 @@ - id: ui-settings-account name: '@deepseek-ai/dsh-client-ui-settings-account' - - id: account-controller - name: '@deepseek-ai/dsh-api-account-controller' + - id: ui-account-notifications + name: '@deepseek-ai/dsh-client-ui-account-notifications' - id: settings-controller name: '@deepseek-ai/dsh-api-settings-controller' - # The MCP client host connects no server: the manager below validates, - # mounts, probes, and authorizes servers through it, so a reload of the MCP - # client replaces its servers and restarts the manager. - - id: mcp-client-host - name: '@deepseek-ai/dsh-mcp-client' - config: - host: true - # One shared MCP server fleet: Settings-configured servers plus servers # that installed plugins register, with status and recovery over Remote. # Credential templates and OAuth grants resolve through the credentials @@ -162,6 +154,11 @@ name: '@deepseek-ai/dsh-mcp-manager' inject: [credentials] + # MCP connector accounts on the Plugins page; connectors register their + # OAuth server with `ctx.mcpAccounts`. + - id: mcp-account + name: '@deepseek-ai/dsh-mcp-account' + # Workspace commands and reconnect-safe projection over Typert Remote. - id: workspace-controller name: '@deepseek-ai/dsh-api-workspace-controller' @@ -349,6 +346,11 @@ - id: ui-plugin-manager name: '@deepseek-ai/dsh-client-ui-plugin-manager' + # Connector account sections on the Plugins page; CLI app plugins and MCP + # connectors register their accounts with `ctx.connectorAccounts`. + - id: ui-connector-account + name: '@deepseek-ai/dsh-client-ui-connector-account' + # Read-only Plugin list tab in the Settings Plugins section; the built-in # bundles the sidebar page leaves out are inspected here. - id: ui-settings-plugin-inventory @@ -451,12 +453,6 @@ - id: ui-message-feedback name: '@deepseek-ai/dsh-client-ui-message-feedback' - # MCP connector plugins register their OAuth accounts with the `mcpAccounts` - # registry; the Plugins page shows each account's section, title tag, - # activation guidance, and notices through the `mcpAccounts` Remote. - - id: ui-mcp-account - name: '@deepseek-ai/dsh-client-ui-mcp-account' - # Model selection: the /model popupSelect + composer seat over session.models. - id: ui-model-selection name: '@deepseek-ai/dsh-client-ui-model-selection' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index df1a86695b..4cf8df335a 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -78,25 +78,28 @@ "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", + "@deepseek-ai/dsh-client-ui-account-notifications": "workspace:*", "@deepseek-ai/dsh-client-ui-agent-preset": "workspace:*", "@deepseek-ai/dsh-client-ui-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", "@deepseek-ai/dsh-client-ui-attachment": "workspace:*", "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", - "@deepseek-ai/dsh-message-quotes": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-commands": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-cordis": "workspace:*", "@deepseek-ai/dsh-client-ui-deliverables": "workspace:*", "@deepseek-ai/dsh-client-ui-directory-picker-browse": "workspace:*", "@deepseek-ai/dsh-client-ui-directory-picker-native": "workspace:*", "@deepseek-ai/dsh-client-ui-entry-customization": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", "@deepseek-ai/dsh-client-ui-goal": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-jobs": "workspace:*", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", - "@deepseek-ai/dsh-client-ui-mcp-account": "workspace:*", "@deepseek-ai/dsh-client-ui-message-feedback": "workspace:*", "@deepseek-ai/dsh-client-ui-model-selection": "workspace:*", "@deepseek-ai/dsh-client-ui-open-in-app": "workspace:*", @@ -154,9 +157,10 @@ "@deepseek-ai/dsh-host-product-telemetry-otel": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-mcp-client": "workspace:*", + "@deepseek-ai/dsh-mcp-account": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-message-feedback": "workspace:*", + "@deepseek-ai/dsh-message-quotes": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-persona": "workspace:*", "@deepseek-ai/dsh-plan-mode": "workspace:*", @@ -200,19 +204,7 @@ "@deepseek-ai/dsh-workspace-changes": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "commander": "^15.0.0", - "open": "^11.0.2", - "@deepseek-ai/dsh-api-account-controller": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-ui-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*", - "@deepseek-ai/dsh-host-product-telemetry-otel": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*", - "@deepseek-ai/dsh-harness-dev-context": "workspace:*", - "@deepseek-ai/dsh-deliverable-file-references": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*" + "open": "^11.0.2" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index 0fc32e6248..d0c9f7f419 100644 --- a/packages/bundle/web-app/presets/cordis.patch.yml +++ b/packages/bundle/web-app/presets/cordis.patch.yml @@ -8,13 +8,13 @@ id: cordis order: 4 plugins: - # Same persona as `standard`: tool descriptions and the skill catalog carry - # the operating detail, and the dsh-doc skill owns the preset-authoring rules. + # The dsh-doc skill owns plugin implementation and authorization guidance. - id: persona name: '@deepseek-ai/dsh-persona' config: prefix: >- You are a coding agent powered by the {{model}} model. + You help the user customize DeepSeek Harness itself. - id: agent-instructions name: '@deepseek-ai/dsh-agent-instructions' config: diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index a40aab5aa9..d0bca7e336 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -39,6 +39,9 @@ name: '@deepseek-ai/dsh-tool-schedule' - id: skill-filesystem name: '@deepseek-ai/dsh-skill-filesystem' + config: + customSkillDirs: + - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills') - id: tool-skill name: '@deepseek-ai/dsh-tool-skill' - id: command-goal diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 967308fa47..54854f5f19 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 89f143e725defcef - zh: 4beaf092d9cf98c3 + en: affd6d8506276e34 + zh: 92730ec91d83d609 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 1513d71623..6edf512eb4 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -83,11 +83,11 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-settings-subagent/`](ui-settings-subagent/README.md) | Provides the Subagent settings page on the Plugins page | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.md) | Provides the web search and fetch settings page on the Plugins page | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.md) | Contributes the sidebar Plugins panel: install, enable, disable, retry, and compose installed packages | — | +| [`ui-connector-account/`](ui-connector-account/README.md) | Holds the accounts connector plugins register on the Host and shows each bundle's account section, tag, activation prompt, confirmations, and notices on the Plugins page | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.md) | Adds region-local More menus that pin or unpin plugin launchers and start a plugin draft | — | | [`ui-plugin-market/`](ui-plugin-market/README.md) | Contributes the Discover tab to the Plugins page: browse market indexes and install their bundles | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings | — | | [`ui-deliverables/`](ui-deliverables/README.md) | Produces the changed-files card with its comparison tabs, delivery cards, and clickable final-response file references | — | -| [`ui-mcp-account/`](ui-mcp-account/README.md) | Holds the OAuth accounts MCP connector plugins register on the Host and shows each one's section, tag, activation guidance, and notices on the Plugins page | `ctx.mcpAccounts` | | [`ui-message-feedback/`](ui-message-feedback/README.md) | Provides message ratings and feedback dialogs opened from ratings, `/feedback`, or the Session Header menu | `ctx.feedbackUi` | | [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.md) | In-app directory browsing surface for the workspace directory flow | — | | [`ui-directory-picker-native/`](ui-directory-picker-native/README.md) | Native directory-picker surface driving the local Desktop or Host OS chooser | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 6253cdca92..635750069e 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -83,11 +83,11 @@ kind: "package-group" | [`ui-settings-subagent/`](ui-settings-subagent/README.zh.md) | 在插件页提供子智能体设置页 | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.zh.md) | 在插件页提供网页搜索与获取设置页 | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.zh.md) | 贡献侧栏的“插件”面板:安装、启用、停用、重试与组合已安装的包 | — | +| [`ui-connector-account/`](ui-connector-account/README.zh.md) | 保存连接器插件在 Host 上注册的账号,并在插件页显示每个插件包的账号区块、标签、开启引导、确认和提示 | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.zh.md) | 添加分区域的“更多”菜单,固定或收起插件入口,并开始创建插件的草稿 | — | | [`ui-plugin-market/`](ui-plugin-market/README.zh.md) | 为“插件”页面贡献“发现”标签页:浏览市场索引并安装其中的组合包 | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.zh.md) | 向「插件」设置贡献只读的 Host Loader 清单标签页 | — | | [`ui-deliverables/`](ui-deliverables/README.zh.md) | 生成改动文件卡片及其对比 tab、交付文件卡片与可点击的最终响应文件引用 | — | -| [`ui-mcp-account/`](ui-mcp-account/README.zh.md) | 保存 MCP 连接器插件在 Host 上注册的 OAuth 账号,并在插件页面显示每个账号的区块、标签、开启后的引导与提示 | `ctx.mcpAccounts` | | [`ui-message-feedback/`](ui-message-feedback/README.zh.md) | 提供消息赞踩,以及从赞踩、`/feedback` 或会话标题栏菜单打开的反馈弹窗 | `ctx.feedbackUi` | | [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.zh.md) | 面向工作区目录流程的应用内目录浏览界面 | — | | [`ui-directory-picker-native/`](ui-directory-picker-native/README.zh.md) | 驱动本地 Desktop 或 Host OS 选择器的原生目录选择界面 | — | diff --git a/packages/client/ui-account-notifications/README.i18n.yaml b/packages/client/ui-account-notifications/README.i18n.yaml new file mode 100644 index 0000000000..1ce8f44b0d --- /dev/null +++ b/packages/client/ui-account-notifications/README.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-account-notifications/README.md +/: + en: 46ed0081fc307e5d + zh: d9ed06af27b3cb29 +/deepseek-ai-dsh-client-ui-account-notifications: + en: c8d24427c7fcd3aa + zh: 5c0cf16f36ae6165 +/deepseek-ai-dsh-client-ui-account-notifications/summary: + en: 46cf31a87b0b765c + zh: 04f6b33570b046f7 +/deepseek-ai-dsh-client-ui-account-notifications/table-of-contents: + en: af856ba79fe31b8e + zh: c9b0188689359236 +/deepseek-ai-dsh-client-ui-account-notifications/use-this-package: + en: c466836df88d4ae1 + zh: 036e859139daa51d +/deepseek-ai-dsh-client-ui-account-notifications/model-experience: + en: 5fed5504300020e6 + zh: efd8e7c32b699e7e +/deepseek-ai-dsh-client-ui-account-notifications/model-experience/kv-cache-effect: + en: ca3015e252db0114 + zh: fb634b5b32d09f37 +/deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work: + en: 0d59eea475321fd0 + zh: 1cf67a196e76b832 +/deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work/dev-note: + en: 64006edb418180b1 + zh: 12f7d7ab2cbccd43 diff --git a/packages/client/ui-account-notifications/README.md b/packages/client/ui-account-notifications/README.md new file mode 100644 index 0000000000..10a0eeaadb --- /dev/null +++ b/packages/client/ui-account-notifications/README.md @@ -0,0 +1,57 @@ +--- +description: "Display account notifications and refresh their localized content." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-account-notifications + +English | [中文](README.zh.md) + +## Summary + +Show server-authored account notifications beside the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) + + +## Use this package + +The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; the account menu supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports. + +Startup with a stored account, sign-in, and each Settings entry start a new polling cycle with an immediate request. `notificationPollIntervalMs` on the `ui-account-notifications` row supplies the initial delay, defaulting to 600,000 ms. A successful list response replaces it with `next_poll_after` seconds, including empty lists. The delay starts after the request settles; failures retain the latest delay, and restarting restores the configured initial value. Polling continues in the background. + +Account settings owns the sole account stream and exposes its current state and lifecycle events through `accountUi` and `account-ui/change`. Login-progress updates retain cards and polling. Credential replacement, disconnection, access revocation, sign-out, and plugin disposal clear cards, stop polling, and discard late replies. Notification requests do not wait for profile or avatar data. Notification state is not stored in the browser. + +Cards render inside the sidebar above the account launcher and below menus and dialogs without taking focus. Their width follows the expanded launcher up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences. + +Notifications wait for Desktop and model-credential onboarding to finish. Only the foreground card is interactive and reports `displayed`, once per mount after a painted frame while it intersects the viewport and the sidebar and document are visible. The Settings overlay does not exclude that frame. A displayed foreground card remains until close or expiry even when a later list omits it; waiting cards follow server order. + +Each card uses the server's plain-text title, body, and ordered primary or secondary buttons. Every non-dismiss action reports `cta_clicked` with the notification ID, executes immediately, and retains the card; the account action opens Account settings. Closing through the close button or a dismiss action reports only `dismissed` as the card is removed, before the next card moves into place. Closing before the first painted frame does not report `displayed`. Expiry and account cleanup do not report dismissal. Click reports contain no action ID or target. + +Each interaction is reported once without waiting or retrying; either boolean acknowledgement completes that attempt. A failed report logs a diagnostic without an account UI error or undoing the interaction. The server owns consumption: a later list may offer a closed card again. List failures keep the current cards. + +Switching language requests current cards through the content endpoint, including consumed cards, without another list query or display report. Content updates preserve card identity, order, and focus. Failed reads retain the previous text and log a diagnostic; replies for an older language, signed-out account, or closed card cannot restore stale content. + + +## Model Experience + +None, as notifications remain client presentation data and never enter model requests or Session logs. + +#### KV Cache effect + +No model request prefix changes. + +## Known Limitations and Deferred Work + + + +- Cards retain the existing expiry and foreground-retention behavior. Server copy is plain text; supported actions dismiss the card or open Account settings. Network failures keep current cards and resume on the next poll. + + +### Dev Note + +The package tests cover lifecycle ownership; the Web notification scenario checks the assembled account menu. diff --git a/packages/client/ui-account-notifications/README.zh.md b/packages/client/ui-account-notifications/README.zh.md new file mode 100644 index 0000000000..adbae8cac4 --- /dev/null +++ b/packages/client/ui-account-notifications/README.zh.md @@ -0,0 +1,57 @@ +--- +description: "展示账号通知并刷新本地化内容。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-account-notifications + +[English](README.md) | 中文 + +## 概述 + +在账号菜单旁展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。 + +## 目录 + +- [使用此包](#use-this-package) +- [模型体验](#model-experience) +- [已知限制与待办](#known-limitations-and-deferred-work) + + +## 使用此包 + +Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号菜单提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。 + +带有已存账号的启动、登录及每次进入设置页都会启动新一轮轮询,并立即请求。`ui-account-notifications` 行中的 `notificationPollIntervalMs` 提供初始间隔,默认 600,000 ms。成功的列表响应通过 `next_poll_after` 秒替换间隔,空列表也相同。从请求结束时开始计时;失败沿用最近间隔,重启轮询恢复配置的初始值。轮询在后台继续。 + +账号设置拥有唯一的账号流,通过 `accountUi` 和 `account-ui/change` 提供当前状态及生命周期事件。登录进度更新沿用卡片和轮询。凭据替换、断连、权限撤销、退出登录和插件卸载会清空卡片、停止轮询并丢弃迟到响应。通知请求不等待资料或头像。通知状态不写入浏览器存储。 + +卡片在侧栏内部、账号入口上方渲染,位于菜单和对话框之下,不抢占焦点。宽度跟随展开的账号入口,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。 + +通知等待 Desktop 和模型凭据引导完成。只有前排卡片可交互并上报 `displayed`:卡片与视口相交、侧栏和文档可见并完成一帧绘制后,同一次挂载只上报一次。设置蒙层不排除该帧。已展示的前排卡片保留至关闭或过期,即使后续列表不再返回它;待展示卡片遵循服务端顺序。 + +每张卡片使用服务端纯文本标题、正文和有序的主要或次要按钮。所有非 dismiss 操作都携带通知 ID 上报 `cta_clicked`,立即执行并保留卡片;账号操作会打开账号设置。通过关闭按钮或 dismiss 操作关闭时,在移除卡片、下一张开始补位前只上报 `dismissed`。首帧绘制前关闭不会补报 `displayed`。过期和账号清理不上报关闭。点击上报不携带 action ID 或 target。 + +每次交互只上报一次,不等待、不重试;任一布尔确认结果都会结束本次尝试。上报失败会记录诊断日志,不在账号界面报错,也不撤销交互。消费状态由服务端决定:后续列表可能再次返回已关闭的卡片。列表失败保留当前卡片。 + +切换语言通过内容接口请求当前卡片,支持已消费通知,不重新查询列表或上报展示。内容更新保留卡片身份、顺序和焦点。读取失败保留原文并记录诊断日志;旧语言、已退登账号或已关闭卡片的响应不会恢复过时内容。 + + +## 模型体验 + +无,通知属于客户端展示数据,不进入模型请求或 Session 日志。 + +#### KV 缓存影响 + +模型请求前缀不变。 + +## 已知限制与待办 + + + +- 卡片保留现有的过期与前排保留行为。服务端文案使用纯文本;支持的操作为关闭卡片或打开账号设置。网络失败保留当前卡片,并在下次轮询时继续。 + + +### 开发备注 + +包内测试覆盖生命周期所有权;Web 通知场景验证组合后的账号菜单。 diff --git a/packages/client/ui-account-notifications/locale/de.json b/packages/client/ui-account-notifications/locale/de.json new file mode 100644 index 0000000000..3584bba2da --- /dev/null +++ b/packages/client/ui-account-notifications/locale/de.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Kontobenachrichtigungen" + } +} diff --git a/packages/client/ui-account-notifications/locale/en.json b/packages/client/ui-account-notifications/locale/en.json new file mode 100644 index 0000000000..e2cad8bd35 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Account notifications" + } +} diff --git a/packages/client/ui-account-notifications/locale/es.json b/packages/client/ui-account-notifications/locale/es.json new file mode 100644 index 0000000000..ae797bfded --- /dev/null +++ b/packages/client/ui-account-notifications/locale/es.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notificaciones de la cuenta" + } +} diff --git a/packages/client/ui-account-notifications/locale/fr.json b/packages/client/ui-account-notifications/locale/fr.json new file mode 100644 index 0000000000..254e2e6fa3 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/fr.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notifications du compte" + } +} diff --git a/packages/client/ui-account-notifications/locale/ja.json b/packages/client/ui-account-notifications/locale/ja.json new file mode 100644 index 0000000000..8a82ef90bf --- /dev/null +++ b/packages/client/ui-account-notifications/locale/ja.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "アカウント通知" + } +} diff --git a/packages/client/ui-account-notifications/locale/pt.json b/packages/client/ui-account-notifications/locale/pt.json new file mode 100644 index 0000000000..19f27cc8e7 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/pt.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notificações da conta" + } +} diff --git a/packages/client/ui-account-notifications/locale/ru.json b/packages/client/ui-account-notifications/locale/ru.json new file mode 100644 index 0000000000..743b8451dd --- /dev/null +++ b/packages/client/ui-account-notifications/locale/ru.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Уведомления аккаунта" + } +} diff --git a/packages/client/ui-account-notifications/locale/zh.json b/packages/client/ui-account-notifications/locale/zh.json new file mode 100644 index 0000000000..e8b0422500 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "账号通知" + } +} diff --git a/packages/client/ui-account-notifications/package.json b/packages/client/ui-account-notifications/package.json new file mode 100644 index 0000000000..de3bd6aa8b --- /dev/null +++ b/packages/client/ui-account-notifications/package.json @@ -0,0 +1,74 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-account-notifications", + "description": "Display account notifications and refresh localized content", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-account-notifications" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-settings-account" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@testing-library/react": "^16.3.3", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + } +} diff --git a/packages/client/ui-settings-account/src/client/AccountNotice.module.css b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css similarity index 82% rename from packages/client/ui-settings-account/src/client/AccountNotice.module.css rename to packages/client/ui-account-notifications/src/client/AccountNotifications.module.css index 4ece2277fc..cd508405b9 100644 --- a/packages/client/ui-settings-account/src/client/AccountNotice.module.css +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css @@ -1,11 +1,13 @@ /* Each deeper card is centered 4px above the preceding card and narrows by the - design's 272/280 ratio. The foreground alone determines the stack height. */ -.stack { position: fixed; z-index: 40; isolation: isolate; width: 280px; max-width: calc(100vw - 16px); } + design's 252/260 ratio. The foreground alone determines the stack height. */ +.stack { position: relative; isolation: isolate; width: 100%; max-width: 280px; } .card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; } .card[data-front="false"] { position: absolute; inset: 0; height: 100%; overflow: hidden; pointer-events: none; } @media (prefers-reduced-motion: reduce) { .card { transition: none; } } .copy { display: flex; flex-direction: column; gap: 2px; overflow-wrap: anywhere; } .copy p { margin: 0; white-space: pre-wrap; } +.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } +.action { max-width: 100%; height: auto; min-height: 28px; white-space: normal; overflow-wrap: anywhere; } .title { display: flex; align-items: flex-start; gap: 2px; line-height: 20px; font-weight: 500; } .icon { display: flex; flex: none; width: 14px; height: 14px; margin-top: 1px; color: var(--dsw-alias-brand-primary-new-colorprimary-new-color); } .close { position: absolute; top: 6px; right: 6px; display: flex; align-items: center; justify-content: center; width: 18px; height: 18px; padding: 4px; border: 0; background: transparent; color: var(--dsw-alias-label-caption); cursor: pointer; } diff --git a/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx new file mode 100644 index 0000000000..1776aee512 --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx @@ -0,0 +1,175 @@ +/** Notification extension rendered inside the sidebar account menu. */ +import { useEffect, useRef, type CSSProperties } from 'react' +import { Button, IconCloseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-settings-account/client' +import type { AccountNotice } from './notification-controller.ts' +import type { NotificationKey } from './locales.ts' +import css from './AccountNotifications.module.css' +import { dismissNotice } from './notice-transition.ts' + +/** Notification view and interactions supplied by the notification plugin. */ +export interface AccountNotificationsInjected { + hooks: { notices: HostObservable } + /** @param id - notification that completed a displayed frame. */ + shown: (id: AccountNotice['id']) => void + /** @param id - foreground notification whose non-dismiss action was clicked. */ + ctaClicked: (id: AccountNotice['id']) => void + /** @param id - notification explicitly closed by the user. */ + dismiss: (id: AccountNotice['id']) => void +} + +/** Notification component props derived from its parent-owned slot. */ +export type AccountNotificationsProps = PropsRuntime<'settings.launcher.notifications'> + & InjectFace & PropsLocale<'account.notifications'> + +/** @param props - account-menu availability and notification content. @returns the anchored notification stack. */ +export function AccountNotifications({ active, openAccount, useNotices, shown, ctaClicked, dismiss, t }: AccountNotificationsProps) { + const notices = useNotices(value => value) + return active && +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { 'account.notifications': NotificationKey } +} + +/* v8 ignore next 3 -- closed-union defaults only defend future source widening */ +function assertNever(_value: never): never { + throw new Error('unsupported account notification target') +} + +/** @param displayUntil - server display deadline. @returns whether the notification remains eligible for display. */ +function live(displayUntil: string | null): boolean { + if (displayUntil === null) return true + const expires = Date.parse(displayUntil) + // An unparsable timestamp is not evidence of expiry, so the notice still shows. + return Number.isNaN(expires) || expires > Date.now() +} + +/** + * @param run - callback to invoke once one presented frame has passed. + * @returns a canceller for a card that unmounts or hides first. + */ +function afterPaint(run: () => void): () => void { + if (typeof requestAnimationFrame !== 'function') { + // Without a frame clock, the following task is the best available paint boundary. + const timer = setTimeout(run, 0) + return () => { clearTimeout(timer) } + } + let cancelled = false + let timer: ReturnType | undefined + const frame = requestAnimationFrame(() => { + // The frame callback runs before its paint; the following task runs after it. + timer = setTimeout(() => { + if (!cancelled) run() + }, 0) + }) + return () => { + cancelled = true + cancelAnimationFrame(frame) + if (timer !== undefined) clearTimeout(timer) + } +} + +/** @param props - server-ordered notices, localized fallback copy, and display callbacks. + * @returns a non-modal stack whose foreground card alone can report display or be closed. + */ +export function AccountNoticeStack({ notices, closeLabel, onShown, onCtaClicked, onDismiss, onOpenAccount }: { + notices: readonly AccountNotice[] + closeLabel: string + /** Open the account settings route while retaining the notification. */ + onOpenAccount: () => void + /** Called after the foreground card has passed a visible presented frame. */ + onShown: (id: AccountNotice['id']) => void + /** Called when the user clicks any non-dismiss action on the foreground card. */ + onCtaClicked: (id: AccountNotice['id']) => void + /** Called when the user closes the foreground card. */ + onDismiss: (id: AccountNotice['id']) => void +}) { + const liveNotices = notices.filter(notice => live(notice.displayUntil)) + return
+ {liveNotices.map((notice, depth) => )} +
+} + +/** One stable card node remains mounted as the cards before it are dismissed. */ +function NoticeCard({ notice, depth, closeLabel, onShown, onCtaClicked, onDismiss, onOpenAccount }: { + notice: AccountNotice + depth: number + closeLabel: string + onOpenAccount: () => void + onShown: (id: AccountNotice['id']) => void + onCtaClicked: (id: AccountNotice['id']) => void + onDismiss: (id: AccountNotice['id']) => void +}) { + const foreground = depth === 0 + const card = useRef(null) + const reported = useRef(false) + const actionSlots = new Map() + useEffect(() => { + if (!foreground || reported.current || !live(notice.displayUntil)) return + const element = card.current + /* v8 ignore next -- React attaches the card ref before running this effect. */ + if (element === null) return + let intersecting = false + let cancel: (() => void) | undefined + const visible = () => intersecting && document.visibilityState !== 'hidden' && !element.closest('[hidden], [inert]') + const attempt = () => { + if (reported.current || cancel !== undefined || !live(notice.displayUntil)) return + if (!visible()) return + cancel = afterPaint(() => { + cancel = undefined + if (reported.current || !visible() || !live(notice.displayUntil)) return + reported.current = true + onShown(notice.id) + }) + } + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + intersecting = entry.isIntersecting + attempt() + } + }) + observer.observe(element) + document.addEventListener('visibilitychange', attempt) + return () => { + observer.disconnect() + document.removeEventListener('visibilitychange', attempt) + cancel?.() + } + }, [foreground, notice.id, notice.displayUntil, onShown]) + return +} diff --git a/packages/client/ui-account-notifications/src/client/index.ts b/packages/client/ui-account-notifications/src/client/index.ts new file mode 100644 index 0000000000..3b5adafe27 --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/index.ts @@ -0,0 +1,68 @@ +/** Account notifications driven by the existing account UI stream. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { AccountUiState } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from '../config.ts' +import { AccountNotifications, type AccountNotificationsInjected } from './AccountNotifications.tsx' +import { createNotificationController, type AccountNotice } from './notification-controller.ts' +import { en, zh, ja, es, fr, de, ru, pt } from './locales.ts' +export type { AccountNotificationsInjected, AccountNotificationsProps } from './AccountNotifications.tsx' + +/** Services used for notification lifecycle and presentation. */ +export const inject = ['slots', 'locale', 'remote', 'remote.account', 'accountUi'] + +/** @param ctx - client plugin context sharing the account owner's existing state stream. */ +export function apply(ctx: Context): void { + const page = globalThis as Partial> + const config = Config(page[NOTIFICATIONS_CONFIG_GLOBAL] ?? {}) + ctx.effect(() => ctx.locale.register('account.notifications', { en, zh, ja, es, fr, de, ru, pt }), 'notifications: dictionaries') + let snapshot: readonly AccountNotice[] = [] + const listeners = new Set<() => void>() + const controller = createNotificationController({ + locale: ctx.locale.getSnapshot().active, + pollIntervalMs: config.notificationPollIntervalMs, + read: async (locale) => { + const result = await ctx.remote.account.getNotifications(ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification read failed') + return result.value + }, + readContent: async (id, locale) => { + const result = await ctx.remote.account.getNotificationContent(id, ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification content read failed') + return result.value + }, + reportEvent: async (id, event) => { + const result = await ctx.remote.account.reportNotificationEvent(id, event, + ctx.accountUi.clientMetadata(ctx.locale.getSnapshot().active)) + if (!result.ok) throw new Error('account notification event report failed') + return result.value + }, + publish: (notices) => { snapshot = notices; for (const listener of listeners) listener() }, + }) + const update = (state: AccountUiState, reset: boolean): void => { + const signedIn = state.view?.status === 'credential-stored' && !state.failed + if (reset || !signedIn) controller.end() + if (signedIn && reset) controller.begin() + } + ctx.effect(() => () => { controller.end() }, 'notifications: account lifetime') + ctx.on('account-ui/change', update) + ctx.on('account-ui/refresh', () => controller.refresh()) + ctx.on('locale/change', (state) => { void controller.setLocale(state.active) }) + update(ctx.accountUi.getSnapshot(), true) + const state = { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }, + } + const injected: AccountNotificationsInjected = { + hooks: { notices: state }, + shown: (id) => { controller.shown(id) }, + ctaClicked: (id) => { controller.ctaClicked(id) }, + dismiss: (id) => { controller.dismiss(id) }, + } + ctx.slots.inject('settings.launcher.notifications', () => ctx.slots.register({ + name: 'settings.launcher.notifications', locale: 'account.notifications', + inject: () => injected, + }, AccountNotifications)) +} diff --git a/packages/client/ui-account-notifications/src/client/locales.ts b/packages/client/ui-account-notifications/src/client/locales.ts new file mode 100644 index 0000000000..be4ef4fd3f --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/locales.ts @@ -0,0 +1,18 @@ +/** Close-control copy owned by account notifications; notification content is server-localized. */ +export const en = { close: 'Close' } +/** Chinese notification controls. */ +export const zh = { close: '关闭' } +/** Japanese notification controls. */ +export const ja = { close: '閉じる' } +/** Spanish notification controls. */ +export const es = { close: 'Cerrar' } +/** French notification controls. */ +export const fr = { close: 'Fermer' } +/** German notification controls. */ +export const de = { close: 'Schließen' } +/** Russian notification controls. */ +export const ru = { close: 'Закрыть' } +/** Portuguese notification controls. */ +export const pt = { close: 'Fechar' } +/** Localized notification control keys. */ +export type NotificationKey = keyof typeof en diff --git a/packages/client/ui-settings-account/src/client/notice-transition.ts b/packages/client/ui-account-notifications/src/client/notice-transition.ts similarity index 100% rename from packages/client/ui-settings-account/src/client/notice-transition.ts rename to packages/client/ui-account-notifications/src/client/notice-transition.ts diff --git a/packages/client/ui-account-notifications/src/client/notification-controller.ts b/packages/client/ui-account-notifications/src/client/notification-controller.ts new file mode 100644 index 0000000000..6c1ba0d01b --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/notification-controller.ts @@ -0,0 +1,248 @@ +/** + * Lifecycle of account notifications: one foreground card in a stack, one read result in + * force at a time, and independent display, action-click, and dismissal reports. Account activation + * and Settings entry replace the polling cycle with an immediate read. Each read + * settles before the next delay begins; the server owns unconsumed notifications. + * + * A displayed event is sent once the foreground card reports a presented frame: the card has + * a position, the document is visible, and it painted one frame. The card measures + * no cover, so a card painted under the open Settings overlay reports like any + * other. Business-action clicks report without waiting or closing the card. + * Explicit dismissal sends only a dismissed event. + * Expiry and account cleanup do not report dismissal. + * + * One lifecycle covers one signed-in session. Login-progress updates retain the + * card and active poll. Credential and connection changes end + * that lifecycle before another begins. Signing out and unloading also clear + * the cards; a later sign-in shows whatever the server offers. + * @module @deepseek-ai/dsh-client-ui-account-notifications/src/client/notification-controller + */ +import type { + AccountNotification, AccountNotificationBatch, AccountNotificationEvent, AccountNotificationId, +} from '@deepseek-ai/dsh-deepseek-account/types' + +/** Notification content currently available to the sidebar presentation. */ +export type AccountNotice = AccountNotification + +/** Collaborators and polling interval of one account notification lifecycle. */ +export interface NotificationControllerOptions { + /** Initial delay for each poll, retained until the server provides a new one. */ + readonly pollIntervalMs: number + /** UI language in effect when the controller starts. */ + readonly locale: string + /** Read the signed-in account's unconsumed notifications. @returns the batch, or null when no account is signed in. */ + read: (locale: string) => Promise + /** + * Query localized content for an existing card without changing consumption. + * @param id - notification requested by stable identity. + * @param locale - language captured for this request. + * @returns content, or null when the account changed; failures reject. + */ + readContent: (id: AccountNotificationId, locale: string) => Promise + /** + * Report one notification interaction. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @returns false when the account changed or signed out; a protocol failure rejects. + */ + reportEvent: (id: AccountNotificationId, event: AccountNotificationEvent) => Promise + /** @param notices - notices in front-to-back order; empty when none are shown. */ + publish: (notices: readonly AccountNotice[]) => void +} + +/** Commands the account plugin issues to the account notification lifecycle. */ +export interface NotificationController { + /** + * Start the signed-in lifecycle and restart polling with an immediate read. + * Re-entry retains cards; the caller ends the lifecycle on credential or connection changes. + */ + begin(): void + /** Stop the lifecycle, drop the displayed notice, and ignore late event failures. */ + end(): void + /** + * Restart polling with an immediate read, retaining cards. + * @returns after the immediate read settles, without waiting for later polls. + */ + refresh(): Promise + /** + * Refresh current cards in a new UI language, retaining order and consumption. + * @param locale - active UI language; an unchanged value issues no request. + * @returns after content requests settle; failures retain the previous content. + */ + setLocale(locale: string): Promise + /** @param id - notice whose card passed a presented frame while visible. */ + shown(id: AccountNotificationId): void + /** @param id - foreground notice whose non-dismiss action was clicked; reports without removing the card. */ + ctaClicked(id: AccountNotificationId): void + /** @param id - foreground notice the user explicitly closed; reports only a dismissed event. */ + dismiss(id: AccountNotificationId): void +} + +/** One replaceable query cycle; an obsolete request cannot publish or schedule another read. */ +interface NotificationPoll { + intervalMs: number + timer?: ReturnType +} + +/** + * @param displayUntil - server expiration timestamp. + * @param at - milliseconds since epoch. + * @returns whether the notification can no longer be shown. + */ +function expired(displayUntil: string | null, at: number): boolean { + if (displayUntil === null) return false + const expires = Date.parse(displayUntil) + // An unparsable timestamp is not evidence of expiry, so the notice still shows. + return !Number.isNaN(expires) && expires <= at +} + +/** + * Own the read, display, and interaction reporting lifecycle of account notifications. + * @param options - collaborators and timings. + * @returns the controller the account plugin drives from account and settings state. + */ +export function createNotificationController(options: NotificationControllerOptions): NotificationController { + let scope: object | undefined + let locale = options.locale + let contentGeneration = 0 + /** Notice currently published to the sidebar, including the expiration checked at display time. */ + let current: readonly AccountNotice[] = [] + let poll: NotificationPoll | undefined + /** Notifications the card on screen already reported, so one mount cannot report display twice. */ + const reported = new Set() + const setCurrent = (notices: readonly AccountNotice[]): void => { + if (notices.length === current.length && notices.every((notice, index) => { + return JSON.stringify(notice) === JSON.stringify(current[index]) + })) return + const retained = new Set(notices.map(notice => notice.id)) + for (const id of reported) if (!retained.has(id)) reported.delete(id) + current = notices + options.publish(notices) + } + /** + * Keep a presented foreground card until dismissal or expiration, refreshing + * its copy when offered again; other live candidates follow in server order. + */ + const apply = (batch: AccountNotificationBatch, preserveCopy: boolean): void => { + const notifications = batch.notifications.map((notice) => { + const previous = preserveCopy ? current.find(value => value.id === notice.id) : undefined + return previous === undefined ? notice : { ...notice, title: previous.title, body: previous.body, actions: previous.actions } + }) + const foreground = current[0] + const retained = foreground !== undefined && reported.has(foreground.id) + ? notifications.find(notice => notice.id === foreground.id) ?? foreground + : undefined + const at = Date.now() + const candidates = notifications.filter(notice => !expired(notice.displayUntil, at)) + setCurrent(retained !== undefined && !expired(retained.displayUntil, at) + ? [retained, ...candidates.filter(notice => notice.id !== retained.id)] + : candidates) + } + + /** Refresh only cards that still belong to this account and language when the replies settle. */ + async function refreshContent(): Promise { + const scopeAtCall = scope + if (scopeAtCall === undefined || current.length === 0) return + const generation = ++contentGeneration + const requestedLocale = locale + const responses = await Promise.allSettled(current.map(async notice => options.readContent(notice.id, requestedLocale))) + if (scope !== scopeAtCall || generation !== contentGeneration) return + if (responses.some(response => response.status === 'rejected')) console.error('[deepseek-account] notification content read failed') + const updates = responses.flatMap(response => response.status === 'fulfilled' && response.value !== null ? [response.value] : []) + setCurrent(current.map((notice) => { + const update = updates.find(value => value.id === notice.id) + return update == null ? notice : { ...notice, title: update.title, body: update.body, actions: update.actions } + })) + } + + /** + * Read once for the active poll, retaining cards on failure. Replacement and + * sign-out discard late replies and prevent another read from being scheduled. + * @param pollAtRead - query cycle that owns this read. + * @returns after this read settles. + */ + async function runRead(pollAtRead: NotificationPoll): Promise { + const requestedLocale = locale + let batch: AccountNotificationBatch | null + try { batch = await options.read(requestedLocale) } + catch (_error) { + if (poll !== pollAtRead) return + console.error('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + batch = null + } + if (poll !== pollAtRead) return + if (batch !== null) { + pollAtRead.intervalMs = batch.nextPollAfterSeconds * 1_000 + apply(batch, requestedLocale !== locale) + if (requestedLocale !== locale) await refreshContent() + } + if (poll !== pollAtRead) return + pollAtRead.timer = setTimeout(() => { void runRead(pollAtRead) }, pollAtRead.intervalMs) + } + + const stopPolling = (): void => { + if (poll?.timer !== undefined) clearTimeout(poll.timer) + poll = undefined + } + const restartPolling = (): Promise => { + stopPolling() + poll = { intervalMs: options.pollIntervalMs } + return runRead(poll) + } + + /** Attempt each interaction once without changing the card on failure. */ + const report = async (id: AccountNotificationId, event: AccountNotificationEvent): Promise => { + const scopeAtReport = scope + if (scopeAtReport === undefined || current[0]?.id !== id || (event === 'displayed' && reported.has(id))) return + if (event === 'displayed') reported.add(id) + try { await options.reportEvent(id, event) } + catch (_error) { + if (scope === scopeAtReport) { + console.error('[deepseek-account] notification event report failed; keeping local state without retry', { event }) + } + } + } + + const endLifecycle = (): void => { + if (scope === undefined) return + stopPolling() + scope = undefined + contentGeneration++ + reported.clear() + setCurrent([]) + } + + return { + begin() { + scope ??= {} + void restartPolling() + }, + end: endLifecycle, + refresh(): Promise { + if (scope === undefined) return Promise.resolve() + return restartPolling() + }, + async setLocale(value) { + if (value === locale) return + locale = value + contentGeneration++ + await refreshContent() + }, + shown(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'displayed') + }, + ctaClicked(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'cta_clicked') + }, + dismiss(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'dismissed') + setCurrent(current.slice(1).filter(notice => !expired(notice.displayUntil, Date.now()))) + }, + } +} diff --git a/packages/client/ui-account-notifications/src/config.ts b/packages/client/ui-account-notifications/src/config.ts new file mode 100644 index 0000000000..4a37e8392a --- /dev/null +++ b/packages/client/ui-account-notifications/src/config.ts @@ -0,0 +1,14 @@ +/** Public polling configuration shared by the notification Host and Client halves. */ +import Schema from '@deepseek-ai/schemastery' + +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +/** Validate notification polling configuration. */ +export const Config = Schema.object({ + notificationPollIntervalMs: Schema.natural().min(1).max(2_147_483_647).default(600_000), +}) +/** Bootstrap key for public notification configuration. */ +export const NOTIFICATIONS_CONFIG_GLOBAL = '__DSH_ACCOUNT_NOTIFICATIONS_CONFIG__' diff --git a/packages/client/ui-mcp-account/src/css-modules.d.ts b/packages/client/ui-account-notifications/src/css-modules.d.ts similarity index 100% rename from packages/client/ui-mcp-account/src/css-modules.d.ts rename to packages/client/ui-account-notifications/src/css-modules.d.ts diff --git a/packages/client/ui-account-notifications/src/index.ts b/packages/client/ui-account-notifications/src/index.ts new file mode 100644 index 0000000000..45b84f3cea --- /dev/null +++ b/packages/client/ui-account-notifications/src/index.ts @@ -0,0 +1,12 @@ +/** Publishes public configuration for the account notification client plugin. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from './config.ts' +export { Config } from './config.ts' + +/** @param ctx - Host page bootstrap collector. @param config - validated notification configuration. */ +export function apply(ctx: Context, config: Config): void { + ctx.on('webserver/index-inject', (table) => { + table.push({ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: config }) + }) +} diff --git a/packages/client/ui-account-notifications/tests/apply.client.spec.ts b/packages/client/ui-account-notifications/tests/apply.client.spec.ts new file mode 100644 index 0000000000..ba0b42bfd2 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/apply.client.spec.ts @@ -0,0 +1,350 @@ +// @vitest-environment jsdom +/** Notification integration shares the account plugin's single state stream. */ +import { afterEach, beforeEach, expect, onTestFinished, vi } from 'vitest' +import { ok } from '@deepseek-ai/dsh-remote-mock' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' +import type { AccountNotificationBatch, AccountNotificationId, AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import type { AccountNotificationsInjected } from '../src/client/AccountNotifications.tsx' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' +import { notification } from './notification-fixture.ts' + +const it = createClientTest({ roster: webApp }) +const SELF = '@deepseek-ai/dsh-client-ui-settings-account' +const view: AccountView = { status: 'signed-out', attempt: null, + links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } +const stored: AccountView = { ...view, status: 'credential-stored' } +function bonus(orderId: string, message = 'Awarded 5.00'): AccountNotificationBatch { + return { nextPollAfterSeconds: 300, notifications: [notification(orderId, { body: message, displayUntil: '2099-01-01T00:00:00Z' })] } +} +function operations(c: TestClient): AccountSectionInjected { + const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!() + return injected as AccountSectionInjected +} +function notificationOperations(c: TestClient): AccountNotificationsInjected { + const injected: object = c.ctx.slots.entries('settings.launcher.notifications')[0]!.inject!() + return injected as AccountNotificationsInjected +} +beforeEach(() => { vi.stubEnv('DSH_CLIENT_VERSION', '0.0.0-test') }) +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.restoreAllMocks() }) + +it('reads the unnotified bonus in the active locale and acknowledges only after the card renders', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' })) + // A successful read is not a display, so nothing may be acknowledged yet. + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + notificationOperations(c).shown(orderId as AccountNotificationId) + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'displayed', expect.objectContaining({ locale: 'en' })) + }) + notificationOperations(c).ctaClicked(orderId as AccountNotificationId) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith( + orderId, 'cta_clicked', expect.objectContaining({ locale: 'en' })) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(orderId) + notificationOperations(c).dismiss(orderId as AccountNotificationId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'dismissed', expect.objectContaining({ locale: 'en' })) + }) +}, 60_000) + +it('starts one notification poll across the credential commit and login-success frames', async ({ start }) => { + const c = await start() + c.mock.remote.session.initializeDefaultModel.mockResolvedValue(ok(undefined)) + const reads = c.mock.remote.account.getNotifications + const id = 'one-login' as SignInAttemptId + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'committing' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) +}, 60_000) + +for (const outcome of ['null', 'failure'] as const) it(`queries a replacement credential without adopting the old ${outcome} reply`, async ({ start }) => { + const c = await start() + const previous = Promise.withResolvers>>() + const reads = c.mock.remote.account.getNotifications + reads.mockReturnValueOnce(previous.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + reads.mockResolvedValueOnce(ok(bonus('replacement-notice'))) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(2) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') + if (outcome === 'null') previous.resolve(ok(null)) + else previous.reject(new Error('obsolete credential')) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') +}, 60_000) + +it('clears notification cards and ignores old event failures when credentials change despite a failed replacement list', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + const event = Promise.withResolvers>>() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockReturnValueOnce(event.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(id) + await vi.advanceTimersByTimeAsync(0) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + c.mock.remote.account.getNotifications.mockRejectedValueOnce(new Error('replacement offline')) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + event.reject(new Error('old request failed')) + await vi.advanceTimersByTimeAsync(3_000) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + expect(log).toHaveBeenCalledWith('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice without retrying its event across repeated signed-in frames', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(orderId) + await vi.advanceTimersByTimeAsync(0) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + await vi.advanceTimersByTimeAsync(60_000) + notificationOperations(c).shown(orderId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith( + '[deepseek-account] notification event report failed; keeping local state without retry', { event: 'displayed' }) + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice absent when the bonus read is refused, then shows the next read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValueOnce({ + ok: false, error: new RemoteError('gateway/internal', 'offline', {}), + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + await actions.refreshAccount() + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) +}, 60_000) + +it('drops the previous account notice and stops reading after sign-out', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000001'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + // Signing out ends the lifecycle, so no further read follows. + const reads = c.mock.remote.account.getNotifications.mock.calls.length + await new Promise((resolve) => { setTimeout(resolve, 20) }) + expect(c.mock.remote.account.getNotifications.mock.calls.length).toBe(reads) +}, 60_000) + +it('refreshes balances and notifications immediately on Settings entry', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const balance: AccountDetails['balance'] = { + status: 'ready', value: [{ currency: 'CNY', balance: '12.34' }], bonusWallets: [{ currency: 'CNY', balance: '5.00' }], + } + c.mock.remote.account.getBalance.mockResolvedValue(ok(balance)) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + // Account activation starts with an immediate read. + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + // Signing in already read the wallet once through the details refresh. + const balances = c.mock.remote.account.getBalance.mock.calls.length + await actions.refreshAccount() + expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(balances + 1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + // The bonus read carries the active UI language. + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'en' })) +}, 60_000) + +it('replaces polling on startup, sign-in and Settings entry and stops on sign-out or unload', async ({ start }) => { + vi.stubGlobal(NOTIFICATIONS_CONFIG_GLOBAL, { notificationPollIntervalMs: 1_000 }) + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + try { + await c.reload(SELF) + await c.flush() + const actions = operations(c) + const reads = c.mock.remote.account.getNotifications + reads.mockClear() + // Startup receives the stored account in its initial stream snapshot. + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(500) + await actions.refreshAccount() + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(4) + await c.unload(SELF) + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(4) + } finally { vi.useRealTimers() } +}, 60_000) + +it('publishes a failed balance from a Settings entry without dropping the bonus read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + await actions.refreshAccount() + expect(actions.hooks.account.getSnapshot().details?.balance).toEqual({ status: 'failed' }) + // The bonus read still ran: a failed wallet read does not cancel it. + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) +}, 60_000) + +it('refreshes consumed notification content on a locale change without reading the unconsumed list again', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.remote.account.getNotificationContent.mockResolvedValue(ok(notification(id, { title: '公告', body: '新的中文内容' }))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(id) }) + notificationOperations(c).shown(id as AccountNotificationId) + await vi.waitFor(() => { expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) }) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('新的中文内容') }) + expect(c.mock.remote.account.getNotificationContent).toHaveBeenCalledWith( id, expect.objectContaining({ locale: 'zh' })) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) +}, 60_000) + +it('retains notification content when the localization RPC is refused', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + const output = vi.spyOn(console, 'error').mockImplementation(() => {}) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.getNotificationContent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(output).toHaveBeenCalledWith('[deepseek-account] notification content read failed') }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') +}, 60_000) + +it('clears notifications and stops polling when the account carrier fails', async ({ start }) => { + const c = await start() + const open = c.ctx.remote.$stream.bind(c.ctx.remote) + let fail: (() => void) | undefined + vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { + if (options.name === 'account') fail = () => { options.carrierFailed?.(new Error('connection lost')) } + return open(options) + }) + await c.reload(SELF) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000000'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toHaveLength(1) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + vi.useFakeTimers() + try { + fail?.() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + await vi.advanceTimersByTimeAsync(600_000) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + } finally { vi.useRealTimers() } +}, 60_000) + +it('reloads notifications without opening another account stream', async ({ start }) => { + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('retained'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + const stream = vi.spyOn(c.ctx.remote, '$stream') + const before = c.mock.remote.account.getNotifications.mock.calls.length + await c.reload('@deepseek-ai/dsh-client-ui-account-notifications') + await c.flush() + expect(stream).not.toHaveBeenCalled() + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(before + 1) + expect(notificationOperations(c).hooks.notices.getSnapshot()[0]?.id).toBe('retained') +}) + +it('publishes notification changes through one stable source and releases its subscribers', async ({ start }) => { + const c = await start() + const source = notificationOperations(c).hooks.notices + expect(notificationOperations(c).hooks.notices).toBe(source) + const listener = vi.fn() + const dispose = source.subscribe(listener) + onTestFinished(dispose) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('first'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(source.getSnapshot()[0]?.id).toBe('first') + expect(listener).toHaveBeenCalled() + dispose() + listener.mockClear() + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + expect(source.getSnapshot()).toEqual([]) + expect(listener).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/config.client.spec.ts b/packages/client/ui-account-notifications/tests/config.client.spec.ts new file mode 100644 index 0000000000..7c479ec7f4 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/config.client.spec.ts @@ -0,0 +1,27 @@ +/** Notification configuration reaches the client without account secrets. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished } from 'vitest' +import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' +import { apply, Config } from '../src/index.ts' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' + +it('publishes polling configuration and removes the publisher on disposal', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin({ apply, Config }, { notificationPollIntervalMs: 250 }) + const table: IndexInjection[] = [] + const peer = { principal: { kind: 'owner' } } as Parameters[1] + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([{ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: { notificationPollIntervalMs: 250 } }]) + await ctx.fiber.dispose() + table.length = 0 + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([]) +}) + +it('defaults to ten minutes and rejects intervals outside browser timer limits', () => { + expect(Config({}).notificationPollIntervalMs).toBe(600_000) + for (const notificationPollIntervalMs of [0, -1, 1.5, 2_147_483_648]) { + expect(() => Config({ notificationPollIntervalMs })).toThrow() + } +}) diff --git a/packages/client/ui-settings-account/tests/expected/notice.txt b/packages/client/ui-account-notifications/tests/expected/notice.txt similarity index 100% rename from packages/client/ui-settings-account/tests/expected/notice.txt rename to packages/client/ui-account-notifications/tests/expected/notice.txt diff --git a/packages/client/ui-settings-account/tests/notice-transition.client.spec.ts b/packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts similarity index 100% rename from packages/client/ui-settings-account/tests/notice-transition.client.spec.ts rename to packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts diff --git a/packages/client/ui-settings-account/tests/notice.client.spec.tsx b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx similarity index 50% rename from packages/client/ui-settings-account/tests/notice.client.spec.tsx rename to packages/client/ui-account-notifications/tests/notice.client.spec.tsx index 5fbbfc3994..6491f93619 100644 --- a/packages/client/ui-settings-account/tests/notice.client.spec.tsx +++ b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx @@ -1,17 +1,38 @@ // @vitest-environment jsdom /** * The bonus notice card reports display only when the server's copy is - * actually on screen: it needs an anchor position, a visible document, and one - * presented frame. Closing counts as seen because the user acted on it. + * actually on screen: it needs a visible sidebar and document, and one presented + * frame. Closing counts as seen because the user acted on it. */ -import { createRef } from 'react' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { act } from 'react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AccountBonusOrderId } from '@deepseek-ai/dsh-deepseek-account/types' -import { AccountNoticeStack } from '../src/client/AccountNotice.tsx' +import { AccountNoticeStack } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' const disconnect = vi.fn() +const observers: VisibilityObserver[] = [] +let intersecting = true + +class VisibilityObserver implements IntersectionObserver { + readonly root = null + readonly rootMargin = '0px' + readonly scrollMargin = '0px' + readonly thresholds = [0] + private target!: Element + constructor(private readonly callback: IntersectionObserverCallback) { observers.push(this) } + observe(target: Element): void { this.target = target; this.notify(intersecting) } + unobserve(): void {} + disconnect = disconnect + takeRecords(): IntersectionObserverEntry[] { return [] } + notify(visible: boolean): void { + const rect = new DOMRect(0, 0, 260, 100) + this.callback([{ + target: this.target, isIntersecting: visible, intersectionRatio: visible ? 1 : 0, + time: 0, boundingClientRect: rect, intersectionRect: rect, rootBounds: null, + }], this) + } +} let visibility: 'visible' | 'hidden' = 'visible' /** Frame callbacks the card scheduled, in order. */ let frames: (() => void)[] = [] @@ -23,7 +44,10 @@ function setVisibility(value: 'visible' | 'hidden'): void { beforeEach(() => { visibility = 'visible' + intersecting = true + observers.length = 0 frames = [] + vi.stubGlobal('IntersectionObserver', VisibilityObserver) Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }) // jsdom drives requestAnimationFrame from its own clock, so the test presents frames explicitly. vi.stubGlobal('requestAnimationFrame', (callback: () => void) => { frames.push(callback); return frames.length }) @@ -32,15 +56,13 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); vi.restoreAllMocks(); disconnect.mockClear() }) function mount(id: string, onShown = vi.fn(), onDismiss = vi.fn()) { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() + const onCtaClicked = vi.fn() const view = render(<> -
- + {}} + notices={[notification(id, { displayUntil: '2099-01-01T00:00:00Z' })]} + onShown={onShown} onCtaClicked={onCtaClicked} onDismiss={onDismiss} /> ) - return { view, onShown, onDismiss } + return { view, onShown, onCtaClicked, onDismiss } } /** @@ -89,12 +111,13 @@ it('waits for another visible frame when the document hides before the follow-up expect(onShown).toHaveBeenCalledExactlyOnceWith('order-1') }) -it('reports dismissal so closing the card counts as seen', async () => { - const { onShown, onDismiss } = mount('order-1') +it('reports dismissal without a CTA click when the close icon is clicked', async () => { + const { onShown, onCtaClicked, onDismiss } = mount('order-1') await presentFrames() fireEvent.click(screen.getByRole('button', { name: 'Close' })) expect(onDismiss).toHaveBeenCalledWith('order-1') expect(onShown).toHaveBeenCalledOnce() + expect(onCtaClicked).not.toHaveBeenCalled() }) it('reports neither display nor dismissal when unmounted before its frame', async () => { @@ -140,17 +163,14 @@ it.each([true, false])('cancels the presentation task when the card unmounts fir }) it('keeps back cards mounted but inaccessible and reports them only after promotion', async () => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() const onShown = vi.fn() const onDismiss = vi.fn() - const notices = ['first', 'second', 'third'].map(id => ({ - orderId: id as AccountBonusOrderId, title: id, message: `${id} copy`, expiresAt: '', + const notices = ['first', 'second', 'third'].map(id => notification(id, { + title: id, body: `${id} copy`, actions: [{ label: 'Dismiss', style: 'secondary', target: { type: 'dismiss' } }], })) const tree = (remaining: typeof notices) => <> -
- + {}} + onShown={onShown} onCtaClicked={vi.fn()} onDismiss={onDismiss} /> const view = render(tree(notices)) const second = screen.getByText('second copy').closest('aside') @@ -170,12 +190,84 @@ it('keeps back cards mounted but inaccessible and reports them only after promot expect(onShown).toHaveBeenCalledTimes(2) }) -it('does not acknowledge a notice before an anchor is mounted', async () => { - const onShown = vi.fn() - render(()} title="News" closeLabel="Close" - notices={[{ orderId: 'notice' as AccountBonusOrderId, message: 'News', expiresAt: '' }]} - onShown={onShown} onDismiss={vi.fn()} />) +it('keeps sidebar cards mounted without reporting until they enter the viewport', async () => { + intersecting = false + const { view, onShown, onDismiss } = mount('notice') + const card = view.container.querySelector('aside') + expect(card).not.toBeNull() + expect(view.container.contains(screen.getByRole('status'))).toBe(true) await presentFrames() expect(onShown).not.toHaveBeenCalled() - expect(screen.queryByRole('status')).toBeNull() + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + act(() => { observers[0]!.notify(false); observers[0]!.notify(true) }) + await presentFrames() + expect(view.container.querySelector('aside')).toBe(card) + expect(onShown).toHaveBeenCalledOnce() + expect(onDismiss).not.toHaveBeenCalled() +}) + +it.each(['hidden', 'inert'])('does not report when its sidebar becomes %s before the presentation task', async (attribute) => { + const { view, onShown } = mount('notice') + await presentFrames(() => { view.container.setAttribute(attribute, '') }) + expect(onShown).not.toHaveBeenCalled() + view.container.removeAttribute(attribute) + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') +}) + +it('does not report when the card leaves the viewport before the presentation task', async () => { + const { onShown } = mount('notice') + await presentFrames(() => { observers[0]!.notify(false) }) + expect(onShown).not.toHaveBeenCalled() +}) + +it.each(['primary', 'secondary'] as const)('reports non-dismiss %s actions and keeps focus while localized content changes', async (style) => { + const onShown = vi.fn() + const onDismiss = vi.fn() + const onOpenAccount = vi.fn() + const onCtaClicked = vi.fn() + const content = (chinese: boolean) => notification('notice', { + title: chinese ? '产品公告' : 'Product news', body: chinese ? '新功能已上线' : 'New features', + actions: [ + { label: chinese ? '查看余额' : 'View balance', style, target: { type: 'app_route', name: 'account' } }, + { label: chinese ? '知道了' : 'Got it', style, target: { type: 'dismiss' } }, + ], + }) + const tree = (chinese: boolean) => <> + + + const view = render(tree(false)) + await presentFrames() + const button = screen.getByRole('button', { name: 'View balance' }) + button.focus() + fireEvent.click(button) + expect(onOpenAccount).toHaveBeenCalledOnce() + expect(onCtaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(onDismiss).not.toHaveBeenCalled() + view.rerender(tree(true)) + expect(screen.getByRole('button', { name: '查看余额' })).toBe(button) + expect(document.activeElement).toBe(button) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + fireEvent.click(screen.getByRole('button', { name: '知道了' })) + expect(onDismiss).toHaveBeenCalledExactlyOnceWith('notice') + expect(onCtaClicked).toHaveBeenCalledOnce() +}) + +it('renders separate buttons for repeated action targets', () => { + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + render(<> + {}} + onShown={vi.fn()} onCtaClicked={vi.fn()} onDismiss={vi.fn()} notices={[notification('notice', { actions: [ + { label: 'Got it', style: 'primary', target: { type: 'dismiss' } }, + { label: 'Later', style: 'secondary', target: { type: 'dismiss' } }, + ] })]} /> + ) + expect(screen.getByRole('button', { name: 'Got it' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Later' })).toBeTruthy() + expect(output).not.toHaveBeenCalled() }) diff --git a/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts new file mode 100644 index 0000000000..211f8e58cd --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts @@ -0,0 +1,822 @@ +// @vitest-environment jsdom +/** + * Notification lifecycle: account activation and Settings entry replace polling + * with an immediate query. Display reports follow a presented frame. + * Each event is attempted once; nothing + * about a notice survives sign-out or unload. + */ +import { afterEach, expect, it, vi } from 'vitest' +import type { AccountNotificationBatch, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' +import { createNotificationController, type AccountNotice, type NotificationController } from '../src/client/notification-controller.ts' +import { notification } from './notification-fixture.ts' + +const TIMING = { pollIntervalMs: 600_000 } +const controllers = new Set() + +/** + * @param id - notification identifier. + * @param displayUntil - server expiration. + * @returns one unconsumed notification as the Host projects it. + */ +function batch(id: string, displayUntil: string | null = '2099-01-01T00:00:00Z'): AccountNotificationBatch { + return { + nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: [notification(id, { displayUntil })], + } +} + +function setup() { + const read = vi.fn(async (): Promise => null) + const readContent = vi.fn(async (): Promise => null) + const displayed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const dismissed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const clicked = vi.fn(async (_id: AccountNotificationId): Promise => true) + const stacks: (readonly AccountNotice[])[] = [] + const published: (AccountNotice | null)[] = [] + const controller = createNotificationController({ + ...TIMING, locale: 'en', read, readContent, + reportEvent: (id, event) => ({ displayed: displayed, cta_clicked: clicked, dismissed })[event](id), + publish: (notices) => { stacks.push(notices); published.push(notices[0] ?? null) }, + }) + controllers.add(controller) + /** @returns the most recently published notice. */ + const latest = (): AccountNotice | null | undefined => published.at(-1) + return { controller, read, readContent, displayed, clicked, dismissed, published, latest, stacks } +} + +afterEach(() => { + for (const controller of controllers) controller.end() + controllers.clear() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it('reads immediately and starts the next delay only after the current request settles', async () => { + vi.useFakeTimers() + const { controller, read } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + controller.begin() + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 3) + expect(read).toHaveBeenCalledTimes(1) + finish(null) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + controller.end() +}) + +it.each(['begin', 'refresh'] as const)('restarts polling immediately on %s and cancels the previous delay', async (trigger) => { + vi.useFakeTimers() + const { controller, read } = setup() + controller.begin() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + if (trigger === 'begin') controller.begin() + else await controller.refresh() + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + controller.end() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('discards a superseded request without publishing or resuming its poll', async () => { + vi.useFakeTimers() + const { controller, read, latest } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + read.mockResolvedValue(batch('new')) + controller.begin() + await controller.refresh() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + finish(batch('old')) + await vi.advanceTimersByTimeAsync(0) + expect(latest()?.id).toBe('new') + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('does not report or reschedule an obsolete request failure', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + let reject!: (error: Error) => void + read.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail })) + controller.begin() + controller.end() + reject(new Error('offline')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(1) + expect(log).not.toHaveBeenCalled() +}) + +it('does not resume polling after sign-out while a list reply is refreshing language content', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + const content = Promise.withResolvers() + read.mockReturnValueOnce(response.promise) + readContent.mockReturnValueOnce(content.promise) + controller.begin() + await controller.setLocale('zh') + response.resolve(batch('first')) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledWith('first', 'zh') + controller.end() + content.resolve(notification('first')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(latest()).toBeNull() + expect(read).toHaveBeenCalledOnce() +}) + +it('retains the shown card on failure and polls again after the configured delay', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read, latest, displayed } = setup() + read.mockResolvedValueOnce(batch('first')).mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue(batch('second')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(latest()?.id).toBe('first') + expect(log).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(read).toHaveBeenCalledTimes(3) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledOnce() +}) + +it('uses each server delay in seconds, retains it after failure, and resets it when polling restarts', async () => { + vi.useFakeTimers() + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + read.mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 2 }) + .mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 5 }) + .mockRejectedValueOnce(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(1_999) + expect(read).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(4) + await controller.refresh() + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(6) +}) + +it('publishes the server copy for the first unconsumed notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + controller.end() +}) + +it('reports display only after a presented frame and keeps the card until it is closed', async () => { + const { controller, read, displayed, published, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + expect(displayed).not.toHaveBeenCalled() + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + // A refresh still offering the notification must not republish the open card. + const publishedBefore = published.length + await controller.refresh() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(2) }) + expect(published.length).toBe(publishedBefore) + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + expect(latest()).toBeNull() + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it.each(['aborted', 'null'] as const)("does not adopt the replaced credential's in-flight read when it answers %s", async (answer) => { + vi.useFakeTimers() + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockRejectedValue(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + // Account A's next signed-in frame starts a read the Host abandons when the + // credential is replaced by B. B's frame must not inherit it: A's answer names + // the replaced account, so adopting it would leave B with no read of its own. + const abandoned = Promise.withResolvers() + read.mockReturnValueOnce(abandoned.promise) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + expect(read).toHaveBeenCalledTimes(3) + expect(latest()).toMatchObject({ id: 'notice-2' }) + if (answer === 'aborted') abandoned.reject(new Error('aborted')) + else abandoned.resolve(null) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + // The abandoned answer cannot restore the previous account's card. + expect(latest()).toMatchObject({ id: 'notice-2' }) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('refreshes the copy of the notification already on screen when a read offers it again', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + // The same notification arrives with new copy: its card updates in place instead of being replaced. + read.mockResolvedValue({ ...batch('notice-1'), notifications: [{ ...batch('notice-1').notifications[0]!, title: 'Updated title', body: 'Updated copy' }] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1', title: 'Updated title', body: 'Updated copy' }) + controller.end() +}) + +it('withdraws a card the user never saw when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // The card never reported a presented frame, so an empty read withdraws it. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it.each(['omitted', 'reordered'] as const)('keeps the displayed card in front when the next read leaves it %s', async (placement) => { + vi.useFakeTimers() + const { controller, read, displayed, stacks } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const next = ['second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: placement === 'reordered' ? [...next, ...batch('first', null).notifications] : next }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['first', 'second', 'third']) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second', 'third']) + controller.shown('second' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(2) + expect(displayed).toHaveBeenLastCalledWith('second') + } finally { + controller.end() + } +}) + +it.each(['elapsed', 'updated'] as const)('removes a displayed card whose expiration %s before the next read', async (expiration) => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-10-27T00:00:00Z')) + const { controller, read, stacks } = setup() + try { + read.mockResolvedValue(batch('first', '2026-10-28T00:00:00Z')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + if (expiration === 'elapsed') vi.setSystemTime(new Date('2026-10-28T00:00:00Z')) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...expiration === 'updated' ? batch('first', '2026-10-27T00:00:00Z').notifications : [], + ...batch('second', null).notifications, + ] }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second']) + } finally { + controller.end() + } +}) + +it('ignores a dismissal that names a notification the card does not show', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.dismiss('notice-2' as AccountNotificationId) + // The other notification's dismissal neither withdraws this card nor reports its display. + expect(latest()).toMatchObject({ id: 'notice-1' }) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays a notification offered again after a previous sign-in reported it', async () => { + const first = setup() + first.read.mockResolvedValue(batch('notice-1')) + first.controller.begin() + await vi.waitFor(() => { expect(first.latest()).toMatchObject({ id: 'notice-1' }) }) + first.controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(first.displayed).toHaveBeenCalledTimes(1) }) + first.controller.end() + // Nothing is remembered, so the same notification the server still offers displays again. + const second = setup() + second.read.mockResolvedValue(batch('notice-1')) + second.controller.begin() + await vi.waitFor(() => { expect(second.latest()).toMatchObject({ id: 'notice-1' }) }) + second.controller.end() +}) + +it('discards the previous account card when a credential is replaced without a signed-out frame', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockResolvedValue(false) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledOnce() }) + // The credential is replaced in place: another signed-in frame arrives, the read + // names the other account, and no signed-out frame ever describes the switch. + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('reports each new display of a notification offered again after dismissal', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + // Closing the card withdraws it; the next read of the same notification is a new card. + controller.dismiss('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + await controller.refresh() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(2) }) + controller.end() +}) + +it('keeps the visible card when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // A card the user has already seen keeps its place. + controller.shown('notice-1' as AccountNotificationId) + // A Settings entry whose read returns nothing must not pull the card out from under the user. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it('withdraws the displayed card when the signed-in account changes', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('never reports display after the plugin unloads', async () => { + vi.useFakeTimers() + const { controller, read, displayed } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(displayed).not.toHaveBeenCalled() +}) + +it('suppresses a notification that expired before its first presented frame', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1', '2000-01-01T00:00:00Z')) + controller.begin() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(1) }) + expect(latest()).toBeUndefined() + controller.end() +}) + +it('does not record a display when the award expired before the card could render', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + // The card refuses to render an expired award, so no display is reported. + controller.shown('notice-1' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays and reports a notice without expiration', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', displayUntil: null }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + controller.end() +}) + +it('publishes every live notice and reports display only for the foreground card', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + const notifications = ['first', 'second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toEqual(notifications) }) + controller.shown('second' as AccountNotificationId) + controller.dismiss('third' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + expect(stacks.at(-1)).toEqual(notifications) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledExactlyOnceWith('first') }) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(1)) + expect(displayed).toHaveBeenCalledTimes(1) + controller.shown('second' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenLastCalledWith('second') }) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(2)) + controller.dismiss('third' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed.mock.calls).toEqual([['first'], ['second'], ['third']]) + controller.end() +}) + +it('drops queued notices that expire before promotion without reporting display', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', null).notifications, + ...batch('expired', '2099-01-01T00:00:00Z').notifications, + ...batch('last', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(3) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['last']) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + controller.end() +}) + +it('publishes a title-only refresh without reporting the same display twice', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()?.id).toBe('first') }) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: batch('first', null).notifications.map(notice => ({ ...notice, title: 'Updated title' })) }) + await controller.refresh() + expect(latest()?.title).toBe('Updated title') + controller.shown('first' as AccountNotificationId) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('does not read or report display outside an active account lifecycle', async () => { + const { controller, read, displayed } = setup() + await controller.refresh() + expect(read).not.toHaveBeenCalled() + expect(displayed).not.toHaveBeenCalled() +}) + +it('closes the visible notice when the preceding card expires before its display callback', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', '2099-01-01T00:00:00Z').notifications, + ...batch('second', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(2) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('second') + controller.end() +}) + +it('refreshes a consumed card in place on language changes without another list or display report', async () => { + vi.useFakeTimers() + const { controller, read, readContent, displayed, latest } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const actions = [{ label: '知道了', style: 'secondary', target: { type: 'dismiss' } }] as const + readContent.mockResolvedValue(notification('first', { title: '通知', body: '新的中文内容', actions })) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()).toMatchObject({ id: 'first', title: '通知', body: '新的中文内容', actions }) + expect(read).toHaveBeenCalledTimes(1) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledTimes(1) + } finally { controller.end() } +}) + +it('ignores an earlier language response after a later language change', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const first = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(first.promise) + const changing = controller.setLocale('zh') + readContent.mockResolvedValueOnce(notification('first', { body: 'Latest English content' })) + await controller.setLocale('en') + first.resolve(notification('first', { body: '过时的中文内容' })) + await changing + expect(latest()?.body).toBe('Latest English content') + } finally { first.resolve(null); controller.end() } +}) + +it.each(['dismiss', 'sign-out', 'account-change'] as const)('does not restore content after %s', async (change) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(response.promise) + const changing = controller.setLocale('zh') + if (change === 'dismiss') controller.dismiss('first' as AccountNotificationId) + else if (change === 'sign-out') controller.end() + else { + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await Promise.resolve() + } + response.resolve(notification('first', { body: '迟到的内容' })) + await changing + expect(latest()?.id ?? null).toBe(change === 'account-change' ? 'second' : null) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['failure', 'absent'] as const)('retains the current content when localization returns %s', async (outcome) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (outcome === 'failure') readContent.mockRejectedValueOnce(new Error('private-detail')) + await controller.setLocale('zh') + expect(latest()?.body).toBe('Server copy 5.00') + expect(JSON.stringify(output.mock.calls)).not.toContain('private-detail') + expect(output).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + } finally { controller.end() } +}) + +it('localizes notifications returned by a list request started before the language changed', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockReturnValueOnce(response.promise) + controller.begin() + await controller.setLocale('zh') + expect(readContent).not.toHaveBeenCalled() + readContent.mockResolvedValueOnce(notification('first', { body: '当前语言内容' })) + response.resolve(batch('first', null)) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()?.body).toBe('当前语言内容') + } finally { response.resolve(null); controller.end() } +}) + +it('keeps localized copy while an older list response refreshes other notification fields', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest, published } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValueOnce(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + read.mockReturnValueOnce(response.promise) + const refreshing = controller.refresh() + readContent.mockResolvedValue(notification('first', { body: '新的中文内容' })) + await controller.setLocale('zh') + const count = published.length + response.resolve(batch('first', null)) + await refreshing + expect(latest()?.body).toBe('新的中文内容') + expect(published.slice(count).every(notice => notice?.body === '新的中文内容')).toBe(true) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['shown', 'before-frame'] as const)('reports an explicit dismissal once when closed %s', async (presentation) => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (presentation === 'shown') { + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() + } + controller.dismiss('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(presentation === 'shown' ? 1 : 0) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') +}) + +it.each(['expiry', 'account-change', 'sign-out', 'unload'] as const)('does not report dismissal on %s cleanup or from a stale callback', async (cleanup) => { + vi.useFakeTimers() + const { controller, read, dismissed } = setup() + const deadline = new Date(Date.now() + 100).toISOString() + read.mockResolvedValue(batch('first', cleanup === 'expiry' ? deadline : null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + if (cleanup === 'expiry') await vi.advanceTimersByTimeAsync(100) + else if (cleanup === 'account-change') { + controller.end() + read.mockResolvedValue(batch('second')) + controller.begin() + await Promise.resolve() + } else controller.end() + controller.dismiss('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('attempts each display and dismissal once after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + for (const report of [displayed, dismissed]) { + if (outcome === 'failure') report.mockRejectedValue(new Error('private-detail')) + else report.mockResolvedValue(outcome === 'success') + } + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + controller.begin() + await controller.refresh() + controller.shown('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(60_000) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 2 : 0) + expect(JSON.stringify(log.mock.calls)).not.toContain('private-detail') +}) + +it('reports the next card and dismissal without waiting for an earlier display report', async () => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue({ ...batch('first', null), notifications: [notification('first'), notification('second')] }) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + controller.shown('second' as AccountNotificationId) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + } finally { + pending.resolve(true) + await pending.promise + controller.end() + } +}) + +it.each(['success', 'failure'] as const)('ignores a late event %s after changing credentials', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('second' as AccountNotificationId) + if (outcome === 'success') pending.resolve(true) + else pending.reject(new Error('obsolete')) + await vi.advanceTimersByTimeAsync(60_000) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(log).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('reports a CTA click once without dismissing or retrying after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, clicked, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + if (outcome === 'failure') clicked.mockRejectedValue(new Error('offline')) + else clicked.mockResolvedValue(outcome === 'success') + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(60_000) + expect(clicked).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + controller.ctaClicked('first' as AccountNotificationId) + expect(clicked).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(0) +}) + +it('keeps dismissal available while a CTA-click report is pending', async () => { + vi.useFakeTimers() + const { controller, read, clicked, dismissed, latest } = setup() + const pending = Promise.withResolvers() + clicked.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + controller.dismiss('first' as AccountNotificationId) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(latest()).toBeNull() + } finally { + pending.resolve(true) + await pending.promise + } +}) + +it.each(['back-card', 'expired', 'signed-out'] as const)('ignores a CTA click from a %s notification', async (state) => { + vi.useFakeTimers() + const { controller, read, clicked } = setup() + read.mockResolvedValue({ ...batch('first', null), notifications: [ + notification('first', { displayUntil: '2099-01-01T00:00:00Z' }), notification('second'), + ] }) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (state === 'signed-out') controller.end() + else if (state === 'expired') vi.setSystemTime(new Date('2100-01-01T00:00:00Z')) + controller.ctaClicked((state === 'back-card' ? 'second' : 'first') as AccountNotificationId) + expect(clicked).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/notification-fixture.ts b/packages/client/ui-account-notifications/tests/notification-fixture.ts new file mode 100644 index 0000000000..d60b0da8dc --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-fixture.ts @@ -0,0 +1,15 @@ +/** Complete account notification values shared by presentation tests. */ +import type { AccountNotification, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' + +/** + * Create one notification without wire parsing or account lifecycle effects. + * @param id - stable notification identity. + * @param fields - scenario-specific notification fields. + * @returns localized display content with no actions or deadline unless supplied. + */ +export function notification(id: string, fields: Partial> = {}): AccountNotification { + return { + id: id as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Bonus credited', body: 'Server copy 5.00', actions: [], ...fields, + } +} diff --git a/packages/client/ui-account-notifications/tests/view.client.spec.tsx b/packages/client/ui-account-notifications/tests/view.client.spec.tsx new file mode 100644 index 0000000000..ff9d91438c --- /dev/null +++ b/packages/client/ui-account-notifications/tests/view.client.spec.tsx @@ -0,0 +1,36 @@ +// @vitest-environment jsdom +/** The menu extension preserves notifications while onboarding hides their presentation. */ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' +import { AccountNotifications, type AccountNotificationsProps } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' + +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) + +it('shows retained cards inside the menu and opens account settings without dismissing them', () => { + vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} }) + const notices = [notification('notice', { actions: [ + { label: 'View account', style: 'primary', target: { type: 'app_route', name: 'account' } }, + ] })] + const openAccount = vi.fn() + const dismiss = vi.fn() + const ctaClicked = vi.fn() + const props: AccountNotificationsProps = { + ...({} as GlobalStandardProps), active: false, openAccount, ctaClicked, dismiss, shown: vi.fn(), + useNotices: select => select(notices), t: () => 'Close', + } + const view = render() + expect(screen.queryByRole('status')).toBeNull() + view.rerender() + fireEvent.click(screen.getByRole('button', { name: 'View account' })) + expect(openAccount).toHaveBeenCalledOnce() + expect(ctaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(screen.getByRole('status')).toBeTruthy() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.queryByRole('status')).toBeNull() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.getByRole('button', { name: 'View account' })).toBeTruthy() +}) diff --git a/packages/client/ui-account-notifications/tsconfig.json b/packages/client/ui-account-notifications/tsconfig.json new file mode 100644 index 0000000000..3d18f2dc37 --- /dev/null +++ b/packages/client/ui-account-notifications/tsconfig.json @@ -0,0 +1,42 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-settings-account" + }, + { + "path": "../../credentials/deepseek-account" + }, + { + "path": "../../host/webserver" + }, + { + "path": "../ui-renderer" + } + ] +} diff --git a/packages/client/ui-account-notifications/tsdown.config.ts b/packages/client/ui-account-notifications/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-account-notifications/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index d92283aad2..d193002324 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -11,6 +11,7 @@ export const guideEn = { guideStandardExplanation: [ '### How it works', 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, and context compaction.', + 'For questions about DSH and plugin or preset work you request, the dsh-doc skill guides the agent to the installed documentation and source. Its instructions load only when requested or relevant; loading it does not change files, tools, or the profile.', '### When to choose it', 'Start here for everyday coding, file work, and research. Standard mode can also write scripts and process files in batches. PTC changes how tool calls are organized; it is not required for batch tasks.', ].join('\n\n'), @@ -54,7 +55,7 @@ export const guideEn = { guideCordisIntro: 'Choose Creator mode for a new task. Describe the capability you want, where it should appear, and how you will verify it.', guideCordisExplanation: [ '### What you can create', - 'Creator mode includes the standard task tools plus runtime inspection and guidance for authoring Cordis plugins and agent presets. It can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', + 'Creator mode includes the standard task tools and adds runtime inspection. Standard and Creator share the dsh-doc guidance for plugin and preset development. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', '### Plugins and modes', 'A plugin adds capabilities to DSH, such as a tool, a service connection, or a UI entry. A mode is an agent preset that selects tools and defines how the agent works in a task. A plugin can be included in a custom preset.', '### How the result takes effect', @@ -89,6 +90,7 @@ export const guideZh: Record = { guideStandardExplanation: [ '### 工作方式', 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理和上下文压缩等能力。', + '对于 DSH 相关问题以及你要求的插件或预设工作,dsh-doc skill 引导 Agent 查阅已安装的文档和源码。其指令仅在被要求加载或与当前任务相关时加载;加载该 skill 不会改变文件、工具或 profile。', '### 什么时候选', '日常编程、文件处理和资料整理可以从这里开始。标准模式也能编写脚本、批量处理文件;PTC 改变的是工具调用方式,批量任务并不必须使用 PTC。', ].join('\n\n'), @@ -132,7 +134,7 @@ export const guideZh: Record = { guideCordisIntro: '新建任务时选择「创造模式」,说明希望增加什么能力、从哪里使用,以及怎样验证效果。', guideCordisExplanation: [ '### 可以创造什么', - '创造模式具备标准任务工具,并增加运行时检查,以及 Cordis 插件和 Agent 预设的开发指引。可以编写插件来添加功能或界面,也可以组合工具和提示词,创建适合特定任务的模式。', + '创造模式包含标准任务工具,并增加了运行时检查。标准模式和创造模式共用 dsh-doc 指引,用于插件和预设开发。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', '### 插件与模式的关系', '插件为 DSH 增加能力,例如工具、服务连接或界面入口。模式是一份 Agent 预设,用来选择任务可用的工具,并约定 Agent 的工作方式。自定义模式中也可以使用自己开发的插件。', '### 怎样让成果生效', diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml new file mode 100644 index 0000000000..63dcb56e37 --- /dev/null +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -0,0 +1,49 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-connector-account/README.md +/: + en: f09638e4097c52fb + zh: 2fb344b05a189ad0 +/deepseek-ai-dsh-client-ui-connector-account: + en: bdb528546ec26353 + zh: 0dd55dbc0c8e837a +/deepseek-ai-dsh-client-ui-connector-account/summary: + en: b25fc16fb18a63c1 + zh: 4508e8a44745b08d +/deepseek-ai-dsh-client-ui-connector-account/table-of-contents: + en: d152484eb41ac6b4 + zh: 5b6bd00fce5371c3 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package: + en: 9d8d49a0b1b3ce24 + zh: 8eba3710036afa00 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/register-an-account: + en: e618281ea7721daf + zh: a5d5f5e307ea3435 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: + en: f2bb2f05e2e122a4 + zh: f3dc9945b3f30736 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: + en: 0f6140d7ed6427b9 + zh: feadef500ee4fd98 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: + en: 353a48db7e7dd0f7 + zh: 653f3d983d3fd572 +/deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: + en: 890bd2109a5b5c4f + zh: f4373b71cb4f2018 +/deepseek-ai-dsh-client-ui-connector-account/further-exploration: + en: 029949903a73d283 + zh: 6f9a8c2f7620de69 +/deepseek-ai-dsh-client-ui-connector-account/model-experience: + en: bdbc56a07884f8d6 + zh: 22ca2ee613472c0b +/deepseek-ai-dsh-client-ui-connector-account/model-experience/kv-cache-effect: + en: 4cd0965a7997970e + zh: 690e5a9d945f7f6e +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work: + en: d2c5f54b80b86b15 + zh: 8b637f97ac1d0223 +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work/dev-note: + en: 2ab3c4acae06850c + zh: bd2093ba1fdd6860 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md new file mode 100644 index 0000000000..9f1ac26602 --- /dev/null +++ b/packages/client/ui-connector-account/README.md @@ -0,0 +1,138 @@ +--- +description: "Register a connector plugin's account on the Host with `ctx.connectorAccounts` and show its section, title tag, activation prompt, confirmations, and notices on the Plugins page through one `connectorAccounts` Remote, with the registrant's own text and the shared copy of this package." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +English | [中文](README.zh.md) + +## Summary + +Connector plugins register their account on the Host with `ctx.connectorAccounts` to show it on the Plugins page: CLI app plugins register the account their vendor CLI keeps, and MCP connectors their OAuth server's account. The Host decides what the page shows and does: each registrant maps its account to a display, and the registry starts or cancels only the operations the account lists. The browser half renders each bundle's section, title tag, and activation prompt, and opens authorization pages and reports notices only in the browser that started the operation. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +A registrant's Host row registers its account once; the registrant ships no browser code for the account. + +### Register an account + +The registrant's Host row registers its account source while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` identifies the account in the Remote; the page passes it back to start and cancel operations. A second registration with the same key throws. +- `packageName` is the npm package whose bundle page carries the section and tag; a package carries at most one account. An account without one, such as a server configured in Settings, appears on no bundle page. +- `source` is the account: its current view, change observation, a check, and starting and cancelling operations. +- `operations` lists the kinds a page button may start, each with the optional text its success reports in the browser that started it; the registry rejects any other kind. +- `copy` holds the section title, the hint under it, and the activation prompt's title, body, and Connect label. + +The registrant imports the registry's types with `import type` from the package root or `./types`. The returned disposer withdraws the account from every page. + +### Present the section + +`present(view)` maps the account view to a `ConnectorAccountDisplay`: the phase, the status line, the optional title tag, buttons, the operation Connect starts in the activation prompt, detail, notes, and failure with its untranslated diagnostic items. The registry calls it for every stream on each change, so it only maps the view. Every string is `LocalizedText`, which each browser resolves in its active language. A button carries a command: `start` with one of the registered operation kinds, `cancel` for the operation in progress, which the source ignores in a phase that is not cancellable, or `open` to reopen its authorization page. A button with `confirm` asks first and runs only after the user accepts. + +| Surface | Behavior | +|---|---| +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | +| Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | +| Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | + +### Following operations + +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. The stream reconnects after a lost connection; when it fails for good, the sections keep the last accounts with their buttons disabled until the page reloads. Unloading the browser half closes the stream; Host-owned operations keep running. + +### Shared copy + +The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Later, the diagnostic label, and the failure notice. Every other string comes from the registrant. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. + +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | The `ctx.connectorAccounts` registry and its Remote | +| [`src/types.ts`](src/types.ts) | Registration, source, view, display, and entry types | +| [`src/client/index.ts`](src/client/index.ts) | The browser entry: the dictionary and the slot registrations | +| [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | +| [`src/client/components.tsx`](src/client/components.tsx) | The slot entries of each surface and the buttons' Remote calls | +| [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | + +
+ +----- + + +## Further Exploration + +- [Plugin manager page](../ui-plugin-manager/README.md) — the Plugins page and its bundle slots. +- [Client package map](../README.md) — adjacent browser UI packages. + +----- + + +## Model Experience + +None, as the registry and its surfaces are Plugins page UI and add no model input. Each registrant documents the tools and skills its account enables. + +#### KV Cache effect + +None; registering or removing an account changes no model-visible text. + +## Known Limitations and Deferred Work + + + +- The five display phases are fixed; a registrant maps any further account state onto one of them. +- A registrant whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. +- Each browser that loads the Web app starts a check of every idle account. +- The Web and Desktop compositions load the registry whether or not a connector plugin is installed. +- An authorization page that opens after the call answers can be blocked by the browser; the section's open button shows it again. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs drive the registry with fake account sources. Client specs drive `BrowserAccounts` with a fake Remote stream, render the surfaces with the Chinese dictionary and a fake Remote, and mount the browser half against a real slot registry and locale runtime. + +
diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md new file mode 100644 index 0000000000..5c00f7a229 --- /dev/null +++ b/packages/client/ui-connector-account/README.zh.md @@ -0,0 +1,138 @@ +--- +description: "通过 `ctx.connectorAccounts` 在 Host 上注册连接器插件的账号,并经由一个 `connectorAccounts` Remote 在插件页显示其区块、标题旁标签、开启引导、确认和提示,文案来自注册方自己的文本和本包的共用文案。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +[English](README.md) | 中文 + +## 概述 + +连接器插件在 Host 上通过 `ctx.connectorAccounts` 注册账号,在插件页显示账号:CLI 应用插件注册其厂商 CLI 保存的账号,MCP 连接器注册其 OAuth 服务器的账号。页面显示什么、能做什么由 Host 决定:每个注册方把自己的账号映射为展示内容,注册表只启动或取消该账号列出的操作。浏览器一半渲染每个插件包的区块、标题旁标签和开启引导,并且只在发起操作的浏览器中打开授权页、报告提示。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两半。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [延伸阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +注册方的 Host 行注册一次账号;注册方不为账号提供任何浏览器代码。 + +### 注册账号 + +注册方的 Host 行在注册表运行时注册其账号来源,因此没有注册表的组合(如 headless profile)会跳过注册: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` 在 Remote 中标识该账号;页面启动和取消操作时把它传回。用同一个键再次注册会抛出异常。 +- `packageName` 是其插件包页面承载区块和标签的 npm 包;一个包最多承载一个账号。没有包名的账号(如在 Settings 中配置的服务器)不出现在任何插件包页面上。 +- `source` 是账号:其当前视图、变化观察、检查,以及启动和取消操作。 +- `operations` 列出页面按钮可以启动的操作类型,每项可带该操作成功时在发起它的浏览器中报告的文本;注册表拒绝其他类型。 +- `copy` 包含区块标题、区块下方的提示,以及开启引导的标题、正文和连接按钮文案。 + +注册方用 `import type` 从包根或 `./types` 导入注册表的类型。返回的销毁函数会把账号从所有页面撤下。 + +### 展示区块 + +`present(view)` 把账号视图映射为 `ConnectorAccountDisplay`:阶段、状态行、可选的标题旁标签、按钮、开启引导中“连接”启动的操作、说明、附加行,以及带不翻译诊断项的失败信息。注册表在每次变化时为每条流调用它,因此它只做视图映射。所有文案都是 `LocalizedText`,由各浏览器按当前语言解析。按钮携带一个命令:`start` 启动某个已注册的操作类型,`cancel` 取消进行中的操作(处于不可取消的阶段时来源会忽略),`open` 重新打开其授权页。带 `confirm` 的按钮会先询问,用户确认后才执行。 + +| 界面 | 行为 | +|---|---| +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | +| 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | + +### 跟随操作 + +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。连接断开后流会自动重连;流永久失败时,区块保留最后的账号,按钮不可用,直到页面重新加载。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 + +### 共用文案 + +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、稍后、排障信息标签和失败提示。其余文案都来自注册方。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 + +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | `ctx.connectorAccounts` 注册表及其 Remote | +| [`src/types.ts`](src/types.ts) | 注册、来源、视图、display 和条目类型 | +| [`src/client/index.ts`](src/client/index.ts) | 浏览器入口:字典和插槽注册 | +| [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面的插槽条目,以及按钮的 Remote 调用 | +| [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | + +
+ +----- + + +## 延伸阅读 + +- [插件管理页](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 +- [客户端包地图](../README.zh.md)——相邻的浏览器 UI 包。 + +----- + + +## 模型体验 + +无,注册表及其界面属于插件页 UI,不增加模型输入。各注册方自行说明其账号启用的工具和技能。 + +#### KV Cache 影响 + +无;注册或移除账号不改变任何模型可见文本。 + +## 已知限制与后续工作 + + + +- 五个显示阶段固定不变;注册方需把其他账号状态映射到其中之一。 +- Host 行加载失败的注册方不显示账号区块;插件页仍会列出该插件包及其加载失败。 +- 每个加载 Web 应用的浏览器都会触发一次对所有空闲账号的检查。 +- 无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。 +- 调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 测试用假的账号来源驱动注册表。客户端测试用假的 Remote 流驱动 `BrowserAccounts`,用中文字典和假的 Remote 渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一半。 + +
diff --git a/packages/client/ui-connector-account/locale/de.json b/packages/client/ui-connector-account/locale/de.json new file mode 100644 index 0000000000..98f0f64dea --- /dev/null +++ b/packages/client/ui-connector-account/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector-Kontoverbindung", + "description": "Kontobereich, Titel-Tag, Aktivierungshinweis und Benachrichtigungen auf der Seite „Plugins“ für Connector-Plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/en.json b/packages/client/ui-connector-account/locale/en.json new file mode 100644 index 0000000000..f0d6ca2f20 --- /dev/null +++ b/packages/client/ui-connector-account/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector account connection", + "description": "Account section, title tag, activation prompt, and notices on the Plugins page for connector plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/es.json b/packages/client/ui-connector-account/locale/es.json new file mode 100644 index 0000000000..90e3835555 --- /dev/null +++ b/packages/client/ui-connector-account/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexión de cuenta de conectores", + "description": "Sección de cuenta, etiqueta del título, aviso de activación y notificaciones en la página Complementos para los complementos de conectores." + } +} diff --git a/packages/client/ui-connector-account/locale/fr.json b/packages/client/ui-connector-account/locale/fr.json new file mode 100644 index 0000000000..6aa61577ee --- /dev/null +++ b/packages/client/ui-connector-account/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connexion de compte de connecteur", + "description": "Section de compte, étiquette de titre, invite d’activation et notifications sur la page Plugins pour les plugins de connecteur." + } +} diff --git a/packages/client/ui-connector-account/locale/ja.json b/packages/client/ui-connector-account/locale/ja.json new file mode 100644 index 0000000000..d8a18a8135 --- /dev/null +++ b/packages/client/ui-connector-account/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "コネクターアカウント接続", + "description": "コネクタープラグイン向けに、「プラグイン」ページでのアカウントセクション、タイトルタグ、有効化時の案内、通知を提供します。" + } +} diff --git a/packages/client/ui-connector-account/locale/pt.json b/packages/client/ui-connector-account/locale/pt.json new file mode 100644 index 0000000000..abec0eafe9 --- /dev/null +++ b/packages/client/ui-connector-account/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexão de conta de conector", + "description": "Seção da conta, etiqueta do título, aviso de ativação e notificações na página Plug-ins para plugins de conector." + } +} diff --git a/packages/client/ui-connector-account/locale/ru.json b/packages/client/ui-connector-account/locale/ru.json new file mode 100644 index 0000000000..be0914f34b --- /dev/null +++ b/packages/client/ui-connector-account/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Подключение аккаунта коннектора", + "description": "Раздел аккаунта, метка у заголовка, подсказка при включении и уведомления на странице «Плагины» для плагинов-коннекторов." + } +} diff --git a/packages/client/ui-connector-account/locale/zh.json b/packages/client/ui-connector-account/locale/zh.json new file mode 100644 index 0000000000..af4aade6f6 --- /dev/null +++ b/packages/client/ui-connector-account/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "连接器账号连接", + "description": "在插件页为连接器插件提供账号区块、标题标签、开启引导与提示。" + } +} diff --git a/packages/client/ui-mcp-account/package.json b/packages/client/ui-connector-account/package.json similarity index 85% rename from packages/client/ui-mcp-account/package.json rename to packages/client/ui-connector-account/package.json index 963318e7d3..a571731e29 100644 --- a/packages/client/ui-mcp-account/package.json +++ b/packages/client/ui-connector-account/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-client-ui-mcp-account", - "description": "MCP account surfaces for connector plugins: the Host registry connectors register their OAuth server accounts with, and the Plugins page section, title tag, activation guidance, and notices it serves over one Remote", + "name": "@deepseek-ai/dsh-client-ui-connector-account", + "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", "version": "0.2.2-rc.1", "publishConfig": { "access": "public" @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/client/ui-mcp-account" + "directory": "packages/client/ui-connector-account" }, "type": "module", "main": "lib/index.js", @@ -22,11 +22,11 @@ "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, - "./src/*": "./src/*", - "./package.json": "./package.json", "./types": { "types": "./lib/types/types.d.ts" }, + "./src/*": "./src/*", + "./package.json": "./package.json", "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" @@ -64,6 +64,7 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-gateway": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", @@ -72,8 +73,6 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@deepseek-ai/dsh-mcp-client": "workspace:*", - "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-package-manifest": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@testing-library/react": "^16.3.3", diff --git a/packages/client/ui-mcp-account/src/client/McpAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css similarity index 100% rename from packages/client/ui-mcp-account/src/client/McpAccount.module.css rename to packages/client/ui-connector-account/src/client/ConnectorAccount.module.css diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx new file mode 100644 index 0000000000..e0293d02b2 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -0,0 +1,215 @@ +/** + * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section with the + * confirmation a button asks for, the title tag, the activation prompt, and the notice. Each is the slot entry that reads + * this browser's state and calls the Remote. + */ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' +import css from './ConnectorAccount.module.css' +import type { ConnectorAccountKey } from './locales.ts' +import { openAuthorizationPage } from './state.ts' +import type { ConnectorAccountFace, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' + +type FaceProps = InjectFace & { t: Translate } +type BundleFaceProps = InjectFace & { t: Translate } + +const TONE: Record = { + checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', +} + +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', +} + +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + +/** + * Run a button's command against the Host: start and cancel call the Remote directly, and open shows the operation's + * authorization page again in this browser. + * @param face - the Remote and the browser state the commands report to. + * @returns whether a call this surface made has not answered, and the runner of one account's command. + */ +function useAccountCommand( + face: Pick, +): { readonly busy: boolean; readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void } { + const [busy, setBusy] = useState(false) + // A second click before the re-render still finds the first call pending. + const pending = useRef(false) + const call = (operation: () => Promise): void => { + if (pending.current) return + pending.current = true + setBusy(true) + // The Host keeps the diagnostic; the page reports one retryable outcome. + void operation().catch(() => { face.failed() }).finally(() => { pending.current = false; setBusy(false) }) + } + const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { + const { key } = entry + switch (command.kind) { + case 'start': + call(async () => { face.follow(key, await settle(face.remote.start(key, command.operation))) }) + return + case 'cancel': { + const operation = entry.operation + if (operation !== undefined) call(async () => { await settle(face.remote.cancel(key, operation.id)) }) + return + } + case 'open': + openAuthorizationPage(entry.operation?.authorizationUrl) + return + /* v8 ignore next -- closed command union */ + default: assertNever(command) + } + } + return { busy, run } +} + +/** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ +function Confirm(props: { + readonly t: Translate + readonly title: string + readonly body: string + readonly label: string + readonly onClose: () => void + readonly onConfirm: () => void +}): ReactNode { + const { t, title, body, label, onClose, onConfirm } = props + return ( + + + + }> +

{body}

+
+ ) +} + +/** + * The `plugins.bundle.config` entry: the account section on its bundle's page. + * @param props - the bundle's face and the translator. + * @returns the title, status line, buttons, detail, notes, failure, hint, and the confirmation a button asked for, or + * null before the Host lists the account. + */ +export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { + const { useConnectorAccounts, account, resolveText, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const linked = useConnectorAccounts(state => state.linked) + const { busy, run } = useAccountCommand(props) + const [confirming, setConfirming] = useState() + if (entry === undefined) return null + const { display } = entry + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } + return + } + const details = display.failure?.details ?? [] + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {resolveText(display.status)} +
{display.buttons.map(button)}
+
+ {display.detail === undefined ? null :

{resolveText(display.detail)}

} + {display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {display.failure === undefined ? null : ( +

+ {resolveText(display.failure.text)} + {details.length === 0 ? null : <> {t('failure.details', { details: details.join(' · ') })}} +

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + )} +
+ ) +} + +function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { + for (const entry of state.accounts.values()) if (entry.packageName === packageName) return entry + return undefined +} + +/** + * The `plugins.detail.badge` entry shared by every bundle that owns an account. + * @param props - the open detail page's subject and the face. + * @returns the display's tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + */ +export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { + const { useConnectorAccounts, resolveText, subject } = props + const packageName = subject.kind === 'item' || !subject.pkg.enabled ? undefined : subject.pkg.name + const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) + const badge = entry?.display.badge + return entry === undefined || badge === undefined ? null : {resolveText(badge)} +} + +/** + * The `plugins.bundle.activation` entry: guidance after the user switches a bundle on while its account is not + * connected. Connect opens the bundle page and starts the display's `connect` command. + * @param props - activation callbacks, the bundle's face, and the translator. + * @returns a prompt shown while disconnected, or null before the Host lists the account. It waits while the account is + * checking or connecting, which may still end disconnected, and dismisses itself once the account is connected or + * unavailable. + */ +export function ConnectorAccountActivationEntry( + props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, +): ReactNode { + const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props + const entry = useConnectorAccounts(state => state.accounts.get(account)) + const { run } = useAccountCommand(props) + const phase = entry?.display.phase + useEffect(() => { + if (phase === 'connected' || phase === 'unavailable') onDismiss() + }, [phase, onDismiss]) + if (entry === undefined) return null + const { activation } = entry.copy + const { connect } = entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(entry, connect) + } + return ( + + + + }> +

{resolveText(activation.body)}

+
+ ) +} + +/** + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. + * @param props - the face and the translator. + * @returns the toast for the latest notice, or null. + */ +export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { + const notice = useConnectorAccounts(state => state.notice) + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..2c15e0ec09 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,89 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const browser = new BrowserAccounts(ctx, ctx.remote.connectorAccounts) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + remote: ctx.remote.connectorAccounts, + resolveText: text => ctx.locale.resolveText(text), + follow: (key, id) => { browser.follow(key, id) }, + failed: () => { browser.failed() }, + dismissNotice: () => { browser.dismissNotice() }, + } + ctx.effect(function* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..c0a30b7555 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,86 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', +} + +/** Every key the shared account surfaces translate. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..332715e431 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,141 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsRemote, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +export class BrowserAccounts { + /** The accounts, stream state, and notice every surface on the page reads. */ + readonly state: SnapshotStore = createSnapshotStore({ + accounts: new Map(), linked: true, notice: undefined, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private readonly stream: RemoteStream + private readonly observing: Promise + + /** + * @param ctx - the browser context carrying the Remote client. + * @param remote - the `connectorAccounts` Remote. + */ + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + this.patch({ notice: undefined }) + } + + /** + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + await this.observing + } + + private async observe(): Promise { + try { + for await (const item of this.stream) { + // An item the stream yielded just before disposal must not reach the disposed page. + if (this.disposed) return + this.show(item.value.accounts) + item.accept() + } + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) + } + } + + private show(entries: readonly ConnectorAccountEntry[]): void { + const accounts = new Map(entries.map(entry => [entry.key, entry])) + for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) + this.patch({ accounts, linked: true }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..482363c688 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,46 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + readonly accounts: ReadonlyMap + /** Whether the Host stream is delivering. */ + readonly linked: boolean + readonly notice: ConnectorAccountNotice | undefined +} + +/** The `connectorAccounts` Remote methods the page uses. */ +export interface ConnectorAccountsRemote { + watch(signal: AbortSignal): AsyncIterable + start(key: string, operation: string): Promise> + cancel(key: string, id: ConnectorOperationId): Promise> +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** The Remote the buttons call directly. */ + readonly remote: Pick + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + readonly follow: (key: string, id: ConnectorOperationId) => void + /** Report that a Remote call this browser made did not finish. */ + readonly failed: () => void + readonly dismissNotice: () => void +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..aa7ec1d6d4 --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId | Promise + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity once the account's source has started it. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..debd04d302 --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..d01ff8c3f2 --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,155 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function' && typeof value.remote === 'object') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + await face.remote.start(FIXTURE, 'connect') + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + face.follow(FIXTURE, OP) + face.failed() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) + face.dismissNotice() + expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() + + // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { + expect(b.ctx.slots.entries(slot)).toEqual([]) + } + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') + expect(b.closeStream).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..25978b5ac3 --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,222 @@ +// @vitest-environment jsdom +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en +const button = (name: string) => screen.getByRole('button', { name }) +const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } + +const DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +const ok = (value: T): RemoteResult => ({ ok: true, value }) +const refused = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never + +function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { + const current: ConnectorAccountsState = { + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + remote: { + start: vi.fn(async (_key: string, _operation: string) => ok(OP)), + cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), + }, + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, + } +} + +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation through the Remote', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.remote.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { + const props = face() + const answer = Promise.withResolvers>() + props.remote.start.mockReturnValueOnce(answer.promise) + render() + fireEvent.click(button('连接演示')) + expect(disabled()).toEqual([true]) + await act(async () => { answer.resolve(ok(OP)) }) + expect(disabled()).toEqual([false]) + expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.remote.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('reports a start the Host refused or that never answered, without following it', async () => { + const props = face() + props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) + render() + await click('连接演示') + await click('连接演示') + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await click('取消') + expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = sectionOf(display) + render() + await click('取消') + expect(idle.remote.cancel).not.toHaveBeenCalled() +}) + +it('renders nothing for a bundle whose account the Host has not listed', () => { + render() + render(prompt(face({}, []))) + expect(document.body.textContent).toBe('') +}) + +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { + const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) + const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) + const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face(), row)) + expect(screen.getByText('未连接')).toBeTruthy() + for (const [props, subject] of [ + [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + +it('connects from the prompt through the operation the display names, or only opens the page', async () => { + const onOpenDetails = vi.fn() + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, vi.fn(), onOpenDetails)) + fireEvent.click(button('连接演示')) + expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.remote.start).not.toHaveBeenCalled() +}) + +it('starts once for a second click before the first call answers', async () => { + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) + const answer = Promise.withResolvers>() + props.remote.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(ok(OP)) }) + expect(props.remote.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..ee8e24276f --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,170 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..4c11668ac2 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const browser = new BrowserAccounts(ctx, remote) + onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + ctx, browser, remote, open: windowOpen, streams, options: () => options, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { + const b = fixture() + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) + expect(b.state().linked).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.state().linked).toBe(true) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { + const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) + await b.publish(entry(FIXTURE)) + b.fail(new Error('Host without the registry')) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) +}) + +it('opens nothing and reports nothing after disposal', async () => { + const b = fixture() + await b.browser.dispose() + b.browser.follow(FIXTURE, OP) + b.browser.failed() + expect(b.state().notice).toBeUndefined() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state().linked).toBe(true) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-mcp-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json similarity index 91% rename from packages/client/ui-mcp-account/tsconfig.client.json rename to packages/client/ui-connector-account/tsconfig.client.json index 06e93f1d06..115af386fd 100644 --- a/packages/client/ui-mcp-account/tsconfig.client.json +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -38,23 +38,20 @@ { "path": "../ui-slots" }, - { - "path": "../../mcp/mcp-client" - }, { "path": "../../typert/protocol" }, - { - "path": "../../util/values" - }, { "path": "../locale/tsconfig.client.json" }, + { + "path": "../../util/brand" + }, { "path": "../../util/package-manifest" }, { - "path": "../../mcp/mcp-manager" + "path": "../../util/values" } ] } diff --git a/packages/client/ui-mcp-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json similarity index 91% rename from packages/client/ui-mcp-account/tsconfig.host.json rename to packages/client/ui-connector-account/tsconfig.host.json index a0b64f5bfa..564ba19f3b 100644 --- a/packages/client/ui-mcp-account/tsconfig.host.json +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -14,10 +14,10 @@ "path": "../../../vendor/cordis" }, { - "path": "../../mcp/mcp-manager" + "path": "../../typert/protocol" }, { - "path": "../../typert/protocol" + "path": "../../util/brand" }, { "path": "../../util/package-manifest" diff --git a/packages/client/ui-mcp-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json similarity index 100% rename from packages/client/ui-mcp-account/tsconfig.json rename to packages/client/ui-connector-account/tsconfig.json diff --git a/packages/client/ui-mcp-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts similarity index 100% rename from packages/client/ui-mcp-account/tsdown.config.ts rename to packages/client/ui-connector-account/tsdown.config.ts diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index c88fda7554..52e160a17b 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -18,11 +18,11 @@ en: ef43c4f149195939 zh: 49fc6c83fd3a05ce /deepseek-ai-dsh-client-ui-conversation/sent-user-text: - en: cc4dafd1aae02468 - zh: be6b67724b7ac4a3 + en: 4a094cd97426ad18 + zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: bd2a85b9012fa3c3 - zh: e88d7e682e316a0e + en: 7c45c9c9767b3184 + zh: 290037aa8a71b1df /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: b3f74c35f88ab2fa - zh: 8492b314debd130c + en: c8323c1986c1be46 + zh: 6151492c67d4cb88 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 041aa0d5d4..32c07ecabc 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -61,7 +61,7 @@ Queue previews enable whitespace collapsing and document-edge trimming, retain e [Message quotes](../../session/message-quotes/README.md) registers quote matching and rendering through the same UserText extension points. Each user-text container and draft editor owns an independent hover-card group, so its quote previews replace one another immediately. -The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinate spans beside references. Storage accepts earlier string and reference-only drafts; Session switching and Workspace transfer preserve atomic quotes through the existing editor runtime, and a failed send leaves them in the editor. `inputActions.insertQuote(text)` inserts a nonblank selection only while the composer is in plain mode. Submission emits ordinary Markdown text; pending echoes, queue rows, steering rows, and durable messages use the same text matcher. +The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinate spans beside references. Storage accepts earlier string and reference-only drafts; Session switching and Workspace transfer preserve atomic quotes through the existing editor runtime, and a failed send leaves them in the editor. `inputActions.insertQuote(text, summary?)` inserts a nonblank selection only while the composer is in plain mode; an optional `QuoteSummary` replaces the text in the composer display and is stored with the draft, while the sent message still carries the text. Submission emits ordinary Markdown text; pending echoes, queue rows, steering rows, and durable messages use the same text matcher. `UiConversation.interactions` owns plugin registrations for selected-text and context-menu gestures. A registration supplies a synchronous handler whose ID selects its keyed Slot component; plugins use the Slot injection mechanism for rendering. Handlers call `open()` to display and call `preventDefault()` separately when replacing a browser default. Chat supplies DOM selections and local layout; original source data and Markdown offsets are not inferred from DOM positions. @@ -132,6 +132,8 @@ Each composer attempt carries its original occurrence time, gesture, delivery in A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. +Every mounted composer, including a subagent conversation open in the right Sidebar, joins one document-level paste route. A paste whose clipboard carries files, while focus is outside any input, text area, or editable element, enters the composer that most recently held focus, or the main Conversation's composer before any other composer has held focus or while the focused one cannot accept files; a paste inside a focused editor stays with that editor, and clipboard text without files is never inserted this way. A composer in a hidden or inert subtree, such as a collapsed Sidebar or an unselected tab, is never addressed, and while a modal dialog or menu is open only a composer inside it can be. When no addressable composer can accept files, the paste keeps the browser's default handling. + Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A refused or failed submission publishes no echo and leaves the draft in the composer with an error notice. A refusal from the Agent admission stage (`session/prompt-rejected`) shows its own text, unless `presented` says the refusing plugin explains it in its own interface, in which case the composer adds no notice. Disabled Send and Stop buttons suppress their tooltips, including a Stop button that becomes a disabled Send button when the turn ends. While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. While a message waits for the Host, the seat shows its progress, and a separate Stop stays beside it. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label. Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions and accept pasted or dropped images, but expose no File row; creator availability does not disable input, and Host admission failures use the ordinary prompt error feedback ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../subagent/subagent/README.md)). @@ -221,6 +223,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 0ac0d779d1..f7e349e84d 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -61,7 +61,7 @@ Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CS [Message quotes](../../session/message-quotes/README.zh.md) 通过相同的 UserText 扩展点注册引用匹配与渲染。 每个用户文本容器和草稿编辑器各自拥有独立的悬停卡片分组,其中的 quote 原文弹层会立即互相替换。 -现有语义 `DraftSnapshot` 在 references 旁保留 quote 文本及 clipboard 坐标范围。存储接受较早的字符串和仅含 reference 的草稿;Session 切换和 Workspace 转移通过现有编辑器 runtime 保留原子 quote,发送失败时它们留在编辑器中。`inputActions.insertQuote(text)` 仅在输入框处于 plain 模式时插入非空选区。提交产出普通 Markdown 文本;待发送回显、队列行、steering 行和持久消息使用同一文本匹配器。 +现有语义 `DraftSnapshot` 在 references 旁保留 quote 文本及 clipboard 坐标范围。存储接受较早的字符串和仅含 reference 的草稿;Session 切换和 Workspace 转移通过现有编辑器 runtime 保留原子 quote,发送失败时它们留在编辑器中。`inputActions.insertQuote(text, summary?)` 仅在输入框处于 plain 模式时插入非空选区;可选的 `QuoteSummary` 在输入框中替代文本显示并随草稿保存,发送的消息仍携带该文本。提交产出普通 Markdown 文本;待发送回显、队列行、steering 行和持久消息使用同一文本匹配器。 `UiConversation.interactions` 拥有插件对文本选择和右键手势的注册。每个注册项提供同步处理函数,其 ID 选择对应的 keyed Slot 组件;插件通过 Slot injection 机制渲染。处理函数调用 `open()` 展示,需要替代浏览器默认行为时单独调用 `preventDefault()`。Chat 提供 DOM 选区和区域内布局;机制不从 DOM 位置推断原始来源数据或 Markdown 偏移。 @@ -132,6 +132,8 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 +每个已挂载的 composer(包括在右侧栏打开的子代理对话)都加入同一条文档级粘贴路由。焦点不在任何输入框、文本区域或可编辑元素内时,剪贴板带有文件的粘贴会进入最近一次获得焦点的 composer;在其他 composer 获得焦点之前,或最近聚焦的 composer 当前无法接收文件时,则进入主 Conversation 的 composer。已聚焦编辑器内的粘贴仍由该编辑器处理,不含文件的剪贴板文字不会经此插入。位于隐藏或 inert 子树中的 composer(例如折叠的侧栏或未选中的标签页)不会成为目标;打开模态对话框或菜单时,只有其中的 composer 可以成为目标。没有可作为目标的 composer 能接收文件时,粘贴保留浏览器的默认处理。 + 排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到提示词确认不会启用队列操作。被拒绝或失败的提交不会公开回显,草稿留在 composer 中并显示错误提示。Agent 接纳阶段的拒绝(`session/prompt-rejected`)显示它自带的文字;若 `presented` 表明拒绝它的插件会在自己的界面里说明,composer 不再提示。 Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切换成禁用 Send 的按钮也遵循此规则。普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。消息等待 Host 接收期间,该位置显示发送进度,旁边另有独立的 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,允许粘贴或拖入图片,但不提供「文件」菜单项;创建者的在线状态不禁用输入,Host 接收失败使用普通提示词错误反馈([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../subagent/subagent/README.zh.md))。 @@ -221,6 +223,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index aae71928be..37420f7fc2 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -33,6 +33,7 @@ import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' +import { createComposerFileIntake } from './input/file-intake.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -460,6 +461,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }), }, ConversationSessionHeader) + const fileIntake = createComposerFileIntake() const registerComposerBar = () => slots.register({ name: 'conversation.composer.bar', locale: NS, @@ -477,6 +479,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { + registerFileIntake: fileIntake, keyboard: undefined, addFiles: undefined, removeAttachment: undefined, @@ -500,6 +503,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { const inputTriggers = inputHub.inputTriggers(sessionId) const bridge = hostPathBridge() return { + registerFileIntake: fileIntake, keyboard: shell, addFiles: (files, directories = new Set()) => { if (sessions.binding(sessionId) === undefined) return t('file.sessionUnavailable') diff --git a/packages/client/ui-conversation/src/client/contract/draft-editor.ts b/packages/client/ui-conversation/src/client/contract/draft-editor.ts index b305bb3a3c..86592a82db 100644 --- a/packages/client/ui-conversation/src/client/contract/draft-editor.ts +++ b/packages/client/ui-conversation/src/client/contract/draft-editor.ts @@ -1,5 +1,6 @@ /** Editor-facing ranges, reference projections, and the composer keyboard interface. */ import type { LexicalEditor } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { InputState } from './input.ts' import type { InputSubmitMode } from './composer-submission.ts' @@ -28,6 +29,8 @@ export interface DraftQuote { readonly length: number /** Selected text before Markdown quote prefixes are added. */ readonly text: string + /** Readable display the inserting owner supplied; the draft text and the sent message still carry `text`. */ + readonly summary?: QuoteSummary | undefined } /** diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 6f6b0f1436..3d8ebd6d6a 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -11,6 +11,7 @@ import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/cli import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Branded } from '@deepseek-ai/dsh-brand' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { ArbitrateKey, ArbitrateOutcome, DraftQuote, Occurrence, ReferenceInsert, TokenSpan } from './draft-editor.ts' import type { InputSubmitMode, MessageSubmission } from './composer-submission.ts' @@ -182,8 +183,13 @@ export interface InputTarget { /** Per-session input facade owned by the conversation wiring layer. */ export interface SessionInput extends InputTarget { - /** Insert selected transcript text as an atomic quote. @param text - nonblank selection. @returns whether editing accepted it. */ - insertQuote(text: string): boolean + /** + * Insert text as an atomic quote. + * @param text - nonblank selection; the sent message carries it as a Markdown blockquote. + * @param summary - readable display shown in the composer instead of `text`. + * @returns whether editing accepted it. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean /** Replace the whole draft with plain text, removing inline reference chips. */ setDraft(text: string): void @@ -256,8 +262,13 @@ export type DraftInitializationResult = 'applied' | 'preserved' | 'blocked' * paste/…) stay InputBar-private and never ride this face. */ export interface InputActions { - /** Insert one nonblank transcript quote. @param text - selected text. @returns whether editing accepted it. */ - insertQuote(text: string): boolean + /** + * Insert one nonblank quote. + * @param text - selected text; the sent message carries it as a Markdown blockquote. + * @param summary - readable display shown in the composer instead of `text`. + * @returns whether editing accepted it. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean /** @returns a revision-guarded copy of the current editor selection. */ captureInsertion(): TokenSpan /** diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index e7ae7285ab..f8bbf67c5b 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -545,6 +545,8 @@ export interface ConversationSessionHeaderInjected { export interface ComposerBarOwnerProps { /** Hero uses centered placement; composer uses the active bottom placement. */ variant: 'hero' | 'composer' + /** Conversation content occurrence rendering this composer; an unaddressed document paste reaches the main one. */ + occurrence: ConversationContentInputProps['variant'] /** A feature-owned reason that makes message input inert while leaving model selection live. */ blocked?: { readonly reason: string } /** Lock all message actions while preserving the resident composer surface. */ @@ -558,8 +560,33 @@ export interface ComposerBarOwnerProps { accessory?: ReactNode } +/** One composer's entry in the document-level paste route. */ +export interface ComposerFileIntakeTarget { + /** Composer card containing every control of this composer. */ + readonly card: HTMLElement + /** Conversation content occurrence rendering the composer. */ + readonly occurrence: ConversationContentInputProps['variant'] + /** Whether a routed paste may enter now; a refusing composer is skipped, and when no composer accepts the browser keeps the event. */ + readonly accepts: () => boolean + /** + * Add one routed paste through the composer's intake validation. + * @param files - pasted browser files in clipboard order. + * @param directories - members of `files` the clipboard entry API identified as directories. + */ + readonly add: (files: readonly File[], directories?: ReadonlySet) => void +} + +/** + * Join the document-level paste route shared by every composer of the plugin instance. + * @param target - the registering composer. + * @returns the disposer leaving the route; the last disposer removes the route's document listeners. + */ +export type ComposerFileIntake = (target: ComposerFileIntakeTarget) => () => void + /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { + /** Document paste routing across mounted composers. */ + registerFileIntake: ComposerFileIntake keyboard: ComposerKeyboard | undefined /** * Register one picked batch; resolves to the rejection copy or null. Where diff --git a/packages/client/ui-conversation/src/client/draft.ts b/packages/client/ui-conversation/src/client/draft.ts index e4cee855b2..c5e96539de 100644 --- a/packages/client/ui-conversation/src/client/draft.ts +++ b/packages/client/ui-conversation/src/client/draft.ts @@ -1,6 +1,7 @@ /** Semantic draft snapshots shared by storage, programmatic input, and editor restoration. */ import { z } from 'zod' import { formatQuoteText } from '@deepseek-ai/dsh-client-ui-primitives' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { DraftInput, DraftQuote, DraftReference, DraftSnapshot, Occurrence } from './contract/draft-editor.ts' const referenceSchema = z.object({ @@ -18,10 +19,16 @@ const commandSchema = z.object({ token: z.string(), }) +// Lists every QuoteSummary field: parsing strips unknown keys, so a field missing here is dropped from restored drafts. +const quoteSummarySchema: z.ZodType = z.object({ + label: z.string(), title: z.string(), detail: z.string().optional(), body: z.string(), +}) + const quoteSchema = z.object({ offset: z.number().int().nonnegative(), length: z.number().int().positive(), text: z.string().refine(text => text.trim() !== ''), + summary: quoteSummarySchema.optional(), }) const snapshotSchema = z.object({ diff --git a/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx b/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx index ecd42af89d..78a2d379c9 100644 --- a/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx +++ b/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx @@ -3,6 +3,7 @@ import type { JSX } from 'react' import { QuotePreview } from '@deepseek-ai/dsh-client-ui-primitives' import { formatQuoteText } from '@deepseek-ai/dsh-client-ui-primitives' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { EditorConfig, LexicalEditor, LexicalNode, NodeKey, SerializedLexicalNode, Spread, } from 'lexical' @@ -18,21 +19,24 @@ const EMPTY_LABELS: QuoteNodeLabels = { remove: '' } /** JSON form used only by Lexical's editor-state APIs, not browser persistence. */ export type SerializedQuoteNode = Spread<{ text: string + summary?: QuoteSummary }, SerializedLexicalNode> /** Remove one quote occurrence by its Lexical identity. */ export const REMOVE_QUOTE_COMMAND = createCommand('REMOVE_QUOTE_COMMAND') /** Pure React face of one quote node. */ -export function QuoteNodeView({ editor, nodeKey, text, labels }: { +export function QuoteNodeView({ editor, nodeKey, text, summary, labels }: { readonly editor: LexicalEditor readonly nodeKey: NodeKey readonly text: string + readonly summary?: QuoteSummary | undefined readonly labels: QuoteNodeLabels }) { return ( { editor.dispatchCommand(REMOVE_QUOTE_COMMAND, nodeKey) }, @@ -44,6 +48,7 @@ export function QuoteNodeView({ editor, nodeKey, text, labels }: { /** One selected transcript range represented as an atomic inline decorator. */ export class QuoteNode extends DecoratorNode { __text: string + __summary: QuoteSummary | undefined __labels: QuoteNodeLabels /** Lexical node registry type tag. */ @@ -56,27 +61,31 @@ export class QuoteNode extends DecoratorNode { return new QuoteNode( node.__text, node.__labels, + node.__summary, node.__key, ) } /** @param json - serialized editor node. @returns a fresh node with default runtime labels. */ static override importJSON(json: SerializedQuoteNode): QuoteNode { - return new QuoteNode(json.text) + return new QuoteNode(json.text, EMPTY_LABELS, json.summary) } /** * @param text - selected text. * @param labels - runtime-only localized labels. + * @param summary - readable display shown instead of the text. * @param key - Lexical clone-path key; absent for fresh nodes. */ constructor( text: string, labels: QuoteNodeLabels = EMPTY_LABELS, + summary?: QuoteSummary, key?: NodeKey, ) { super(key) this.__text = text + this.__summary = summary this.__labels = labels } @@ -87,6 +96,7 @@ export class QuoteNode extends DecoratorNode { type: 'quote', version: 1, text: this.__text, + ...(this.__summary === undefined ? {} : { summary: this.__summary }), } } @@ -123,6 +133,11 @@ export class QuoteNode extends DecoratorNode { return this.getLatest().__text } + /** Readable display the inserting owner supplied, if any. */ + getQuoteSummary(): QuoteSummary | undefined { + return this.getLatest().__summary + } + /** Update the localized remove label without changing persisted quote data. */ setLabels(labels: QuoteNodeLabels): void { if (this.getLatest().__labels.remove !== labels.remove) this.getWritable().__labels = labels @@ -135,15 +150,21 @@ export class QuoteNode extends DecoratorNode { editor={editor} nodeKey={this.__key} text={this.__text} + summary={this.__summary} labels={this.__labels} /> ) } } -/** @param text - selected quote text. @param labels - runtime labels. @returns a fresh node. */ -export function $createQuoteNode(text: string, labels: QuoteNodeLabels): QuoteNode { - return new QuoteNode(text, labels) +/** + * @param text - selected quote text. + * @param labels - runtime labels. + * @param summary - readable display shown instead of the text. + * @returns a fresh node. + */ +export function $createQuoteNode(text: string, labels: QuoteNodeLabels, summary?: QuoteSummary): QuoteNode { + return new QuoteNode(text, labels, summary) } /** @param node - possible Lexical node. @returns whether it is a QuoteNode. */ diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index a2573fdefc..e2ac87b660 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -23,6 +23,7 @@ import { } from 'lexical' import { mergeRegister } from '@lexical/utils' import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/draft-editor.ts' +import { clipboardFiles } from '../file-intake.ts' import { $isQuoteNode } from './QuoteNode.tsx' /** The bar-supplied behavior behind each intercepted gesture. */ @@ -283,17 +284,7 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer // deliver clipboardData on plain events. const clipboardData = (event as ClipboardEvent).clipboardData ?? null if (clipboardData === null) return false - const files: File[] = [] - const directories = new Set() - for (const item of clipboardData.items) { - if (item.kind !== 'file') continue - const file = item.getAsFile() - if (file === null) continue - files.push(file) - if (typeof item.webkitGetAsEntry === 'function' && item.webkitGetAsEntry()?.isDirectory === true) { - directories.add(file) - } - } + const { files, directories } = clipboardFiles(clipboardData) if (files.length > 0) handlers.intakeFiles(files, directories.size === 0 ? undefined : directories) const text = clipboardData.getData('text/plain') if (text === '') { diff --git a/packages/client/ui-conversation/src/client/input/editor/projection.ts b/packages/client/ui-conversation/src/client/input/editor/projection.ts index dacc465d3b..4c3b246254 100644 --- a/packages/client/ui-conversation/src/client/input/editor/projection.ts +++ b/packages/client/ui-conversation/src/client/input/editor/projection.ts @@ -207,7 +207,11 @@ export function $projectComposer(idOf: (key: NodeKey) => number): EditorProjecti for (const segment of layout.segments) { if (segment.kind !== 'chip') continue if ($isQuoteNode(segment.node)) { - quotes.push({ offset: segment.clipboardStart, length: segment.clipboardLength, text: segment.node.getQuoteText() }) + const summary = segment.node.getQuoteSummary() + quotes.push({ + offset: segment.clipboardStart, length: segment.clipboardLength, text: segment.node.getQuoteText(), + ...(summary === undefined ? {} : { summary }), + }) continue } if (!$isReferenceChipNode(segment.node)) continue diff --git a/packages/client/ui-conversation/src/client/input/editor/runtime.ts b/packages/client/ui-conversation/src/client/input/editor/runtime.ts index f162943b6f..bed9912426 100644 --- a/packages/client/ui-conversation/src/client/input/editor/runtime.ts +++ b/packages/client/ui-conversation/src/client/input/editor/runtime.ts @@ -1,6 +1,7 @@ /** The Composer model's private Lexical editor, projections, and node operations. */ import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { LexicalEditor, NodeKey } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import { $addUpdateTag, $createParagraphNode, $createTextNode, $getAdjacentNode, $isTextNode, $getRoot, $getSelection, $getNodeByKey, $isRangeSelection, @@ -348,14 +349,15 @@ export class DraftEditorRuntime { * Insert one quote after the retained draft selection as an independent undo edit. * @param text - nonblank selected transcript text. * @param labels - current localized editor controls. + * @param summary - readable display shown instead of the text. * @returns whether the insertion position accepted the node. */ - insertQuote(text: string, labels: QuoteNodeLabels): boolean { + insertQuote(text: string, labels: QuoteNodeLabels, summary?: QuoteSummary): boolean { let applied = false this.applyEdit(() => { const projection = $projectComposer(key => this.occurrenceIdOf(key)) const at = projection.selection?.end ?? projection.detectText.length - applied = $replaceDetectSpanWithNodes({ start: at, end: at }, [$createQuoteNode(text, labels), $createTextNode(' ')]) + applied = $replaceDetectSpanWithNodes({ start: at, end: at }, [$createQuoteNode(text, labels, summary), $createTextNode(' ')]) }, PASTE_TAG) return applied } @@ -451,7 +453,7 @@ export class DraftEditorRuntime { const occurrence = span.value appendText(draft.slice(cursor, occurrence.offset)) if (span.kind === 'quote') { - paragraph.append($createQuoteNode(span.value.text, labels)) + paragraph.append($createQuoteNode(span.value.text, labels, span.value.summary)) cursor = occurrence.offset + occurrence.length continue } diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index cb8472f746..1fd208b6f7 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -14,6 +14,7 @@ import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' import type { LexicalEditor } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { CommandClaim, ConsumeTokenRequest, DraftAttachmentId, DraftInitializationOptions, DraftInitializationResult, InputActions, InputEffect, InputNotice, InputState, InputTriggerController, PickOutcome, @@ -100,12 +101,17 @@ function frozen(phase: InputState['phase']): boolean { } /** Whether two projections differ in content (selection and caret excluded). */ +function sameSummary(left: QuoteSummary | undefined, right: QuoteSummary | undefined): boolean { + return left === right || (left !== undefined && right !== undefined && left.label === right.label + && left.title === right.title && left.detail === right.detail && left.body === right.body) +} + function projectionContentChanged(prev: EditorProjection, next: EditorProjection): boolean { if (prev.clipboardText !== next.clipboardText || prev.detectText !== next.detectText) return true if (prev.command !== next.command) return true if (prev.quotes.length !== next.quotes.length || prev.quotes.some((quote, i) => { const old = next.quotes[i] - return old?.text !== quote.text || old.offset !== quote.offset + return old?.text !== quote.text || old.offset !== quote.offset || !sameSummary(old.summary, quote.summary) })) return true if (prev.occurrences.length !== next.occurrences.length) return true return next.occurrences.some((occ, i) => { @@ -140,7 +146,7 @@ export class SessionInputShell implements SessionInput { } /** The public provide-channel action face (one stable identity per session). */ readonly actions: InputActions = { - insertQuote: text => this.insertQuote(text), + insertQuote: (text, summary) => this.insertQuote(text, summary), captureInsertion: () => ({ ...this.caretSpan(), draftRev: this.rev }), insertText: (text, span) => { if (frozen(this.snapshot.phase) || this.disposed) return false @@ -230,10 +236,14 @@ export class SessionInputShell implements SessionInput { this.restoreCommand() } - /** @param text - selected transcript text. @returns whether the editable draft accepted the quote. */ - insertQuote(text: string): boolean { + /** + * @param text - selected transcript text. + * @param summary - readable composer display of the quote. + * @returns whether the editable draft accepted the quote. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean { if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.quoteInsertionAllowed?.() === false || text.trim() === '') return false - const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }) + const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary) if (inserted) this.focus() return inserted } diff --git a/packages/client/ui-conversation/src/client/input/file-intake.ts b/packages/client/ui-conversation/src/client/input/file-intake.ts new file mode 100644 index 0000000000..a46e9145a7 --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/file-intake.ts @@ -0,0 +1,99 @@ +/** + * Document-level paste routing across every mounted composer. + * + * A file paste outside an editable control addresses at most one composer: + * the one that most recently held focus while it can accept files, otherwise + * the main Conversation's composer while it can. A composer inside a hidden or + * inert subtree, or behind the foreground modal dialog or menu, is never + * addressed. + */ +import { modalSelector } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ComposerFileIntake, ComposerFileIntakeTarget } from '../contract/slots.ts' + +/** Controls that own their own paste; the document-level route never takes it from them. */ +const EDITABLE = 'input, textarea, select, [contenteditable]:not([contenteditable="false"])' + +/** + * Clipboard files in clipboard order, with members the entry API reports as directories. + * @param transfer - clipboard payload of one paste event. + * @returns the pasted files and their directory members; empty when the payload has no file item. + */ +export function clipboardFiles(transfer: DataTransfer): { files: File[]; directories: Set } { + const files: File[] = [] + const directories = new Set() + for (const item of transfer.items) { + if (item.kind !== 'file') continue + const file = item.getAsFile() + if (file === null) continue + files.push(file) + if (typeof item.webkitGetAsEntry === 'function' && item.webkitGetAsEntry()?.isDirectory === true) { + directories.add(file) + } + } + return { files, directories } +} + +/** + * Create the paste router shared by the composers of one plugin instance. + * Its document listeners exist only while at least one composer is registered. + * @returns the registration callback injected into each composer. + */ +export function createComposerFileIntake(): ComposerFileIntake { + const targets = new Set() + let focused: ComposerFileIntakeTarget | undefined + let uninstall: (() => void) | undefined + + const addressable = (document: Document): ComposerFileIntakeTarget[] => { + const foreground = [...document.querySelectorAll(modalSelector)].at(-1) + return [...targets].filter(target => target.card.isConnected + && target.card.closest('[inert], [hidden]') === null + && (foreground === undefined || foreground.contains(target.card))) + } + const pasteTarget = (document: Document): ComposerFileIntakeTarget | undefined => { + const candidates = addressable(document).filter(target => target.accepts()) + if (focused !== undefined && candidates.includes(focused)) return focused + return candidates.find(target => target.occurrence === 'main') + } + + const install = (document: Document): () => void => { + const focusin = (event: FocusEvent): void => { + // Document focusin events always target a node of this document. + const node = event.target as Node + const target = [...targets].find(candidate => candidate.card.contains(node)) + if (target !== undefined) focused = target + } + const paste = (event: ClipboardEvent): void => { + // A focused composer editor consumes its own paste before bubbling here. + if (event.defaultPrevented || event.clipboardData === null) return + // The first path element sees through shadow roots, which retarget event.target to their host. + const origin = event.composedPath().find(value => value instanceof Element) + if (origin instanceof Element && origin.closest(EDITABLE) !== null) return + const { files, directories } = clipboardFiles(event.clipboardData) + if (files.length === 0) return + const target = pasteTarget(document) + if (target === undefined) return + event.preventDefault() + target.add(files, directories.size === 0 ? undefined : directories) + } + document.addEventListener('focusin', focusin, true) + document.addEventListener('paste', paste) + return () => { + document.removeEventListener('focusin', focusin, true) + document.removeEventListener('paste', paste) + } + } + + return (target) => { + targets.add(target) + const document = target.card.ownerDocument + if (target.card.contains(document.activeElement)) focused = target + uninstall ??= install(document) + return () => { + targets.delete(target) + if (focused === target) focused = undefined + if (targets.size > 0) return + uninstall?.() + uninstall = undefined + } + } +} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 4c6b8e6578..5c5d1149f8 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -146,6 +146,7 @@ export function ConversationContent(props: ConversationContentProps) { const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', + occurrence: props.variant, ...(inert ? { disabled: true, diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 5b6407242d..f7957393d3 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -45,11 +45,11 @@ export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, - retryFileUpload, + retryFileUpload, registerFileIntake, toggleCommandMenu, stop, retry, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, useStopShortcut, useAccess, - useProjection, sessionId, variant, disabled: inert = false, blocked, + useProjection, sessionId, variant, occurrence, disabled: inert = false, blocked, workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { @@ -310,6 +310,17 @@ export const InputBar = memo(function InputBar({ return installDraftKeyboardDismissal(editor, cardRef) }, [editor]) + // A document paste outside an editable control addresses at most one + // mounted composer; the shared route elects it from focus and the main + // occurrence. + useEffect(() => registerFileIntake({ + // The card is an unconditional descendant attached before this effect. + card: cardRef.current as HTMLDivElement, + occurrence, + accepts: () => gate.current.canAcceptDrop, + add: (files, directories) => { gate.current.intakeFiles(files, directories) }, + }), [registerFileIntake, occurrence]) + // Button presses steal focus from the editor; suppress at mousedown so // typing continues seamlessly. Lexical's focus() carries preventScroll and // restores the previous selection, so no reveal is needed: the caret has diff --git a/packages/client/ui-conversation/tests/file-intake.client.spec.ts b/packages/client/ui-conversation/tests/file-intake.client.spec.ts new file mode 100644 index 0000000000..260005dc41 --- /dev/null +++ b/packages/client/ui-conversation/tests/file-intake.client.spec.ts @@ -0,0 +1,203 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { fireEvent } from '@testing-library/react' +import type { ComposerFileIntakeTarget } from '../src/client/contract/slots.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' + +/** One mounted Conversation: content region, transcript, and composer card. */ +function conversation(occurrence: 'main' | 'embedded', parent: HTMLElement = document.body) { + const content = document.createElement('div') + content.dataset.conversationContent = '' + const transcript = document.createElement('p') + const card = document.createElement('div') + card.dataset.composerCard = '' + const button = document.createElement('button') + card.append(button) + content.append(transcript, card) + parent.append(content) + const add = vi.fn() + let accepting = true + const target: ComposerFileIntakeTarget = { card, occurrence, accepts: () => accepting, add } + return { content, transcript, card, button, add, target, refuse: () => { accepting = false } } +} + +function filePayload(...files: File[]) { + return { + items: files.map(file => ({ kind: 'file', getAsFile: () => file })), + getData: () => '', + } +} + +const image = new File([Uint8Array.of(1)], 'shot.png', { type: 'image/png' }) + +const registrations: (() => void)[] = [] + +/** A fresh route whose registrations the suite releases after each case. */ +function createRoute(): ReturnType { + const register = createComposerFileIntake() + return (target) => { + const leave = register(target) + registrations.push(leave) + return leave + } +} + +afterEach(() => { + for (const leave of registrations.splice(0)) leave() + document.body.replaceChildren() +}) + +describe('composer paste route', () => { + it('routes an unaddressed paste to the main composer until another composer takes focus', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + const leaveMain = register(main.target) + const leaveSide = register(side.target) + + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(false) + expect(main.add).toHaveBeenCalledWith([image], undefined) + expect(side.add).not.toHaveBeenCalled() + + side.button.focus() + main.transcript.tabIndex = -1 + main.transcript.focus() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(side.add).toHaveBeenCalledTimes(1) + expect(main.add).toHaveBeenCalledTimes(1) + + leaveSide() + leaveSide() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(2) + leaveMain() + }) + + it('reports directory members and adopts a composer already holding focus at registration', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + side.button.focus() + register(main.target) + register(side.target) + const folder = new File([], 'folder') + const payload = { + items: [ + { kind: 'string', getAsFile: () => null }, + { kind: 'file', getAsFile: () => null }, + { kind: 'file', getAsFile: () => folder, webkitGetAsEntry: () => ({ isDirectory: true }) }, + { kind: 'file', getAsFile: () => image, webkitGetAsEntry: () => null }, + ], + getData: () => '', + } + fireEvent.paste(document.body, { clipboardData: payload }) + expect(side.add).toHaveBeenCalledWith([folder, image], new Set([folder])) + expect(main.add).not.toHaveBeenCalled() + }) + + it('leaves a paste to its editable control, an earlier handler, or the browser', () => { + const register = createRoute() + const main = conversation('main') + register(main.target) + const field = document.createElement('input') + const editable = document.createElement('div') + editable.setAttribute('contenteditable', 'true') + document.body.append(field, editable) + + expect(fireEvent.paste(field, { clipboardData: filePayload(image) })).toBe(true) + expect(fireEvent.paste(editable, { clipboardData: filePayload(image) })).toBe(true) + expect(fireEvent.paste(document.body, { clipboardData: { items: [], getData: () => 'text' } })).toBe(true) + expect(fireEvent.paste(document.body, { clipboardData: null })).toBe(true) + const handled = (event: Event): void => { event.preventDefault() } + document.body.addEventListener('paste', handled) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + document.body.removeEventListener('paste', handled) + expect(main.add).not.toHaveBeenCalled() + + main.refuse() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).not.toHaveBeenCalled() + }) + + it('never addresses a hidden, inert, detached, or modal-covered composer', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + register(main.target) + register(side.target) + side.button.focus() + + side.content.setAttribute('inert', '') + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(1) + side.content.removeAttribute('inert') + + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + document.body.append(menu) + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + menu.remove() + + const dialog = document.createElement('div') + dialog.setAttribute('role', 'dialog') + dialog.setAttribute('aria-modal', 'true') + const inside = conversation('embedded', dialog) + document.body.append(dialog) + register(inside.target) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(inside.add).not.toHaveBeenCalled() + inside.button.focus() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(inside.add).toHaveBeenCalledTimes(1) + dialog.remove() + + main.content.hidden = true + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + main.content.remove() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).toHaveBeenCalledTimes(1) + expect(side.add).not.toHaveBeenCalled() + }) + + it('skips a composer that cannot accept files for the main composer, and leaves the paste when none can', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + register(main.target) + register(side.target) + side.button.focus() + side.refuse() + + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(false) + expect(main.add).toHaveBeenCalledTimes(1) + expect(side.add).not.toHaveBeenCalled() + main.refuse() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).toHaveBeenCalledTimes(1) + }) + + it('leaves a paste to an editable control inside a shadow root', () => { + const register = createRoute() + const main = conversation('main') + register(main.target) + const host = document.createElement('div') + document.body.append(host) + const field = document.createElement('textarea') + host.attachShadow({ mode: 'open' }).append(field) + + expect(fireEvent.paste(field, { composed: true, clipboardData: filePayload(image) })).toBe(true) + expect(main.add).not.toHaveBeenCalled() + }) + + it('removes its document listeners with the last registration', () => { + const register = createRoute() + const main = conversation('main') + register(main.target)() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).not.toHaveBeenCalled() + const again = register(main.target) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(1) + again() + }) +}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 69499cdff4..630ad9e2cd 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -31,12 +31,13 @@ import type { SubmitOutcome } from '../src/client/contract/input.ts' import { SessionInputShell } from '../src/client/input/facade.ts' import { $replaceDetectSpanWithText, $selectDetectSpan } from '../src/client/input/editor/span-map.ts' import type { - ComposerAttachment, ComposerAttachmentsOwnerProps, DraftFileUploads, InputActivityOwnerProps, + ComposerAttachment, ComposerAttachmentsOwnerProps, ComposerFileIntake, DraftFileUploads, InputActivityOwnerProps, } from '../src/client/contract/slots.ts' import type { DraftAttachmentId } from '../src/client/contract/input.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { en, zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -95,6 +96,8 @@ interface BenchOptions { /** The hub's steer-all face (empty-draft accelerated Enter). */ steerQueue?: () => void variant?: 'hero' | 'composer' + occurrence?: 'main' | 'embedded' + registerFileIntake?: ComposerFileIntake placeholder?: string t?: InputBarProps['t'] accessory?: React.ReactNode @@ -213,6 +216,7 @@ function bench(over?: BenchOptions) { addFiles: over?.addFiles ?? (() => null), useFileUploads: bindSnapshotSelector(createSnapshotStore(over?.fileUploads ?? {})), retryFileUpload: undefined, + registerFileIntake: over?.registerFileIntake ?? createComposerFileIntake(), removeAttachment, resolveDraftAttachments: ids => ids.flatMap((id) => { const attachment = over?.attachments?.find(candidate => candidate.id === id) @@ -230,6 +234,7 @@ function bench(over?: BenchOptions) { t: over?.t ?? makeTranslate(zh, commonZh), renderSlot, variant: over?.variant ?? 'composer', + occurrence: over?.occurrence ?? 'main', ...(over?.inert === true ? { disabled: true } : {}), ...(over?.blocked !== undefined ? { blocked: over.blocked } : {}), ...(over?.workspacePickerOpen !== undefined ? { workspacePickerOpen: over.workspacePickerOpen } : {}), @@ -636,6 +641,31 @@ describe('image draft rail', () => { expect(within.view.queryByRole('alert')).toBeNull() }) + it('joins the paste route with its card and occurrence and routes pastes through its own intake', () => { + const leave = vi.fn() + const register = vi.fn(() => leave) + const addFiles = vi.fn(() => null) + const result = bench({ addFiles, registerFileIntake: register, occurrence: 'embedded' }) + expect(register).toHaveBeenCalledTimes(1) + const target = register.mock.calls[0]![0] + expect(target.card).toBe(result.view.container.querySelector('[data-composer-card]')) + expect(target.occurrence).toBe('embedded') + expect(target.accepts()).toBe(true) + const pasted = new File([Uint8Array.of(1)], 'pasted.png', { type: 'image/png' }) + act(() => { target.add([pasted]) }) + expect(addFiles).toHaveBeenCalledWith([pasted], undefined) + + // Acceptance follows live bar state without re-registering. + result.view.rerender( false} />) + expect(target.accepts()).toBe(false) + expect(register).toHaveBeenCalledTimes(1) + result.view.rerender() + expect(leave).toHaveBeenCalledTimes(1) + expect(register.mock.calls[1]![0].occurrence).toBe('main') + result.view.unmount() + expect(leave).toHaveBeenCalledTimes(2) + }) + it('announces the format problem before any limit when the batch holds a non-image', () => { const addFiles = vi.fn(() => '仅支持 PNG、JPG、WebP、GIF 格式的图片') const result = bench({ diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index a4963d15ac..dd7143f188 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -26,6 +26,7 @@ import { SessionInputShell } from '../src/client/input/facade.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -77,6 +78,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled addFiles: () => null, useFileUploads: bindSnapshotSelector(createSnapshotStore({})), retryFileUpload: undefined, + registerFileIntake: createComposerFileIntake(), removeAttachment: () => {}, // Every id resolves so the bar's registry prune never drops a test image. resolveDraftAttachments: ids => ids.map(id => ({ @@ -95,6 +97,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled stop: vi.fn(), t: makeTranslate(zh, commonZh), variant: 'composer', + occurrence: 'main', } return render() } diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 82c9ba4d56..aed6c05c2a 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -38,6 +38,7 @@ import { $replaceDetectSpanWithText } from '../src/client/input/editor/span-map. import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -179,6 +180,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo addFiles: () => null, useFileUploads: bindSnapshotSelector(createSnapshotStore({})), retryFileUpload: undefined, + registerFileIntake: createComposerFileIntake(), removeAttachment: () => {}, // Every id resolves so the bar's registry prune never drops a test image. resolveDraftAttachments: ids => ids.map(id => ({ @@ -206,6 +208,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo useStopShortcut: bindSnapshotSelector(createSnapshotStore([])), t: makeTranslate(zh, commonZh), variant: 'composer', + occurrence: 'main', } const view = render() const textarea = view.container.querySelector('[data-composer-input]')! diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index d365852fc0..8582f67e55 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -93,6 +93,54 @@ describe('QuoteNode composer lifecycle', () => { }) }) + it('shows an owner summary in place of the text while drafts, editor state, and the sent message keep the text', async () => { + const summary = { label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' } + const { shell, sink } = bench() + const mirrored: DraftSnapshot[] = [] + shell.bindDraftPersistence((document) => { mirrored.push(document) }) + expect(shell.actions.insertQuote(quote, summary)).toBe(true) + const persisted = mirrored.at(-1) + expect(persisted).toEqual({ text: '> selected source text ', references: [], quotes: [{ offset: 0, length: 22, text: quote, summary }] }) + const view = render() + expect(view.container.querySelector('[data-quote-preview-text]')?.textContent).toBe('index.ts L78src/index.ts L78 rename this') + view.unmount() + + const restored = bench().shell + restored.setDraft(persisted as DraftSnapshot) + expect(restored.draftSnapshot).toEqual(persisted) + const reparsed = restored.editor.parseEditorState(restored.editor.getEditorState().toJSON()) + expect(reparsed.read(() => $nodesOfType(QuoteNode).map(node => [node.getQuoteText(), node.getQuoteSummary()]))) + .toEqual([[quote, summary]]) + const plain = bench().shell + plain.insertQuote(quote) + expect(plain.editor.parseEditorState(plain.editor.getEditorState().toJSON()) + .read(() => $nodesOfType(QuoteNode).map(node => node.getQuoteSummary()))).toEqual([undefined]) + + shell.submit('queue') + expect(sink).toHaveBeenCalledWith('> selected source text', [], 'queue', expect.any(AbortSignal), expect.any(Function)) + await vi.waitFor(() => { expect(shell.snapshot.draft).toBe('') }) + }) + + it('treats a summary added or changed at the same text and offset as a draft change', () => { + const summary = { label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' } + const { shell } = bench() + const mirrored: DraftSnapshot[] = [] + shell.bindDraftPersistence((document) => { mirrored.push(document) }) + shell.insertQuote(quote) + const plain = shell.draftSnapshot + const revision = shell.snapshot.draftRev + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary }] }) + expect(shell.snapshot.draftRev).toBeGreaterThan(revision) + expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }]) + expect(mirrored.at(-1)?.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }]) + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] }) + expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this') + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] }) + expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this') + shell.setDraft(plain) + expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote }]) + }) + it('treats insert, close removal, Backspace, undo, and redo as whole-node operations', async () => { const direct = bench().shell direct.insertQuote(quote) diff --git a/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx b/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx index 1d88b71aee..0819ea3407 100644 --- a/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx @@ -15,6 +15,17 @@ describe('quote draft spans', () => { expect(parseStoredDraft({ ...draft, quotes: [quote, quote] })).toBeUndefined() }) + it('restores a stored quote summary and leaves summary-less drafts without one', () => { + const summary = { label: 'a.ts R1', title: 'src/a.ts', detail: 'R1', body: 'why' } + const draft = { text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote', summary }] } + expect(parseStoredDraft(JSON.parse(JSON.stringify(draft)))).toEqual(draft) + const { detail: _detail, ...withoutDetail } = summary + const brief = { ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: withoutDetail }] } + expect(parseStoredDraft(JSON.parse(JSON.stringify(brief)))).toEqual(brief) + expect(parseStoredDraft({ text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote' }] })?.quotes?.[0]?.summary).toBeUndefined() + expect(parseStoredDraft({ ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: { label: 'a.ts' } }] })).toBeUndefined() + }) + it('serializes reference owners outside quotes into ordinary Markdown text', async () => { const serialize = vi.fn(() => Promise.resolve('@[Session](dsh-session:id)')) const quote = '/review @literal' diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 2a099a7d7b..6f599b2d22 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -36,6 +36,7 @@ import type { ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, } from '../src/client/contract/slots.ts' import type { ViewTab } from '../src/client/contract/views.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every session-scope fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -313,6 +314,7 @@ function mount( addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} retryFileUpload={undefined} + registerFileIntake={createComposerFileIntake()} removeAttachment={() => {}} resolveDraftAttachments={() => []} toggleCommandMenu={vi.fn()} diff --git a/packages/client/ui-mcp-account/README.i18n.yaml b/packages/client/ui-mcp-account/README.i18n.yaml deleted file mode 100644 index 568293cbbf..0000000000 --- a/packages/client/ui-mcp-account/README.i18n.yaml +++ /dev/null @@ -1,52 +0,0 @@ -# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/client/ui-mcp-account/README.md -/: - en: 24bf21444e64d7bf - zh: 31bdd57111a6c094 -/deepseek-ai-dsh-client-ui-mcp-account: - en: bc4c3da94b874e94 - zh: 2c191170a5f5d4a0 -/deepseek-ai-dsh-client-ui-mcp-account/summary: - en: b82e447d4c945fd7 - zh: 2ee6c8834ea90d82 -/deepseek-ai-dsh-client-ui-mcp-account/table-of-contents: - en: d152484eb41ac6b4 - zh: 09388d293f9be9cb -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package: - en: eafab9a5fc35e4dd - zh: 787421f67536f779 -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package/register-an-account: - en: cceedbcd9e418af2 - zh: 7da8bddaa664c7ea -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package/what-the-page-shows: - en: 621f9d0e583e589c - zh: 39036f710eaa292e -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package/following-attempts: - en: ce4df6aa75d05535 - zh: d700f7f40cfba245 -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package/failures: - en: 6417c0db250bedd6 - zh: ed17f87e569c11b1 -/deepseek-ai-dsh-client-ui-mcp-account/use-this-package/shared-copy: - en: b0aac6746b7ff15e - zh: 2124a11b3c2b93db -/deepseek-ai-dsh-client-ui-mcp-account/understand-the-implementation: - en: 8410d2a9a8ec2059 - zh: 9e832e896462961e -/deepseek-ai-dsh-client-ui-mcp-account/further-exploration: - en: 85c4d99ffc871cc0 - zh: 900a989ad90b0472 -/deepseek-ai-dsh-client-ui-mcp-account/model-experience: - en: f9e28e1c8dda6810 - zh: b37cd6ac7eb039e7 -/deepseek-ai-dsh-client-ui-mcp-account/model-experience/kv-cache-effect: - en: 4cd0965a7997970e - zh: 690e5a9d945f7f6e -/deepseek-ai-dsh-client-ui-mcp-account/known-limitations-and-deferred-work: - en: 6127934af412594e - zh: 86dc74338eaf9edf -/deepseek-ai-dsh-client-ui-mcp-account/known-limitations-and-deferred-work/dev-note: - en: 5948fc04768b539f - zh: a7af9e91f3929547 diff --git a/packages/client/ui-mcp-account/README.md b/packages/client/ui-mcp-account/README.md deleted file mode 100644 index ec81d67fa5..0000000000 --- a/packages/client/ui-mcp-account/README.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -description: "Register an MCP connector's OAuth account on the Host with `ctx.mcpAccounts` and show its section, title tag, activation guidance, sign-out confirmation, and notices on the Plugins page through one `mcpAccounts` Remote, with the connector's own text and the shared copy of this package." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-mcp-account - -English | [中文](README.zh.md) - -## Summary - -Connector plugins that register an OAuth MCP server with the [MCP manager](../../mcp/mcp-manager/README.md) register its account on the Host with `ctx.mcpAccounts` to show it on the Web sidebar's **Plugins** page. The registry serves every account, with the manager's view of its server, through one `mcpAccounts` Remote. The browser half renders each account's section, title tag, activation guidance, and notices, and authorizes, cancels, signs out, and retries through the manager's Remote. Connectors supply the text that names their service as `LocalizedText`; the shared copy comes from this package's dictionary. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). - -## Table of Contents - -- [Use this package](#use-this-package) -- [Understand the implementation](#understand-the-implementation) -- [Further Exploration](#further-exploration) -- [Model Experience](#model-experience) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) -- [Dev Note](#dev-note) - ------ - - -## Use this package - -A connector's Host row registers its account once; the connector ships no browser code for the account. - -### Register an account - -The connector's Host row registers its account while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: - -```ts ignore-check -import type {} from '@deepseek-ai/dsh-client-ui-mcp-account' - -export function apply(ctx: Context): void { - ctx.inject(['mcpAccounts'], (scope) => { - scope.effect(() => scope.mcpAccounts.register({ server: 'docs', packageName: '@acme/docs', copy }), 'docs: Plugins page account') - }) -} -``` - -`server` is the name the connector registers with the MCP manager, and `packageName` is the npm package whose bundle page carries the section and tag; a second registration for the same package or server throws. `copy` holds every string that names the service: the section title, the Connect label, the activation guidance, the detail line of each state, the sign-out confirmation with what signing out removes, and the connection and sign-out notices. Each string is `LocalizedText`, which each browser resolves in its active language. The connector imports the registry's types with `import type`. The returned disposer withdraws the account from every page. - -### What the page shows - -| Section state | Action | -|---|---| -| Not connected, or the grant expired, no longer matches the server address or OAuth options, was rejected, or lacks permissions | Connect starts an authorization attempt | -| Waiting for you to confirm in the browser | The browser that started the attempt opens the authorization page once; Open authorization page opens it again, and Cancel ends the attempt | -| Connected | Sign out asks for confirmation, then deletes the local grant | -| Cannot connect right now | Retry restarts the server and keeps the existing grant; after incomplete cleanup only a Host restart recovers, so Retry is not offered | - -The tag beside the bundle title reports the same states while the bundle is enabled. Switching the bundle on while no account is connected offers to connect, which opens the bundle page and starts authorization. Leaving the page does not cancel an attempt, which the Host owns. - -### Following attempts - -Each browser opens one stream when the Web app loads. The browser that starts an attempt opens its authorization page once, only when the URL uses HTTPS or loopback HTTP, and reports the connection; other browsers show the same section but open no page and report no notice. An account the Host withdraws drops the attempt this browser followed. Clicks while an action is pending are ignored. - -### Failures - -A failed attempt shows an alert under the status line; a failed page action shows a toast, and the Host keeps the diagnostic. While the stream is not delivering, every action stays disabled. - -### Shared copy - -The `mcpAccount` dictionary holds the copy every account shares: the status lines and tags, the expired, mismatched, and unavailable details, the hint that authorization happens on the Host computer, the failure alert and notice, and the action labels. Every other string comes from the connector. - ------ - - -## Understand the implementation - -
-Implementation internals — click to expand - -The Host half, `McpAccounts`, is a Remote service that injects the MCP manager. `register()` stores the account, and each `watch` stream follows the manager's own `watch` stream: once the manager lists its servers, it yields every account with its server's view after each change of either, coalescing changes that arrive before the next read. It rethrows a failure of the manager's stream and ends with it. - -The browser half mounts the `mcpAccounts` Remote and opens one `watch` stream through `McpAccountsConnection`, which keeps one snapshot store per account: the Host entry, whether the stream is delivering, whether an action this browser started is pending, and the latest notice. Its actions call the manager's `startAuthorization`, `cancelAuthorization`, `signOut`, and `restart` with the account's server. For each account the Host reports, it registers `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, a `plugins.detail.badge` entry with id `.connection`, and a `shell.overlay` toast with id `.connection-toast`, all under the `mcpAccount` namespace and injecting one face. An account the Host drops loses its four entries, and unloading withdraws the entries and the stream before the Remote. - -| File | Role | -|---|---| -| [`src/index.ts`](src/index.ts) | The `ctx.mcpAccounts` registry and its Remote | -| [`src/types.ts`](src/types.ts) | The registration, copy, and stream item types | -| [`src/client/index.ts`](src/client/index.ts) | The browser entry bound to the generated Remote | -| [`src/client/mount.ts`](src/client/mount.ts) | The Remote mount, the dictionary, and the slot registrations of each account | -| [`src/client/connection.ts`](src/client/connection.ts) | The presentation, the stream mirror, authorization page opening, notices, and the pending-action guard | -| [`src/client/McpAccount.tsx`](src/client/McpAccount.tsx) | The four surfaces | -| [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | -| [`src/client/types.ts`](src/client/types.ts) | Snapshot, notice, and face types | - -
- ------ - - -## Further Exploration - -- [MCP manager](../../mcp/mcp-manager/README.md#oauth-authorization) — the `watch`, `startAuthorization`, `cancelAuthorization`, `signOut`, and `restart` operations behind the page. -- [Plugins page](../ui-plugin-manager/README.md#use-this-package) — the bundle page slots this package registers into. -- [MCP subsystem](../../../docs/subsystems/mcp.md) — how the MCP packages fit together. -- [Client package map](../README.md) — adjacent browser UI packages. - ------ - - -## Model Experience - -None, as the registry and its surfaces are Plugins page UI and add no model input. The connector's naming guidance and the server's tools are documented by the connector and the [MCP client](../../mcp/mcp-client/README.md#model-experience). - -#### KV Cache effect - -None; registering or removing an account changes no model-visible text. - -## Known Limitations and Deferred Work - - - -- The section exists only while the connector plugin is on. To sign out after turning the plugin off, turn it on again or delete the grant record. -- A connector whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. -- The authorization callback is the Host web server's own origin, so the browser that completes authorization must reach that server directly, not through a proxy or the Web app's `publicUrl`. -- One grant serves each server on the Host; there is no account picker. -- The Web and Desktop compositions load the registry whether or not a connector is installed. - - -### Dev Note - -
-Working context for maintainers — click to expand - -Host specs drive the registry with a fake manager stream. Client specs drive `McpAccountsConnection` with a fake Remote stream, render the surfaces with a key-echo translator and Chinese connector text, and mount the browser half against a real slot registry and locale runtime. Source coverage excludes `src/client/index.ts`, which imports the generated Remote that exists only in `lib/`. - -
diff --git a/packages/client/ui-mcp-account/README.zh.md b/packages/client/ui-mcp-account/README.zh.md deleted file mode 100644 index 209bc3d2b2..0000000000 --- a/packages/client/ui-mcp-account/README.zh.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -description: "通过 `ctx.mcpAccounts` 在 Host 上注册 MCP 连接器的 OAuth 账号,并经由一个 `mcpAccounts` Remote 在插件页面显示其账号区块、标题标签、开启后的引导、退出登录确认与提示,文案来自连接器自己的文本和本包的共用文案。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-client-ui-mcp-account - -[English](README.md) | 中文 - -## 概述 - -向 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)注册 OAuth MCP 服务器的连接器插件,在 Host 上通过 `ctx.mcpAccounts` 注册账号,使其显示在 Web 侧栏的**插件**页面上。注册表通过一个 `mcpAccounts` Remote 提供所有账号,并附上管理器对各自服务器的视图。浏览器一侧渲染每个账号的区块、标题标签、开启后的引导和提示,并通过管理器的 Remote 完成授权、取消、退出登录和重试。连接器以 `LocalizedText` 提供指明其服务的文案;共用文案来自本包的字典。Web 与 Desktop 组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两侧。 - -## 目录 - -- [使用本包](#use-this-package) -- [理解实现](#understand-the-implementation) -- [进一步探索](#further-exploration) -- [模型体验](#model-experience) -- [已知限制与延期工作](#known-limitations-and-deferred-work) -- [开发备注](#dev-note) - ------ - - -## 使用本包 - -连接器的 Host 行注册一次账号;连接器不为账号提供任何浏览器代码。 - -### 注册账号 - -连接器的 Host 行在注册表运行时注册账号,因此没有注册表的组合(如 headless profile)会跳过注册: - -```ts ignore-check -import type {} from '@deepseek-ai/dsh-client-ui-mcp-account' - -export function apply(ctx: Context): void { - ctx.inject(['mcpAccounts'], (scope) => { - scope.effect(() => scope.mcpAccounts.register({ server: 'docs', packageName: '@acme/docs', copy }), 'docs: Plugins page account') - }) -} -``` - -`server` 是连接器向 MCP 管理器注册的名称,`packageName` 是承载区块和标签的 bundle 所属 npm 包;同一个包或服务器的第二次注册会抛出错误。`copy` 包含所有指明该服务的文案:区块标题、连接按钮文字、开启后的引导、各状态的说明行、包含退出登录会删除什么的退出确认,以及连接成功与退出登录的提示。每条文案都是 `LocalizedText`,由各浏览器按当前语言解析。连接器用 `import type` 引入注册表的类型。返回的释放函数从所有页面撤下该账号。 - -### 页面显示什么 - -| 区块状态 | 操作 | -|---|---| -| 未连接,或授权已过期、与服务器地址或 OAuth 选项不再匹配、被拒绝、缺少权限 | 连接操作发起一次授权尝试 | -| 等待你在浏览器中确认 | 发起尝试的浏览器打开一次授权页面;**打开授权页面**再次打开,**取消**结束这次尝试 | -| 已连接 | **退出登录**确认后删除本地 grant | -| 暂时无法连接 | **重试**重启服务器并保留现有授权;清理未完成时只有重启宿主才能恢复,因此不提供**重试** | - -bundle 开启期间,标题旁的标签报告同样的状态。在尚未连接账号时开启 bundle,页面提示连接,点击后打开 bundle 详情页并发起授权。离开页面不会取消授权尝试,尝试由 Host 持有。 - -### 跟随授权尝试 - -每个浏览器在 Web 应用加载时打开一条流。发起尝试的浏览器把授权页面打开一次,且只在 URL 使用 HTTPS 或回环地址上的 HTTP 时打开,并报告连接结果;其他浏览器显示同样的区块,但不打开页面,也不报告提示。Host 撤下账号时,本浏览器放弃所跟随的尝试。操作未完成时的点击会被忽略。 - -### 失败 - -授权尝试失败时,状态行下方显示提示;页面操作失败时显示 toast,诊断信息留在 Host。流未在传送时,所有操作保持禁用。 - -### 共用文案 - -`mcpAccount` 字典包含所有账号共用的文案:状态行和标签、授权过期、不再匹配与暂时无法连接的说明、授权需在 Host 所在电脑上完成的提示、失败提示与失败 toast,以及各操作的文字。其余文案都来自连接器。 - ------ - - -## 理解实现 - -
-实现内部机制——点击展开 - -Host 一侧的 `McpAccounts` 是注入 MCP 管理器的 Remote 服务。`register()` 保存账号,每条 `watch` 流跟随管理器自己的 `watch` 流:管理器列出服务器后,在任一方每次变化后产出所有账号及其服务器的视图,并合并在下一次读取前到达的变化。管理器的流失败时它重新抛出该错误,管理器的流结束时它随之结束。 - -浏览器一侧挂载 `mcpAccounts` Remote,并通过 `McpAccountsConnection` 打开一条 `watch` 流,为每个账号保存一个快照 store:Host 条目、流是否在传送、本浏览器发起的操作是否未完成,以及最新提示。它的操作以账号的服务器调用管理器的 `startAuthorization`、`cancelAuthorization`、`signOut` 与 `restart`。对 Host 报告的每个账号,它注册以包名为 key 的 `plugins.bundle.config` 与 `plugins.bundle.activation`、id 为 `.connection` 的 `plugins.detail.badge` 条目,以及 id 为 `.connection-toast` 的 `shell.overlay` toast,全部使用 `mcpAccount` 命名空间并注入同一个 face。Host 撤下的账号会失去这四个条目;卸载时先撤下条目和流,再撤下 Remote。 - -| 文件 | 职责 | -|---|---| -| [`src/index.ts`](src/index.ts) | `ctx.mcpAccounts` 注册表及其 Remote | -| [`src/types.ts`](src/types.ts) | 注册、文案和流条目类型 | -| [`src/client/index.ts`](src/client/index.ts) | 绑定生成的 Remote 的浏览器入口 | -| [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、字典,以及每个账号的插槽注册 | -| [`src/client/connection.ts`](src/client/connection.ts) | 显示状态推导、流的镜像、授权页面打开、提示和未完成操作保护 | -| [`src/client/McpAccount.tsx`](src/client/McpAccount.tsx) | 四个界面 | -| [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | -| [`src/client/types.ts`](src/client/types.ts) | 快照、提示和 face 类型 | - -
- ------ - - -## 进一步探索 - -- [MCP 管理器](../../mcp/mcp-manager/README.zh.md#oauth-authorization) — 页面背后的 `watch`、`startAuthorization`、`cancelAuthorization`、`signOut` 与 `restart` 操作。 -- [插件页面](../ui-plugin-manager/README.zh.md#use-this-package) — 本包注册所用的 bundle 详情页插槽。 -- [MCP 子系统](../../../docs/subsystems/mcp.zh.md) — MCP 各包如何协作。 -- [Client 包地图](../README.zh.md) — 相邻的浏览器 UI 包。 - ------ - - -## 模型体验 - -无。注册表及其界面属于插件页面 UI,不增加任何模型输入。连接器的命名引导与服务器工具由连接器和 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)说明。 - -#### KV Cache 影响 - -无;注册或移除账号不改变任何模型可见文本。 - -## 已知限制与延期工作 - - - -- 区块只在连接器插件开启期间存在。关闭插件后要退出登录,需要重新开启插件,或删除 grant 记录。 -- Host 行加载失败的连接器不显示账号区块;插件页面仍列出该 bundle 及其加载失败。 -- 授权回调地址是 Host Web 服务器自身的源地址,因此完成授权的浏览器必须直接访问该服务器,不能经过代理或 Web 应用的 `publicUrl`。 -- Host 上每个服务器只使用一份 grant;没有账号选择器。 -- 无论是否安装了连接器,Web 与 Desktop 组合都会加载注册表。 - - -### 开发备注 - -
-维护者工作上下文——点击展开 - -Host 测试用模拟的管理器流驱动注册表。客户端测试用模拟的 Remote 流驱动 `McpAccountsConnection`,用回显 key 的翻译函数和中文的连接器文案渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一侧。源码覆盖率排除 `src/client/index.ts`,因为它引入只存在于 `lib/` 中的生成 Remote。 - -
diff --git a/packages/client/ui-mcp-account/src/client/McpAccount.tsx b/packages/client/ui-mcp-account/src/client/McpAccount.tsx deleted file mode 100644 index ffdb6714b8..0000000000 --- a/packages/client/ui-mcp-account/src/client/McpAccount.tsx +++ /dev/null @@ -1,145 +0,0 @@ -/** One account's surfaces on the Plugins page: the bundle section, title tag, activation guidance, and notices. */ -import { useEffect, useState, type ReactNode } from 'react' -import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' -import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { McpAccountCopy } from '../types.ts' -import { presentConnection, type ConnectionPresentation } from './connection.ts' -import type { McpAccountKey } from './locales.ts' -import css from './McpAccount.module.css' -import type { McpAccountFace } from './types.ts' - -type Phase = ConnectionPresentation['phase'] -type FaceProps = InjectFace & { t: Translate } - -const TONE: Record = { - 'checking': 'ongoing', 'connecting': 'ongoing', 'authorizing': 'ongoing', 'waiting-browser': 'ongoing', - 'connected': 'done', 'disconnected': 'idle', 'reconnect': 'warning', 'unavailable': 'error', -} - -const BADGE: Record = { - 'checking': undefined, - 'connecting': ['badge.connecting', 'info'], 'authorizing': ['badge.connecting', 'info'], 'waiting-browser': ['badge.connecting', 'info'], - 'connected': ['badge.connected', 'success'], 'disconnected': ['badge.disconnected', 'outline'], - 'reconnect': ['badge.reconnect', 'warning'], 'unavailable': ['badge.unavailable', 'danger'], -} - -/** The detail line of a phase: the connector's text where it names the service, the shared copy otherwise. */ -function detail(shown: ConnectionPresentation, copy: McpAccountCopy, t: Translate, resolveText: FaceProps['resolveText']): string | undefined { - switch (shown.phase) { - case 'checking': return undefined - case 'reconnect': - switch (shown.reason) { - case 'rejected': return resolveText(copy.detail.rejected) - case 'scope': return resolveText(copy.detail.scope) - default: return t(`detail.reconnect.${shown.reason}`) - } - case 'unavailable': return t('detail.unavailable') - case 'waiting-browser': return resolveText(copy.detail.waitingBrowser) - default: return resolveText(copy.detail[shown.phase]) - } -} - -/** - * The account section on the connector bundle's page. - * @param props - the account face and the shared dictionary. - * @returns the status line, its actions, and the sign-out confirmation. - */ -export function McpAccountSection(props: FaceProps): ReactNode { - const { useMcpAccount, resolveText, connect, cancel, signOut, retry, openAuthorization, t } = props - const snapshot = useMcpAccount(value => value) - const [confirming, setConfirming] = useState(false) - const { copy } = snapshot.entry - const shown = presentConnection(snapshot.entry.view) - const disabled = snapshot.busy || !snapshot.linked - const line = detail(shown, copy, t, resolveText) - const action = (label: string, onClick: () => void, variant: 'primary' | 'outline' | 'ghost' = 'outline'): ReactNode => - - const actions: ReactNode[] = [] - switch (shown.phase) { - case 'disconnected': actions.push(action(resolveText(copy.connect), connect, 'primary')); break - case 'reconnect': actions.push(action(t('action.reconnect'), connect, 'primary')); break - case 'waiting-browser': actions.push(action(t('action.open'), openAuthorization, 'primary'), action(t('action.cancel'), cancel, 'ghost')); break - case 'authorizing': actions.push(action(t('action.cancel'), cancel, 'ghost')); break - case 'connected': actions.push(action(t('action.signOut'), () => { setConfirming(true) })); break - case 'unavailable': if (shown.retryable) actions.push(action(t('action.retry'), retry)); break - case 'checking': - case 'connecting': break - } - return ( -
-

{resolveText(copy.title)}

-
- - {t(`status.${shown.phase}`)} -
{actions}
-
- {line === undefined ? null :

{line}

} - {'failed' in shown && shown.failed ?

{t('failed')}

: null} -

{t('hostBrowser')}

- { setConfirming(false) }} - footer={<> - - - }> -

{resolveText(copy.signOut.body)}

-
-
- ) -} - -/** - * The account tag beside the connector bundle's title. - * @param props - the open detail page's subject, the account face, and the shared dictionary. - * @returns the tag for the connector bundle, or null on any other page. - */ -export function McpAccountBadge({ subject, packageName, useMcpAccount, t }: FaceProps & PropsRuntime<'plugins.detail.badge'>): ReactNode { - const phase = useMcpAccount(value => presentConnection(value.entry.view).phase) - if (subject.kind !== 'bundle' || subject.pkg.name !== packageName || !subject.pkg.enabled) return null - const badge = BADGE[phase] - return badge === undefined ? null : {t(badge[0])} -} - -/** - * Guidance after the user switches the connector bundle on while no account is connected. - * @param props - activation callbacks, the account face, and the shared dictionary. - * @returns a dismissible prompt that starts authorization from the bundle's page. - */ -export function McpAccountActivation(props: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode { - const { useMcpAccount, resolveText, connect, onDismiss, onOpenDetails, t } = props - const phase = useMcpAccount(value => presentConnection(value.entry.view).phase) - const copy = useMcpAccount(value => value.entry.copy) - const needed = phase === 'disconnected' || phase === 'reconnect' - useEffect(() => { - // A first connection attempt may still end in a state that needs the guidance. - if (phase !== 'checking' && phase !== 'connecting' && !needed) onDismiss() - }, [phase, needed, onDismiss]) - return ( - - - - }> -

{resolveText(copy.activation.body)}

-
- ) -} - -/** - * Connection outcomes reported outside the Plugins panel's lifetime. - * @param props - the account's notice, its dismissal, and the dictionaries. - * @returns the toast for the latest notice, or null. - */ -export function McpAccountToast({ useMcpAccount, resolveText, dismissNotice, t }: FaceProps): ReactNode { - const notice = useMcpAccount(value => value.notice) - const copy = useMcpAccount(value => value.entry.copy) - if (notice === undefined) return null - switch (notice.kind) { - case 'action-failed': return } onDone={dismissNotice} /> - case 'connected': return - case 'signed-out': return - /* v8 ignore next -- closed notice kind union */ - default: return assertNever(notice.kind) - } -} diff --git a/packages/client/ui-mcp-account/src/client/connection.ts b/packages/client/ui-mcp-account/src/client/connection.ts deleted file mode 100644 index 6d1035e52f..0000000000 --- a/packages/client/ui-mcp-account/src/client/connection.ts +++ /dev/null @@ -1,251 +0,0 @@ -/** Browser mirror of the registered connector accounts and the Plugins page's account actions. */ -import type { Context } from '@deepseek-ai/cordis' -import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' -import type { McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' -import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { McpAuthorizationReason, McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { McpAccountEntry, McpAccountsView } from '../types.ts' -import type { McpAccountFace, McpAccountNotice, McpAccountSnapshot } from './types.ts' - -/** What the user sees about the connection, derived from the Host entry alone. */ -export type ConnectionPresentation = - | { readonly phase: 'checking' | 'connected' | 'connecting' } - | { readonly phase: 'waiting-browser'; readonly attempt: McpOAuthAttemptId; readonly url: string | undefined } - | { readonly phase: 'authorizing'; readonly attempt: McpOAuthAttemptId } - | { readonly phase: 'disconnected'; readonly failed: boolean } - | { readonly phase: 'reconnect'; readonly reason: Exclude; readonly failed: boolean } - | { readonly phase: 'unavailable'; readonly failed: boolean; readonly retryable: boolean } - -function attemptPresentation(attempt: McpOAuthAttemptView): ConnectionPresentation | undefined { - switch (attempt.phase) { - case 'waiting-browser': return { phase: 'waiting-browser', attempt: attempt.id, url: attempt.authorizationUrl } - case 'starting': - case 'exchanging': - case 'committing': return { phase: 'authorizing', attempt: attempt.id } - case 'authorized': - case 'cancelled': - case 'failed': return undefined - /* v8 ignore next -- closed attempt phase union */ - default: return assertNever(attempt.phase) - } -} - -/** - * Derive the connection the page shows from the manager's entry for the server. - * @param server - the entry as the manager last reported it. - * @returns the phase, with the active attempt or the reason a new authorization is needed. - */ -export function presentConnection(server: McpManagedServerView | undefined): ConnectionPresentation { - if (server === undefined) return { phase: 'checking' } - const attempt = server.authorization - const active = attempt === undefined ? undefined : attemptPresentation(attempt) - if (active !== undefined) return active - const failed = attempt?.phase === 'failed' - const status = server.status - switch (status.state) { - case 'connected': return { phase: 'connected' } - case 'connecting': - case 'reconnecting': return { phase: 'connecting' } - case 'waiting-authorization': - return status.reason === 'missing' ? { phase: 'disconnected', failed } : { phase: 'reconnect', reason: status.reason, failed } - case 'closed': return { phase: 'unavailable', failed, retryable: true } - // A credential update or re-enabling the entry recovers these; a restart does not. - case 'waiting-credentials': - case 'disabled': return { phase: 'unavailable', failed, retryable: false } - // Only a Host restart recovers incomplete cleanup. - case 'failed': return { phase: 'unavailable', failed, retryable: status.reason !== 'cleanup' && status.reason !== 'unclosed-generation' } - /* v8 ignore next -- closed managed status union */ - default: return assertNever(status) - } -} - -function openable(url: string): boolean { - if (!URL.canParse(url)) return false - const parsed = new URL(url) - return parsed.protocol === 'https:' - || (parsed.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname)) -} - -function openAuthorizationPage(url: string | undefined): void { - if (url !== undefined && openable(url)) window.open(url, '_blank', 'noopener,noreferrer') -} - -async function settle(call: Promise>): Promise { - const result = await call - if (!result.ok) throw new Error(result.error.message) - return result.value -} - -/** The registry stream the mirror follows. */ -export interface McpAccountsRemote { - watch(signal: AbortSignal): AsyncIterable -} - -/** The manager's account actions the page runs. */ -export interface McpServersRemote { - startAuthorization(server: string): Promise> - cancelAuthorization(server: string, id: McpOAuthAttemptId): Promise> - signOut(server: string): Promise> - restart(server: string): Promise> -} - -/** One Host subscription per browser, shared by every account surface on the Plugins page. */ -export class McpAccountsConnection { - /** Each registered account's snapshot source by bundle package, republished when the Host adds or removes an account. */ - readonly accounts: SnapshotStore>> = - createSnapshotStore>>(new Map()) - - private readonly stores = new Map>() - /** The attempt each account's latest connect in this browser started; only its authorization page opens here. */ - private readonly started = new Map() - private readonly opened = new Set() - private seq = 0 - private disposed = false - private readonly stream: RemoteStream - private readonly observing: Promise - - /** - * @param ctx - the browser context carrying the Remote client. - * @param registry - the `mcpAccounts` Remote. - * @param servers - the manager's `mcpManager` Remote. - */ - constructor(ctx: Context, registry: McpAccountsRemote, private readonly servers: McpServersRemote) { - this.stream = ctx.remote.$stream({ - name: 'MCP accounts', open: signal => registry.watch(signal), - ended: () => new Error('MCP accounts stream ended'), - carrierFailed: () => { this.setLinked(false) }, - }) - this.observing = this.observe() - } - - /** - * Bind one account's page actions; each runs without awaiting so slot handlers stay synchronous. - * @param packageName - the account's bundle package. - * @returns the actions a surface entry injects. - */ - actions(packageName: string): Pick { - return { - connect: () => { void this.connect(packageName) }, - cancel: () => { void this.cancel(packageName) }, - signOut: () => { - void this.run(packageName, async (server) => { - await settle(this.servers.signOut(server)) - this.notify(packageName, 'signed-out') - }) - }, - retry: () => { void this.run(packageName, async (server) => { await settle(this.servers.restart(server)) }) }, - openAuthorization: () => { - const shown = presentConnection(this.stores.get(packageName)?.getSnapshot().entry.view) - if (shown.phase === 'waiting-browser') openAuthorizationPage(shown.url) - }, - dismissNotice: () => { this.patch(packageName, { notice: undefined }) }, - } - } - - /** - * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned attempts keep running. - * @returns after the stream closes. - */ - async dispose(): Promise { - this.disposed = true - await this.stream.dispose() - await this.observing - } - - private async observe(): Promise { - try { - for await (const item of this.stream) { - // An item the stream yielded just before disposal must not reach the disposed page. - if (this.disposed) return - this.show(item.value.accounts) - item.accept() - } - } catch { - // The carrier already reported the failure; a disposed page has nothing left to show. - if (!this.disposed) this.setLinked(false) - } - } - - private show(entries: readonly McpAccountEntry[]): void { - const names = new Set(entries.map(entry => entry.packageName)) - let changed = false - for (const packageName of [...this.stores.keys()]) { - if (names.has(packageName)) continue - this.stores.delete(packageName) - this.started.delete(packageName) - changed = true - } - for (const entry of entries) { - const store = this.stores.get(entry.packageName) - if (store === undefined) { - this.stores.set(entry.packageName, createSnapshotStore({ entry, linked: true, busy: false, notice: undefined })) - changed = true - } else { - store.set({ ...store.getSnapshot(), entry, linked: true }) - } - this.follow(entry) - } - if (changed) this.accounts.set(new Map(this.stores)) - } - - /** Open the authorization page of the attempt this browser started once, and report its outcome. */ - private follow(entry: McpAccountEntry): void { - const attempt = entry.view?.authorization - if (attempt === undefined || attempt.id !== this.started.get(entry.packageName)) return - if (attempt.phase === 'waiting-browser' && !this.opened.has(attempt.id)) { - this.opened.add(attempt.id) - openAuthorizationPage(attempt.authorizationUrl) - } - if (attempt.phase === 'authorized') this.notify(entry.packageName, 'connected') - if (attempt.phase === 'authorized' || attempt.phase === 'cancelled' || attempt.phase === 'failed') this.started.delete(entry.packageName) - } - - private async connect(packageName: string): Promise { - await this.run(packageName, async (server) => { - const attempt = await settle(this.servers.startAuthorization(server)) - const current = this.stores.get(packageName)?.getSnapshot().entry - // A disposed page or an account the Host withdrew meanwhile follows nothing. - if (this.disposed || current === undefined) return - this.started.set(packageName, attempt.id) - // The stream may have reported this attempt before the call answered. - this.follow(current) - }) - } - - private async cancel(packageName: string): Promise { - const shown = presentConnection(this.stores.get(packageName)?.getSnapshot().entry.view) - if (shown.phase !== 'waiting-browser' && shown.phase !== 'authorizing') return - await this.run(packageName, async (server) => { await settle(this.servers.cancelAuthorization(server, shown.attempt)) }) - } - - private async run(packageName: string, operation: (server: string) => Promise): Promise { - const snapshot = this.stores.get(packageName)?.getSnapshot() - if (snapshot === undefined || snapshot.busy) return - this.patch(packageName, { busy: true }) - try { - await operation(snapshot.entry.server) - } catch { - // The Host keeps the diagnostic; the page reports one retryable outcome. - this.notify(packageName, 'action-failed') - } finally { - this.patch(packageName, { busy: false }) - } - } - - private setLinked(linked: boolean): void { - for (const packageName of this.stores.keys()) this.patch(packageName, { linked }) - } - - private patch(packageName: string, change: Partial): void { - const store = this.stores.get(packageName) - if (store !== undefined) store.set({ ...store.getSnapshot(), ...change }) - } - - private notify(packageName: string, kind: McpAccountNotice['kind']): void { - if (this.disposed) return - this.seq += 1 - this.patch(packageName, { notice: { seq: this.seq, kind } }) - } -} diff --git a/packages/client/ui-mcp-account/src/client/index.ts b/packages/client/ui-mcp-account/src/client/index.ts deleted file mode 100644 index a0f94d3633..0000000000 --- a/packages/client/ui-mcp-account/src/client/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * MCP account surfaces, browser half: follows the accounts connector plugins register on the Host and shows each one's - * section, title tag, activation guidance, and notices on its bundle's Plugins page. The surfaces read the shared copy - * from this package's dictionary and each connector's text from the Host. - */ -import type { Context } from '@deepseek-ai/cordis' -import mcpAccountsRemote from '@deepseek-ai/dsh-client-ui-mcp-account/remote' -import { mountMcpAccounts } from './mount.ts' - -export { inject } from './mount.ts' -export type { McpAccountKey } from './locales.ts' -export type { McpAccountFace, McpAccountNotice, McpAccountSnapshot } from './types.ts' - -/** - * Show the registered connector accounts on the Plugins page. - * @param ctx - the browser plugin context. - * @returns a disposer that withdraws the surfaces and the stream, then the Remote. - */ -export async function apply(ctx: Context): Promise<() => Promise> { - return mountMcpAccounts(ctx, mcpAccountsRemote) -} diff --git a/packages/client/ui-mcp-account/src/client/mount.ts b/packages/client/ui-mcp-account/src/client/mount.ts deleted file mode 100644 index d42f955cb8..0000000000 --- a/packages/client/ui-mcp-account/src/client/mount.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** Mount the `mcpAccounts` Remote and show the surfaces of each account the Host registers, for one plugin lifetime. */ -import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-api-remotes/client' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' -import type {} from '@deepseek-ai/dsh-client-locale/client' -import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -import type {} from '@deepseek-ai/dsh-client-ui-mcp-account/remote' -import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' -import { McpAccountsConnection } from './connection.ts' -import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' -import { McpAccountActivation, McpAccountBadge, McpAccountSection, McpAccountToast } from './McpAccount.tsx' -import type { McpAccountFace, McpAccountSnapshot } from './types.ts' - -/** Services the Remote mount and the slot registrations need. */ -export const inject = ['remote', 'slots', 'locale'] - -function registerAccount( - ctx: Context, connection: McpAccountsConnection, packageName: string, store: SnapshotStore, -): () => void { - const { server } = store.getSnapshot().entry - const face: McpAccountFace = { - hooks: { mcpAccount: store }, packageName, resolveText: text => ctx.locale.resolveText(text), ...connection.actions(packageName), - } - const dispose = ctx.effect(function* () { - yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ - name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => face, - }, McpAccountSection)) - yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ - name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => face, - }, McpAccountActivation)) - yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ - name: 'plugins.detail.badge', id: `${server}.connection`, locale: NS, inject: () => face, - }, McpAccountBadge)) - yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ - name: 'shell.overlay', id: `${server}.connection-toast`, locale: NS, inject: () => face, - }, McpAccountToast)) - }, `mcpAccounts: ${packageName}`) - return () => void dispose() -} - -function showAccounts(ctx: Context): void { - ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'mcp-account: dictionaries') - const connection = new McpAccountsConnection(ctx, ctx.remote.mcpAccounts, ctx.remote.mcpManager) - ctx.effect(() => async () => { await connection.dispose() }, 'mcp-account: connection') - ctx.effect(() => { - const shown = new Map void>() - const sync = (): void => { - const accounts = connection.accounts.getSnapshot() - for (const [name, withdraw] of shown) { - if (accounts.has(name)) continue - withdraw() - shown.delete(name) - } - for (const [name, store] of accounts) if (!shown.has(name)) shown.set(name, registerAccount(ctx, connection, name, store)) - } - sync() - const stop = connection.accounts.subscribe(sync) - return () => { - stop() - for (const withdraw of shown.values()) withdraw() - } - }, 'mcp-account: surfaces') -} - -/** - * Mount the `mcpAccounts` Remote, then show the registered accounts for the same plugin lifetime. - * @param ctx - the browser plugin context. - * @param contribution - the generated `mcpAccounts` Remote definitions the built entry supplies. - * @returns a disposer that withdraws the surfaces and the stream before the Remote. - */ -export async function mountMcpAccounts(ctx: Context, contribution: TypertRemoteContribution): Promise<() => Promise> { - const unmount = await ctx.remote.$mount(contribution) - const ui = ctx.inject(['remote.mcpAccounts', 'remote.mcpManager', 'slots', 'locale'], showAccounts) - try { await ui } catch (error) { await ui.dispose(); await unmount(); throw error } - return async () => { await ui.dispose(); await unmount() } -} diff --git a/packages/client/ui-mcp-account/src/client/types.ts b/packages/client/ui-mcp-account/src/client/types.ts deleted file mode 100644 index e360478ef7..0000000000 --- a/packages/client/ui-mcp-account/src/client/types.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Browser-side state and face of the connector accounts the Plugins page shows. */ -import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' -import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import type { McpAccountEntry } from '../types.ts' - -/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ -export interface McpAccountNotice { - readonly seq: number - readonly kind: 'connected' | 'signed-out' | 'action-failed' -} - -/** One account as this browser shows it: the Host's entry plus the stream state, pending action, and notice. */ -export interface McpAccountSnapshot { - readonly entry: McpAccountEntry - /** Whether the Host stream is delivering. */ - readonly linked: boolean - /** Whether an action this browser started for the account has not settled. */ - readonly busy: boolean - readonly notice: McpAccountNotice | undefined -} - -/** The face every surface entry of one account injects. */ -export interface McpAccountFace { - hooks: { mcpAccount: HostObservable } - readonly packageName: string - /** Pick the active language's entry of the connector's text. */ - readonly resolveText: (text: LocalizedText) => string - readonly connect: () => void - readonly cancel: () => void - readonly signOut: () => void - readonly retry: () => void - readonly openAuthorization: () => void - readonly dismissNotice: () => void -} diff --git a/packages/client/ui-mcp-account/src/index.ts b/packages/client/ui-mcp-account/src/index.ts deleted file mode 100644 index 82a40c3ae5..0000000000 --- a/packages/client/ui-mcp-account/src/index.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * MCP account surfaces, Host half. Connector plugins register their OAuth server's account with `ctx.mcpAccounts`; the - * Plugins page follows every registered account, with the MCP manager's view of its server, through the `mcpAccounts` - * Remote, and authorizes, cancels, signs out, and retries through the manager's own Remote. - * @module @deepseek-ai/dsh-client-ui-mcp-account - */ - -import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-mcp-manager' -import type { McpManagedServerView } from '@deepseek-ai/dsh-mcp-manager/types' -import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import type { McpAccountRegistration, McpAccountsView } from './types.ts' - -export type * from './types.ts' - -declare module '@deepseek-ai/cordis' { - interface Context { - /** Connector accounts on the Plugins page. */ - mcpAccounts: McpAccounts - } -} - -/** Holds the registered accounts and serves them, with their servers' manager views, to the Plugins page. */ -export default class McpAccounts extends TypertRemoteService { - static inject = ['mcpManager'] - - private readonly accounts = new Map() - private readonly listeners = new Set<() => void>() - private readonly lifetime = new AbortController() - - /** @param ctx - the Host context carrying the MCP manager. */ - constructor(ctx: Context) { - super(ctx, 'mcpAccounts') - ctx.effect(() => () => { this.lifetime.abort(new Error('mcpAccounts: registry disposed')) }) - } - - /** - * Show one account on the Plugins page for as long as the returned disposer has not run. - * @param registration - the server name, the bundle package, and the connector's text. - * @returns an idempotent disposer that withdraws the account. - * @throws when another account already uses the package or the server. - */ - register(registration: McpAccountRegistration): () => void { - const { server, packageName } = registration - for (const account of this.accounts.values()) { - if (account.packageName === packageName) throw new Error(`mcpAccounts: ${packageName} is already registered`) - if (account.server === server) throw new Error(`mcpAccounts: server ${server} is already registered`) - } - this.accounts.set(packageName, registration) - this.changed() - let active = true - return () => { - if (!active) return - active = false - this.accounts.delete(packageName) - this.changed() - } - } - - /** - * Follow every registered account with the manager's view of its server. - * @param signal - the Client's observation lifetime; disposal also ends the stream. - * @returns the accounts once the manager lists its servers, then after each change of either, coalescing changes that - * arrive before the next read; ends with the manager's stream. - * @throws what the manager's stream throws. - */ - @Remote({ mode: 'stream' }) - async *watch(signal: AbortSignal): AsyncIterable { - const stop = new AbortController() - const ended = AbortSignal.any([signal, this.lifetime.signal, stop.signal]) - let servers: readonly McpManagedServerView[] | undefined - let failure: { readonly error: unknown } | undefined - let wake = Promise.withResolvers() - let dirty = true - const notify = (): void => { dirty = true; wake.resolve() } - this.listeners.add(notify) - ended.addEventListener('abort', notify, { once: true }) - const following = (async () => { - try { - for await (const next of this.ctx.mcpManager.watch(ended)) { - servers = next - notify() - } - } catch (error) { - failure = { error } - } finally { - stop.abort() - } - })() - try { - for (;;) { - if (!dirty) await wake.promise - if (failure !== undefined) throw failure.error - if (ended.aborted) break - wake = Promise.withResolvers() - dirty = false - if (servers === undefined) continue - const listed = servers - yield { - accounts: [...this.accounts.values()].map((account) => { - const view = listed.find(server => server.name === account.server) - return view === undefined ? account : { ...account, view } - }), - } - } - } finally { - this.listeners.delete(notify) - ended.removeEventListener('abort', notify) - stop.abort() - await following - } - } - - private changed(): void { - for (const notify of this.listeners) notify() - } -} diff --git a/packages/client/ui-mcp-account/tests/components.client.spec.tsx b/packages/client/ui-mcp-account/tests/components.client.spec.tsx deleted file mode 100644 index c33c648eea..0000000000 --- a/packages/client/ui-mcp-account/tests/components.client.spec.tsx +++ /dev/null @@ -1,206 +0,0 @@ -// @vitest-environment jsdom -/** The account surfaces render the Host entry with the connector's text and this package's shared copy. */ -import type { ComponentProps } from 'react' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { PluginPackageRef, PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type { McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' -import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import { afterEach, expect, it, vi } from 'vitest' -import { McpAccountActivation, McpAccountBadge, McpAccountSection, McpAccountToast } from '../src/client/McpAccount.tsx' -import type { McpAccountSnapshot } from '../src/client/types.ts' -import type { McpAccountCopy } from '../src/types.ts' - -afterEach(cleanup) - -const MISSING: McpManagedServerStatus = { state: 'waiting-authorization', reason: 'missing', lastError: 'x' } -const CONNECTED: McpManagedServerStatus = { state: 'connected', toolCount: 1, connectedAt: 1 } -const PACKAGE = '@acme/docs' -const zh = (text: string): LocalizedText => ({ en: `en ${text}`, zh: text }) - -const COPY: McpAccountCopy = { - title: zh('Docs 账号'), connect: zh('连接 Docs'), - activation: { title: zh('连接 Docs?'), body: zh('Docs 已开启。') }, - detail: { - disconnected: zh('尚未连接 Docs。'), waitingBrowser: zh('在浏览器中完成授权。'), authorizing: zh('正在授权。'), - connecting: zh('正在连接 Docs。'), connected: zh('已连接 Docs。'), rejected: zh('Docs 拒绝了授权。'), scope: zh('Docs 需要更多权限。'), - }, - signOut: { title: zh('退出 Docs?'), body: zh('将删除授权。') }, - notice: { connected: zh('Docs 已连接'), signedOut: zh('已退出 Docs') }, -} - -function server(status: McpManagedServerStatus, phase?: McpOAuthAttemptView['phase'], authorizationUrl?: string): McpManagedServerView { - return { - name: 'docs', configured: true, status, - ...phase === undefined ? {} : { authorization: { id: 'a' as McpOAuthAttemptId, phase, ...authorizationUrl === undefined ? {} : { authorizationUrl } } }, - } -} - -interface Change extends Partial> { - readonly view?: McpManagedServerView | undefined -} - -function snapshot({ view, ...change }: Change): McpAccountSnapshot { - const entry = { server: 'docs', packageName: PACKAGE, copy: COPY, ...view === undefined ? {} : { view } } - return { entry, linked: true, busy: false, notice: undefined, ...change } -} - -function fixture(initial: Change = {}) { - let current = initial - const state = createSnapshotStore(snapshot(initial)) - const face = { - packageName: PACKAGE, - useMcpAccount: bindSnapshotSelector(state), - resolveText: (text: LocalizedText) => typeof text === 'string' ? text : text.zh ?? text.en, - connect: vi.fn(), cancel: vi.fn(), signOut: vi.fn(), retry: vi.fn(), openAuthorization: vi.fn(), dismissNotice: vi.fn(), - t: makeTranslate(), - } - return { - state, face, - set(change: Change) { - current = { ...current, ...change } - act(() => { state.set(snapshot(current)) }) - }, - } -} - -const button = (name: string) => screen.getByRole('button', { name }) - -it('offers the next step for each connection state with the connector\'s text', () => { - const b = fixture({ view: server(MISSING) }) - const { container } = render() - expect(screen.getByText('Docs 账号')).toBeTruthy() - expect(screen.getByText('status.disconnected')).toBeTruthy() - expect(screen.getByText('尚未连接 Docs。')).toBeTruthy() - expect(screen.getByText('hostBrowser')).toBeTruthy() - expect(container.querySelector('[data-mcp-account="disconnected"][data-mcp-account-package="@acme/docs"]')).toBeTruthy() - fireEvent.click(button('连接 Docs')) - expect(b.face.connect).toHaveBeenCalledOnce() - - b.set({ view: server(MISSING, 'waiting-browser', 'https://docs.test') }) - expect(screen.getByText('在浏览器中完成授权。')).toBeTruthy() - fireEvent.click(button('action.open')) - fireEvent.click(button('action.cancel')) - expect(b.face.openAuthorization).toHaveBeenCalledOnce() - expect(b.face.cancel).toHaveBeenCalledOnce() - - b.set({ view: server(MISSING, 'exchanging') }) - expect(screen.getByText('正在授权。')).toBeTruthy() - expect(screen.queryByRole('button', { name: 'action.open' })).toBeNull() - fireEvent.click(button('action.cancel')) - expect(b.face.cancel).toHaveBeenCalledTimes(2) - - b.set({ view: server(MISSING, 'failed') }) - expect(screen.getByRole('alert').textContent).toBe('failed') - - b.set({ view: server({ state: 'waiting-authorization', reason: 'scope', lastError: 'x' }) }) - expect(screen.getByText('Docs 需要更多权限。')).toBeTruthy() - fireEvent.click(button('action.reconnect')) - expect(b.face.connect).toHaveBeenCalledTimes(2) - b.set({ view: server({ state: 'waiting-authorization', reason: 'rejected', lastError: 'x' }) }) - expect(screen.getByText('Docs 拒绝了授权。')).toBeTruthy() - b.set({ view: server({ state: 'waiting-authorization', reason: 'expired', lastError: 'x' }) }) - expect(screen.getByText('detail.reconnect.expired')).toBeTruthy() - - b.set({ view: server({ state: 'failed', reason: 'gave-up' }) }) - expect(screen.getByText('detail.unavailable')).toBeTruthy() - fireEvent.click(button('action.retry')) - expect(b.face.retry).toHaveBeenCalledOnce() - - // Only a Host restart recovers incomplete cleanup, so the page offers no retry. - b.set({ view: server({ state: 'failed', reason: 'cleanup', result: { closeConfirmed: false } }) }) - expect(screen.queryAllByRole('button')).toHaveLength(0) - - b.set({ view: server({ state: 'connecting', attempt: 0 }) }) - expect(screen.getByText('正在连接 Docs。')).toBeTruthy() - expect(screen.queryAllByRole('button')).toHaveLength(0) - - b.set({ view: undefined }) - expect(screen.getByText('status.checking')).toBeTruthy() - expect(document.querySelector('[data-mcp-account="checking"] p')?.textContent).toBe('hostBrowser') -}) - -it('disables actions while one is pending or the Host stream is offline', () => { - const b = fixture({ view: server(MISSING), busy: true }) - render() - expect(button('连接 Docs').hasAttribute('disabled')).toBe(true) - b.set({ busy: false, linked: false }) - expect(button('连接 Docs').hasAttribute('disabled')).toBe(true) - b.set({ linked: true }) - expect(button('连接 Docs').hasAttribute('disabled')).toBe(false) -}) - -it('signs out only after the connector\'s confirmation', () => { - const b = fixture({ view: server(CONNECTED) }) - render() - expect(screen.getByText('已连接 Docs。')).toBeTruthy() - fireEvent.click(button('action.signOut')) - expect(screen.getByText('退出 Docs?')).toBeTruthy() - expect(screen.getByText('将删除授权。')).toBeTruthy() - fireEvent.click(button('action.cancel')) - expect(b.face.signOut).not.toHaveBeenCalled() - fireEvent.click(button('action.signOut')) - fireEvent.click(button('close')) - expect(screen.queryByText('将删除授权。')).toBeNull() - fireEvent.click(button('action.signOut')) - fireEvent.click(screen.getAllByRole('button', { name: 'action.signOut' }).at(-1)!) - expect(b.face.signOut).toHaveBeenCalledOnce() -}) - -it('tags only the enabled bundle of its package', () => { - const b = fixture({ view: server(CONNECTED) }) - const pkg = (name: string, enabled = true): PluginPackageRef => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] }) - const badge = (subject: PluginsSubject) => - } /> - const { rerender } = render(badge({ kind: 'bundle', pkg: pkg(PACKAGE) })) - expect(screen.getByText('badge.connected')).toBeTruthy() - b.set({ view: server(MISSING, 'waiting-browser') }) - expect(screen.getByText('badge.connecting')).toBeTruthy() - b.set({ view: undefined }) - expect(document.body.textContent).toBe('') - b.set({ view: server(MISSING) }) - rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE, false) })) - expect(document.body.textContent).toBe('') - rerender(badge({ kind: 'bundle', pkg: pkg('@acme/other') })) - expect(document.body.textContent).toBe('') - rerender(badge({ kind: 'item', id: 'shell' })) - expect(document.body.textContent).toBe('') - rerender(badge({ kind: 'row', pkg: pkg(PACKAGE), row: { rowId: 'docs', moduleName: PACKAGE, enabled: true } })) - expect(document.body.textContent).toBe('') -}) - -it('guides a newly enabled bundle to connect with the connector\'s prompt, and steps aside once connected', () => { - const b = fixture() - const onDismiss = vi.fn(), onOpenDetails = vi.fn() - const props = { ...b.face, onDismiss, onOpenDetails } as ComponentProps - render() - expect(screen.queryByText('Docs 已开启。')).toBeNull() - expect(onDismiss).not.toHaveBeenCalled() - // A first connection attempt is still settling; the guidance waits for its outcome. - b.set({ view: server({ state: 'connecting', attempt: 0 }) }) - expect(onDismiss).not.toHaveBeenCalled() - b.set({ view: server(MISSING) }) - expect(screen.getByText('连接 Docs?')).toBeTruthy() - expect(screen.getByText('Docs 已开启。')).toBeTruthy() - fireEvent.click(button('activation.later')) - expect(onDismiss).toHaveBeenCalledOnce() - fireEvent.click(button('连接 Docs')) - expect(onOpenDetails).toHaveBeenCalledOnce() - expect(b.face.connect).toHaveBeenCalledOnce() - b.set({ view: server(CONNECTED) }) - expect(onDismiss).toHaveBeenCalledTimes(2) -}) - -it('reports the latest notice with the connector\'s text and leaves dismissal to the toast', () => { - const b = fixture() - render() - expect(document.body.textContent).toBe('') - b.set({ notice: { seq: 1, kind: 'connected' } }) - expect(screen.getByText('Docs 已连接')).toBeTruthy() - b.set({ notice: { seq: 2, kind: 'signed-out' } }) - expect(screen.getByText('已退出 Docs')).toBeTruthy() - b.set({ notice: { seq: 3, kind: 'action-failed' } }) - expect(screen.getByText('notice.action-failed')).toBeTruthy() -}) diff --git a/packages/client/ui-mcp-account/tests/connection.client.spec.ts b/packages/client/ui-mcp-account/tests/connection.client.spec.ts deleted file mode 100644 index e6a4ec1067..0000000000 --- a/packages/client/ui-mcp-account/tests/connection.client.spec.ts +++ /dev/null @@ -1,281 +0,0 @@ -// @vitest-environment jsdom -/** The page follows every registered account through one Host stream and drives authorization through the manager's Remote. */ -import { Context } from '@deepseek-ai/cordis' -import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' -import type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/dsh-api-remotes/client' -import type { McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' -import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import { expect, it, onTestFinished, vi } from 'vitest' -import { McpAccountsConnection, presentConnection } from '../src/client/connection.ts' -import type { McpAccountEntry, McpAccountsView } from '../src/types.ts' - -const ATTEMPT = 'attempt-1' as McpOAuthAttemptId -const DOCS = '@acme/docs' -const WIKI = '@acme/wiki' -const ok = (value: T): RemoteResult => ({ ok: true, value }) - -function attempt(phase: McpOAuthAttemptView['phase'], authorizationUrl?: string, id = ATTEMPT): McpOAuthAttemptView { - return { id, phase, ...authorizationUrl === undefined ? {} : { authorizationUrl } } -} - -function server(status: McpManagedServerStatus, authorization?: McpOAuthAttemptView): McpManagedServerView { - return { name: 'docs', configured: true, status, ...authorization === undefined ? {} : { authorization } } -} - -const MISSING: McpManagedServerStatus = { state: 'waiting-authorization', reason: 'missing', lastError: 'no grant' } -const CONNECTED: McpManagedServerStatus = { state: 'connected', toolCount: 2, connectedAt: 1 } - -it.each<[string, McpManagedServerView | undefined, ReturnType]>([ - ['no entry yet', undefined, { phase: 'checking' }], - ['a missing grant', server(MISSING), { phase: 'disconnected', failed: false }], - ['a failed attempt over a missing grant', server(MISSING, attempt('failed')), { phase: 'disconnected', failed: true }], - ['an expired grant', server({ state: 'waiting-authorization', reason: 'expired', lastError: 'x' }), { phase: 'reconnect', reason: 'expired', failed: false }], - ['missing permissions', server({ state: 'waiting-authorization', reason: 'scope', lastError: 'x' }), { phase: 'reconnect', reason: 'scope', failed: false }], - ['a starting attempt', server(MISSING, attempt('starting')), { phase: 'authorizing', attempt: ATTEMPT }], - ['an exchanging attempt', server(MISSING, attempt('exchanging')), { phase: 'authorizing', attempt: ATTEMPT }], - ['a committing attempt', server(MISSING, attempt('committing')), { phase: 'authorizing', attempt: ATTEMPT }], - ['a browser step', server(MISSING, attempt('waiting-browser', 'https://docs.test/auth')), - { phase: 'waiting-browser', attempt: ATTEMPT, url: 'https://docs.test/auth' }], - ['a connection', server(CONNECTED, attempt('authorized')), { phase: 'connected' }], - ['a cancelled attempt', server(MISSING, attempt('cancelled')), { phase: 'disconnected', failed: false }], - ['a first connection', server({ state: 'connecting', attempt: 0 }), { phase: 'connecting' }], - ['a reconnect backoff', server({ state: 'reconnecting', attempt: 1, maxAttempts: 3, nextRetryAtMs: 2, lastError: 'x' }), { phase: 'connecting' }], - ['a closed instance', server({ state: 'closed', result: { closeConfirmed: true } }), { phase: 'unavailable', failed: false, retryable: true }], - ['missing static credentials', server({ state: 'waiting-credentials', lastError: 'x' }), { phase: 'unavailable', failed: false, retryable: false }], - ['a disabled entry', server({ state: 'disabled' }), { phase: 'unavailable', failed: false, retryable: false }], - ['a stopped supervisor', server({ state: 'failed', reason: 'gave-up' }), { phase: 'unavailable', failed: false, retryable: true }], - ['a load failure', server({ state: 'failed', reason: 'load', lastError: 'x' }), { phase: 'unavailable', failed: false, retryable: true }], - ['an unclosed generation', server({ state: 'failed', reason: 'unclosed-generation', lastError: 'x' }), { phase: 'unavailable', failed: false, retryable: false }], - ['incomplete cleanup', server({ state: 'failed', reason: 'cleanup', result: { closeConfirmed: false } }), { phase: 'unavailable', failed: false, retryable: false }], -])('presents %s', (_name, entry, expected) => { - expect(presentConnection(entry)).toEqual(expected) -}) - -function entry(view?: McpManagedServerView, packageName = DOCS): McpAccountEntry { - const name = packageName === DOCS ? 'docs' : 'wiki' - return { - server: name, packageName, copy: { - title: name, connect: `Connect ${name}`, activation: { title: name, body: name }, - detail: { disconnected: '-', waitingBrowser: '-', authorizing: '-', connecting: '-', connected: '-', rejected: '-', scope: '-' }, - signOut: { title: name, body: name }, notice: { connected: name, signedOut: name }, - }, - ...view === undefined ? {} : { view }, - } -} - -function fixture() { - const queue: McpAccountsView[] = [] - let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 - let options!: RemoteStreamOptions - const stream = { - async *[Symbol.asyncIterator]() { - for (;;) { - if (failure !== undefined) throw failure - // A queued item still arrives after close, as an item the stream yielded just before disposal does. - const next = queue.shift() - if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } - if (closed) return - await new Promise((resolve) => { wake = resolve }) - } - }, - dispose: vi.fn(async () => { closed = true; wake?.() }), - } - const registry = { watch: vi.fn() } - const servers = { - startAuthorization: vi.fn(async (_server: string) => ok(attempt('starting'))), - cancelAuthorization: vi.fn(async (_server: string, _id: McpOAuthAttemptId): Promise> => ok(undefined)), - signOut: vi.fn(async (_server: string): Promise> => ok(undefined)), - restart: vi.fn(async (_server: string): Promise> => ok(undefined)), - } - const ctx = new Context() - ctx.provide('remote', { $stream: (value: typeof options) => { options = value; return stream } }) - const open = vi.spyOn(window, 'open').mockReturnValue(null) - const connection = new McpAccountsConnection(ctx, registry, servers) - onTestFinished(async () => { await connection.dispose(); open.mockRestore(); await ctx.fiber.dispose() }) - return { - connection, registry, servers, open, stream, options: () => options, - face: (packageName = DOCS) => connection.actions(packageName), - snapshot: (packageName = DOCS) => connection.accounts.getSnapshot().get(packageName)?.getSnapshot(), - deliver(...entries: McpAccountEntry[]) { queue.push({ accounts: entries }); wake?.() }, - async publish(...entries: McpAccountEntry[]) { - const target = accepted + 1 - this.deliver(...entries) - await vi.waitFor(() => { expect(accepted).toBe(target) }) - }, - fail(error: Error) { failure = error; wake?.() }, - failOnClose(error: Error) { failure = error }, - } -} - -const settle = async (b: ReturnType, packageName = DOCS) => { - await vi.waitFor(() => { expect(b.snapshot(packageName)?.busy).toBe(false) }) -} -// Every fixture step settles through microtasks, so one macrotask lets a pending action finish. -const drain = () => new Promise((resolve) => { setTimeout(resolve, 0) }) - -it('opens the registry stream and keeps one snapshot source per account the Host registers', async () => { - const b = fixture() - const signal = new AbortController().signal - b.options().open(signal) - expect(b.registry.watch).toHaveBeenCalledWith(signal) - expect(b.options().ended(true)).toBeInstanceOf(Error) - await b.publish(entry(server(MISSING))) - expect(b.snapshot()).toEqual({ entry: entry(server(MISSING)), linked: true, busy: false, notice: undefined }) - const shown = b.connection.accounts.getSnapshot() - const store = shown.get(DOCS) - - await b.publish(entry(server(CONNECTED))) - expect(b.connection.accounts.getSnapshot()).toBe(shown) - expect(store?.getSnapshot().entry.view?.status).toEqual(CONNECTED) - await b.publish(entry(server(CONNECTED)), entry(undefined, WIKI)) - expect([...b.connection.accounts.getSnapshot().keys()]).toEqual([DOCS, WIKI]) - expect(b.connection.accounts.getSnapshot().get(DOCS)).toBe(store) - await b.publish(entry(undefined, WIKI)) - expect([...b.connection.accounts.getSnapshot().keys()]).toEqual([WIKI]) -}) - -it('marks every account offline while the carrier is down', async () => { - const b = fixture() - await b.publish(entry(server(MISSING)), entry(undefined, WIKI)) - b.options().carrierFailed?.(new Error('lost')) - expect([b.snapshot()?.linked, b.snapshot(WIKI)?.linked]).toEqual([false, false]) - await b.publish(entry(server(MISSING)), entry(undefined, WIKI)) - expect([b.snapshot()?.linked, b.snapshot(WIKI)?.linked]).toEqual([true, true]) -}) - -it('opens the authorization page once for the attempt this browser started, then reports the connection', async () => { - const b = fixture() - await b.publish(entry(server(MISSING)), entry(undefined, WIKI)) - b.face().connect() - await settle(b) - expect(b.servers.startAuthorization).toHaveBeenCalledWith('docs') - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/auth'))), entry(undefined, WIKI)) - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/auth'))), entry(undefined, WIKI)) - expect(b.open).toHaveBeenCalledOnce() - expect(b.open).toHaveBeenCalledWith('https://docs.test/auth', '_blank', 'noopener,noreferrer') - b.face().openAuthorization() - expect(b.open).toHaveBeenCalledTimes(2) - await b.publish(entry(server(CONNECTED, attempt('authorized'))), entry(undefined, WIKI)) - expect(b.snapshot()?.notice).toEqual({ seq: 1, kind: 'connected' }) - expect(b.snapshot(WIKI)?.notice).toBeUndefined() - await b.publish(entry(server(CONNECTED, attempt('authorized'))), entry(undefined, WIKI)) - expect(b.snapshot()?.notice?.seq).toBe(1) - b.face().dismissNotice() - expect(b.snapshot()?.notice).toBeUndefined() -}) - -it('opens a page the stream reported before the start call answered, and never another browser\'s attempt', async () => { - const b = fixture() - const answer = Promise.withResolvers>() - b.servers.startAuthorization.mockReturnValueOnce(answer.promise) - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/other', 'other' as McpOAuthAttemptId)))) - expect(b.open).not.toHaveBeenCalled() - b.face().connect() - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'http://127.0.0.1:3080/authorize')))) - expect(b.open).not.toHaveBeenCalled() - answer.resolve(ok(attempt('starting'))) - await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('http://127.0.0.1:3080/authorize', '_blank', 'noopener,noreferrer') }) -}) - -it.each(['http://docs.test/auth', 'javascript:alert(1)', 'not a url'])('refuses to open %s', async (url) => { - const b = fixture() - await b.publish(entry(server(MISSING))) - b.face().connect() - await settle(b) - await b.publish(entry(server(MISSING, attempt('waiting-browser', url)))) - b.face().openAuthorization() - expect(b.open).not.toHaveBeenCalled() -}) - -it('cancels only an active attempt and forgets an attempt that ended', async () => { - const b = fixture() - await b.publish(entry(server(MISSING))) - b.face().cancel() - b.face().openAuthorization() - expect(b.servers.cancelAuthorization).not.toHaveBeenCalled() - expect(b.open).not.toHaveBeenCalled() - b.face().connect() - await settle(b) - await b.publish(entry(server(MISSING, attempt('starting')))) - b.face().cancel() - await vi.waitFor(() => { expect(b.servers.cancelAuthorization).toHaveBeenCalledWith('docs', ATTEMPT) }) - await b.publish(entry(server(MISSING, attempt('cancelled')))) - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/late')))) - expect(b.open).not.toHaveBeenCalled() - expect(b.snapshot()?.notice).toBeUndefined() -}) - -it('signs out and retries through the manager, reporting a failed action once and ignoring overlapping clicks', async () => { - const b = fixture() - await b.publish(entry(server(CONNECTED))) - b.face().signOut() - b.face().retry() - await vi.waitFor(() => { expect(b.snapshot()?.notice?.kind).toBe('signed-out') }) - expect(b.servers.signOut).toHaveBeenCalledWith('docs') - expect(b.servers.restart).not.toHaveBeenCalled() - b.servers.restart.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - b.face().retry() - await vi.waitFor(() => { expect(b.snapshot()?.notice?.kind).toBe('action-failed') }) - expect(b.servers.restart).toHaveBeenCalledWith('docs') - expect(b.snapshot()?.busy).toBe(false) -}) - -it('ignores actions for an account the Host has not registered, and follows no attempt of a withdrawn account', async () => { - const b = fixture() - for (const action of Object.values(b.face())) action() - await b.publish(entry(server(MISSING))) - const answer = Promise.withResolvers>() - b.servers.startAuthorization.mockReturnValueOnce(answer.promise) - b.face().connect() - await b.publish() - answer.resolve(ok(attempt('starting'))) - await drain() - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/auth')))) - expect(b.snapshot()?.busy).toBe(false) - expect(b.open).not.toHaveBeenCalled() - - await b.publish(entry(server(MISSING))) - b.face().connect() - await settle(b) - await b.publish(entry(undefined, WIKI)) - await b.publish(entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/auth')))) - expect(b.open).not.toHaveBeenCalled() - expect(b.servers.startAuthorization).toHaveBeenCalledTimes(2) - expect([b.servers.cancelAuthorization, b.servers.signOut, b.servers.restart].every(call => call.mock.calls.length === 0)).toBe(true) -}) - -it('stops observing on disposal without reporting the closed stream', async () => { - const b = fixture() - await b.publish(entry(server(MISSING))) - b.failOnClose(new Error('closed')) - await b.connection.dispose() - expect(b.stream.dispose).toHaveBeenCalled() - expect(b.snapshot()?.linked).toBe(true) -}) - -it('reports nothing and follows no attempt for an action that settles after disposal, and ignores a view yielded after it', async () => { - const b = fixture() - const waiting = entry(server(MISSING, attempt('waiting-browser', 'https://docs.test/auth')), WIKI) - await b.publish(entry(server(CONNECTED)), waiting) - const signedOut = Promise.withResolvers>() - const started = Promise.withResolvers>() - b.servers.signOut.mockReturnValueOnce(signedOut.promise) - b.servers.startAuthorization.mockReturnValueOnce(started.promise) - b.face().signOut() - b.face(WIKI).connect() - b.deliver(entry(server(MISSING)), waiting) - await b.connection.dispose() - signedOut.resolve(ok(undefined)) - started.resolve(ok(attempt('starting'))) - await settle(b) - await settle(b, WIKI) - expect(b.snapshot()).toMatchObject({ entry: entry(server(CONNECTED)), linked: true, notice: undefined }) - expect(b.open).not.toHaveBeenCalled() -}) - -it('marks the page offline when the stream fails', async () => { - const b = fixture() - await b.publish(entry(server(MISSING))) - b.fail(new Error('invalid frame')) - await vi.waitFor(() => { expect(b.snapshot()?.linked).toBe(false) }) -}) diff --git a/packages/client/ui-mcp-account/tests/mount.client.spec.ts b/packages/client/ui-mcp-account/tests/mount.client.spec.ts deleted file mode 100644 index d46de7ca58..0000000000 --- a/packages/client/ui-mcp-account/tests/mount.client.spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * The browser plugin mounts the `mcpAccounts` Remote and shows each account the Host registers, withdrawing its surfaces - * with the account or the plugin. - */ -import assert from 'node:assert/strict' -import { Context, Service } from '@deepseek-ai/cordis' -import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { McpOAuthAttemptId, McpOAuthAttemptView } from '@deepseek-ai/dsh-mcp-client/types' -import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' -import { expect, it, onTestFinished, vi } from 'vitest' -import { NS } from '../src/client/locales.ts' -import { McpAccountActivation, McpAccountBadge, McpAccountSection, McpAccountToast } from '../src/client/McpAccount.tsx' -import { inject, mountMcpAccounts } from '../src/client/mount.ts' -import type { McpAccountFace } from '../src/client/types.ts' -import type { McpAccountEntry, McpAccountsView } from '../src/types.ts' - -const contribution: TypertRemoteContribution = { package: '@deepseek-ai/dsh-client-ui-mcp-account', descriptors: [] } -const DOCS = '@acme/docs' -const WIKI = '@acme/wiki' - -const SLOTS = [ - ['plugins.bundle.config', McpAccountSection], - ['plugins.bundle.activation', McpAccountActivation], - ['plugins.detail.badge', McpAccountBadge], - ['shell.overlay', McpAccountToast], -] as const - -function isFace(value: Record): asserts value is Record & McpAccountFace { - assert(typeof value.packageName === 'string' && typeof value.resolveText === 'function' && typeof value.connect === 'function') - assert(typeof value.hooks === 'object' && value.hooks !== null) -} - -/** Read the face a slot entry injects. */ -function faceOf(item: { readonly inject?: (() => Record) | undefined }): McpAccountFace { - const face = item.inject!() - isFace(face) - return face -} - -function entry(packageName: string): McpAccountEntry { - const server = packageName === DOCS ? 'docs' : 'wiki' - return { - server, packageName, copy: { - title: server, connect: `Connect ${server}`, activation: { title: server, body: server }, - detail: { disconnected: '-', waitingBrowser: '-', authorizing: '-', connecting: '-', connected: '-', rejected: '-', scope: '-' }, - signOut: { title: server, body: server }, notice: { connected: server, signedOut: server }, - }, - } -} - -async function bench() { - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose() }) - const queue: McpAccountsView[] = [] - let wake: (() => void) | undefined, closed = false, accepted = 0 - const closeStream = vi.fn(async () => { closed = true; wake?.() }) - const unmount = vi.fn(async () => {}) - const startAuthorization = vi.fn(async (_server: string): Promise> => - ({ ok: true, value: { id: 'attempt-1' as McpOAuthAttemptId, phase: 'starting' } })) - class Remote extends Service { - constructor() { super(ctx, 'remote') } - async $mount(received: TypertRemoteContribution) { - expect(received).toBe(contribution) - return unmount - } - $stream() { - return { - async *[Symbol.asyncIterator]() { - for (;;) { - const next = queue.shift() - if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } - if (closed) return - await new Promise((resolve) => { wake = resolve }) - } - }, - dispose: closeStream, - } - } - } - new Remote() - ctx.provide('remote.mcpAccounts', { watch: vi.fn() }) - ctx.provide('remote.mcpManager', { startAuthorization, cancelAuthorization: vi.fn(), signOut: vi.fn(), restart: vi.fn() }) - const locale = new LocaleRuntime(ctx) - ctx.provide('locale', locale) - await ctx.plugin(SlotRegistry) - ctx.slots.register({ name: 'root', children: { - 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, - 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, - 'plugins.detail.badge': { kind: 'list', scope: 'root' }, - 'shell.overlay': { kind: 'list', scope: 'root' }, - } } as never, () => null) - const owners = () => SLOTS.flatMap(([slot]) => ctx.slots.entries(slot).map(item => faceOf(item).packageName)) - return { - ctx, locale, startAuthorization, closeStream, unmount, owners, - mount: () => ctx.plugin({ inject: [...inject], apply: scope => mountMcpAccounts(scope, contribution) }), - async publish(...entries: McpAccountEntry[]) { - const target = accepted + 1 - queue.push({ accounts: entries }) - wake?.() - await vi.waitFor(() => { expect(accepted).toBe(target) }) - }, - } -} - -it('shows each registered account with one face under the shared dictionary and withdraws the surfaces of an account the Host drops', async () => { - const b = await bench() - await b.mount() - expect(b.locale.bind(NS)('action.retry')).toBe('Retry') - expect(b.owners()).toEqual([]) - await b.publish(entry(DOCS), entry(WIKI)) - const faces = SLOTS.map(([slot, component]) => { - const found = b.ctx.slots.entries(slot).find(item => faceOf(item).packageName === DOCS) - expect(found).toMatchObject({ locale: NS, component }) - return faceOf(found!) - }) - expect(new Set(faces.map(face => face.hooks.mcpAccount)).size).toBe(1) - expect(faces[0]!.hooks.mcpAccount.getSnapshot().entry).toEqual(entry(DOCS)) - expect(faces[0]!.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') - expect(b.ctx.slots.entries('plugins.bundle.config').map(item => item.options.key)).toEqual([DOCS, WIKI]) - expect(b.ctx.slots.entries('plugins.bundle.activation').map(item => item.options.key)).toEqual([DOCS, WIKI]) - expect(b.ctx.slots.entries('plugins.detail.badge').map(item => item.options.id)).toEqual(['docs.connection', 'wiki.connection']) - expect(b.ctx.slots.entries('shell.overlay').map(item => item.options.id)).toEqual(['docs.connection-toast', 'wiki.connection-toast']) - faces[0]!.connect() - await vi.waitFor(() => { expect(b.startAuthorization).toHaveBeenCalledWith('docs') }) - - await b.publish(entry(WIKI)) - expect(b.owners()).toEqual([WIKI, WIKI, WIKI, WIKI]) - await b.publish(entry(WIKI), entry(DOCS)) - expect(b.owners().filter(owner => owner === DOCS)).toHaveLength(4) -}) - -it('withdraws every surface, the dictionaries, and the stream before the Remote when the plugin unloads', async () => { - const b = await bench() - const fiber = b.mount() - await fiber - await b.publish(entry(DOCS), entry(WIKI)) - expect(b.owners()).toHaveLength(8) - await fiber.dispose() - expect(b.owners()).toEqual([]) - expect(b.locale.bind(NS)('action.retry')).toBe('action.retry') - expect(b.closeStream).toHaveBeenCalledOnce() - expect(b.unmount).toHaveBeenCalledOnce() - expect(b.closeStream.mock.invocationCallOrder[0]).toBeLessThan(b.unmount.mock.invocationCallOrder[0]!) -}) - -it('withdraws the Remote when the surfaces fail to mount', async () => { - const b = await bench() - vi.spyOn(b.locale, 'register').mockImplementation(() => { throw new Error('registration failed') }) - await expect(mountMcpAccounts(b.ctx, contribution)).rejects.toThrow('registration failed') - expect(b.unmount).toHaveBeenCalledOnce() -}) diff --git a/packages/client/ui-mcp-account/tests/registry.host.spec.ts b/packages/client/ui-mcp-account/tests/registry.host.spec.ts deleted file mode 100644 index f8e2b0d71d..0000000000 --- a/packages/client/ui-mcp-account/tests/registry.host.spec.ts +++ /dev/null @@ -1,139 +0,0 @@ -/** The registry serves every registered account to the Plugins page with the MCP manager's view of its server. */ -import { Context } from '@deepseek-ai/cordis' -import type { McpManagedServerView } from '@deepseek-ai/dsh-mcp-manager/types' -import { expect, it, onTestFinished, vi } from 'vitest' -import McpAccounts from '../src/index.ts' -import type { McpAccountCopy, McpAccountRegistration, McpAccountsView } from '../src/types.ts' - -const COPY: McpAccountCopy = { - title: { en: 'Docs account', zh: 'Docs 账号' }, - connect: 'Connect Docs', - activation: { title: 'Connect Docs', body: 'Docs is on.' }, - detail: { - disconnected: 'Not connected.', waitingBrowser: 'Finish in the browser.', authorizing: 'Authorizing.', connecting: 'Connecting.', - connected: 'Connected.', rejected: 'Docs rejected the grant.', scope: 'Docs needs more permissions.', - }, - signOut: { title: 'Sign out of Docs?', body: 'Removes the grant.' }, - notice: { connected: 'Docs connected', signedOut: 'Signed out of Docs' }, -} - -const DOCS: McpAccountRegistration = { server: 'docs', packageName: '@acme/docs', copy: COPY } -const WIKI: McpAccountRegistration = { server: 'wiki', packageName: '@acme/wiki', copy: COPY } - -function view(name: string, toolCount = 1): McpManagedServerView { - return { name, configured: true, status: { state: 'connected', toolCount, connectedAt: 1 } } -} - -/** A manager whose stream yields the lists the test publishes, until the subscriber stops it, it fails, or it ends. */ -function manager() { - const lists: McpManagedServerView[][] = [] - const signals: AbortSignal[] = [] - let wake: (() => void) | undefined - let failure: Error | undefined - let ended = false - const service = { - async *watch(signal: AbortSignal): AsyncIterable { - signals.push(signal) - signal.addEventListener('abort', () => { wake?.() }, { once: true }) - for (;;) { - if (signal.aborted) return - if (failure !== undefined) throw failure - const next = lists.shift() - if (next !== undefined) { yield next; continue } - if (ended) return - await new Promise((resolve) => { wake = resolve }) - } - }, - } - return { - service, signals, - list(...servers: McpManagedServerView[]) { lists.push(servers); wake?.() }, - fail(error: Error) { failure = error; wake?.() }, - end() { ended = true; wake?.() }, - } -} - -async function registry(servers = manager()) { - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose() }) - ctx.provide('mcpManager', servers.service) - const fiber = ctx.plugin(McpAccounts) - await fiber - return { ctx, fiber, servers } -} - -function watch(ctx: Context, signal = new AbortController().signal): AsyncIterator { - return ctx.mcpAccounts.watch(signal)[Symbol.asyncIterator]() -} - -it('publishes the accounts once the manager lists its servers, then after each change of either', async () => { - const { ctx, servers } = await registry() - const withdraw = ctx.mcpAccounts.register(DOCS) - const controller = new AbortController() - const stream = watch(ctx, controller.signal) - let read = false - const reading = stream.next().finally(() => { read = true }) - await vi.waitFor(() => { expect(servers.signals).toHaveLength(1) }) - expect(read).toBe(false) - servers.list(view('docs'), view('other')) - expect((await reading).value).toEqual({ accounts: [{ ...DOCS, view: view('docs') }] }) - - // An account whose server the manager does not list carries no view. - ctx.mcpAccounts.register(WIKI) - expect((await stream.next()).value).toEqual({ accounts: [{ ...DOCS, view: view('docs') }, WIKI] }) - servers.list(view('docs', 3), view('wiki')) - expect((await stream.next()).value).toEqual({ accounts: [{ ...DOCS, view: view('docs', 3) }, { ...WIKI, view: view('wiki') }] }) - - withdraw() - withdraw() - expect((await stream.next()).value).toEqual({ accounts: [{ ...WIKI, view: view('wiki') }] }) - controller.abort() - expect((await stream.next()).done).toBe(true) - expect(servers.signals[0]!.aborted).toBe(true) -}) - -it('publishes the accounts registered before the manager lists in one view', async () => { - const { ctx, servers } = await registry() - const stream = watch(ctx) - const reading = stream.next() - ctx.mcpAccounts.register(DOCS) - ctx.mcpAccounts.register(WIKI) - servers.list() - expect((await reading).value).toEqual({ accounts: [DOCS, WIKI] }) -}) - -it('refuses a second account for a package or a server', async () => { - const { ctx } = await registry() - ctx.mcpAccounts.register(DOCS) - expect(() => ctx.mcpAccounts.register({ ...WIKI, packageName: DOCS.packageName })).toThrow('mcpAccounts: @acme/docs is already registered') - expect(() => ctx.mcpAccounts.register({ ...WIKI, server: DOCS.server })).toThrow('mcpAccounts: server docs is already registered') -}) - -it('rethrows what the manager stream throws', async () => { - const { ctx, servers } = await registry() - const stream = watch(ctx) - servers.list() - await stream.next() - servers.fail(new Error('manager offline')) - await expect(stream.next()).rejects.toThrow('manager offline') -}) - -it('ends with the manager stream', async () => { - const { ctx, servers } = await registry() - const stream = watch(ctx) - servers.list() - await stream.next() - servers.end() - expect((await stream.next()).done).toBe(true) -}) - -it('ends every stream when the registry unloads', async () => { - const { ctx, fiber, servers } = await registry() - const stream = watch(ctx) - servers.list() - await stream.next() - const pending = stream.next() - await fiber.dispose() - expect((await pending).done).toBe(true) - expect(servers.signals[0]!.aborted).toBe(true) -}) diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index 6122766724..af4f1664fd 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -24,8 +24,8 @@ en: 2a44a378364912db zh: 8c514ce17469747f /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-a-bundle: - en: 390dc85aceac033a - zh: 746ceae45f70dd33 + en: 188ebf6f1590bad1 + zh: e6d41e8586190fa0 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-one-row-of-a-bundle: en: d3627d4dba5e6cc2 zh: e0d0eada4c20331f @@ -33,8 +33,8 @@ en: e9da90f03691101b zh: 902cda935a4ce3c8 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/detail-page-extension-points: - en: d5e3cad5c31cae59 - zh: 6dc38f09b410d247 + en: 16dbfb0ab558c951 + zh: adf098c0751a7144 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/page-tabs: en: 99c06790c2163746 zh: daa87ad1ce9a76ae diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 1b23459a8b..155ef55105 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -78,7 +78,7 @@ After the checks, the list toolbar says how many plugins can be updated, that al ### Switching a bundle -A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete; the Settings Plugins section's Plugin list tab inspects their plugins. +A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete; the Settings Plugins section's Plugin list tab inspects their plugins. ### Switching one row of a bundle @@ -100,7 +100,7 @@ The bundle's patch must declare the row under that id, and the registration exis ### Detail page extension points -A plugin with something to say about a bundle, a row, or an official plugin it does not own contributes to that object's page through three list slots the page declares: `plugins.detail.actions` for a control at the head of the page, before the page's own switch and uninstall; `plugins.detail.badge` for a tag beside the title, after the version, experimental, and problem tags; and `plugins.detail.section` for a section under the page's own content — after the source on a bundle's page, after the configuration on a row's or an official plugin's page. Every entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`, where `pkg` and `row` carry the name, version, installed and enabled facts, and the row list a contribution decides on. An entry renders null for a subject it has nothing for and draws its own section chrome; the page orders entries by `order`. +A plugin with something to say about a bundle, a row, or an official plugin it does not own contributes to that object's page through three list slots the page declares: `plugins.detail.actions` for a control at the head of the page, before the page's own switch and uninstall; `plugins.detail.badge` for a tag beside the title, after the version, experimental, and problem or not-running tags; and `plugins.detail.section` for a section under the page's own content — after the source on a bundle's page, after the configuration on a row's or an official plugin's page. Every entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`, where `pkg` and `row` carry the name, version, installed and enabled facts, and the row list a contribution decides on. An entry renders null for a subject it has nothing for and draws its own section chrome; the page orders entries by `order`. ```tsx ignore-check ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 8062b0e426..586d8adadf 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -78,7 +78,7 @@ Host 将网络失败或超时归因于 GitHub 地址,且提供 npmmirror 时 ### 切换一个组合包 -组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据;设置中「插件」分区的「插件列表」标签页负责查看它们的插件。 +组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据;设置中「插件」分区的「插件列表」标签页负责查看它们的插件。 ### 切换组合包里的一行 @@ -100,7 +100,7 @@ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ ### 详情页扩展点 -对某个不属于自己的组合包、行或官方插件有话要说的插件,通过本页声明的三个 list slot 向该对象的页面贡献内容:`plugins.detail.actions` 在页头放一个控件,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁放一个标签,位于版本、实验性和异常标签之后;`plugins.detail.section` 在页面自身内容之下放一个区块——组合包页在来源信息之后,行页和官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`,其中 `pkg` 与 `row` 携带包名、版本、是否已安装、是否启用以及行列表这些供贡献者判断的事实。条目对无话可说的 subject 返回 null,自绘区块外观;页面按 `order` 排列条目。 +对某个不属于自己的组合包、行或官方插件有话要说的插件,通过本页声明的三个 list slot 向该对象的页面贡献内容:`plugins.detail.actions` 在页头放一个控件,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁放一个标签,位于版本、实验性和异常或未运行标签之后;`plugins.detail.section` 在页面自身内容之下放一个区块——组合包页在来源信息之后,行页和官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`,其中 `pkg` 与 `row` 携带包名、版本、是否已安装、是否启用以及行列表这些供贡献者判断的事实。条目对无话可说的 subject 返回 null,自绘区块外观;页面按 `order` 排列条目。 ```tsx ignore-check ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index d24d1f08fe..f7fac78f91 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -12,6 +12,10 @@ --plugin-page-top-inset: 28px; --bundle-progress-size: 14px; --bundle-toggle-gap: 8px; + /* A card head's inset, icon size, and gap after the icon; a card's reason lines align under its title from these. */ + --card-head-inset: 8px; + --card-icon-size: 48px; + --card-head-gap: 14px; display: flex; flex-direction: column; @@ -387,8 +391,8 @@ .cardHead { display: flex; align-items: center; - gap: 14px; - padding: 8px; + gap: var(--card-head-gap); + padding: var(--card-head-inset); } .cardIcon { @@ -396,14 +400,19 @@ flex: none; align-items: center; justify-content: center; - width: 48px; - height: 48px; + width: var(--card-icon-size); + height: var(--card-icon-size); /* The same hairline frame as the component rows below. */ border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-lg); color: var(--dsw-alias-label-secondary); } +/* A card's reason lines start under its title. */ +.card > .reason { + padding: 0 var(--card-head-inset) var(--card-head-inset) calc(var(--card-head-inset) + var(--card-icon-size) + var(--card-head-gap)); +} + .packageImage { object-fit: contain; } diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index 41df8e96a2..53f0b7d67b 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -419,12 +419,30 @@ function EnableSwitch({ pkg, title, t, busy, onSetEnabled }: { ) } -/** The status one card carries: running, off, or a problem the Host reported. */ -function packageStatus(pkg: PackageView): 'running' | 'disabled' | 'problem' { +/** The status one card carries: running, off, not running because the Host skipped a selected bundle's layer, or another problem. */ +type PackageStatus = 'running' | 'disabled' | 'not-running' | 'problem' + +/** The tag each status shows beside the title on a card and on its page; running and off show none. */ +const STATUS_TAG_KEYS = { + 'running': undefined, + 'disabled': undefined, + 'not-running': 'statusNotRunning', + 'problem': 'statusProblem', +} satisfies Record + +/** A selected bundle the Host reports an error for is not running when none of its rows has a live entry. */ +function packageStatus(pkg: PackageView): PackageStatus { + if (pkg.enabled && pkg.error !== undefined && pkg.rows.every(row => row.entryId === undefined)) return 'not-running' if (pkg.error !== undefined || (pkg.enabled && pkg.rows.some(row => row.phase === 'failed'))) return 'problem' return pkg.enabled ? 'running' : 'disabled' } +/** The danger tag a status carries. */ +function StatusTag({ status, t }: { readonly status: PackageStatus; readonly t: Translate }): ReactNode { + const key = STATUS_TAG_KEYS[status] + return key === undefined ? null : {t(key)} +} + /** The head every card shares: the artwork, the name that opens the page beside its tags, its one-liner, and what sits at the end. */ function CardHead({ title, t, onOpen, icon, tags, description, end }: { readonly title: string @@ -529,7 +547,10 @@ function updateAvailable(pkg: PackageView): boolean { || ((target.spec.startsWith('link:') || pkg.source?.startsWith('link:') === true) && pkg.source !== target.spec) } -/** One package as a card that opens its page: its name, its one-liner, its tags, and its bundle switch. */ +/** + * One package as a card that opens its page: its name, its one-liner, its tags, its bundle switch, and why the Host + * skipped it or does not support its platform. + */ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, onSetEnabled }: { readonly pkg: PackageView /** The newer registry version a version check offers. */ @@ -558,7 +579,7 @@ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, on tags={( <> {beta ? {t('statusBeta')} : null} - {status === 'problem' ? {t('statusProblem')} : null} + {pkg.availability === 'missing' ? {t(pkg.installed ? 'statusMissingFiles' : 'statusNotInstalled')} : null} {updateAvailable(pkg) || newer !== undefined ? {t('statusUpdateAvailable')} : null} @@ -567,7 +588,10 @@ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, on end={} /> - {pkg.error?.code === 'unsupported-platform' &&

{managementText(pkg.error, t)}

} + {/* The card names an incompatibility without its requirement list; the page lists them. */} + {pkg.error !== undefined && (status === 'not-running' || pkg.error.code === 'unsupported-platform') + ?

{managementText({ ...pkg.error, incompatible: [] }, t)}

+ : null} ) } @@ -694,10 +718,10 @@ function RowDetail({ pkg, row, t, resolveText, onBack, renderSlot, form }: { /** * One package's page: the crumb back to the list; its icon with its switch * and, for a package the profile installed or a selection the Host can remove, uninstall; its title beside its - * version tag, its beta tag, and its problem tag; the package name the title + * version tag, its beta tag, and its problem or not-running tag; the package name the title * stands for; its one-liner; the Host's problem when it reports one; the * configuration the bundle registered for itself; its rows with their switches - * and configure controls; and where it comes from. + * and configure controls, unless the Host reports an error and no rows; and where it comes from. */ function PackageDetail({ pkg, t, resolveText, busy, rowBusy, configured, configure, renderSlot, inMore, versions, detail, @@ -779,7 +803,7 @@ function PackageDetail({

{title}

{pkg.version === undefined ? null : {t('versionTag', { version: pkg.version })}} {beta ? {t('statusBeta')} : null} - {status === 'problem' ? {t('statusProblem')} : null} + {pkg.availability === 'missing' ? {t(pkg.installed ? 'statusMissingFiles' : 'statusNotInstalled')} : null} {updateAvailable(pkg) || newer !== undefined ? {t('statusUpdateAvailable')} : null} {renderSlot('plugins.detail.badge', { subject })} @@ -799,7 +823,8 @@ function PackageDetail({ ) : null} - {pkg.availability === 'missing' ? null : ( { pkg({ name: '@deepseek-ai/dsh-web-app', installed: false, removable: false }), pkg({ name: 'dsh-protected', readOnlyReason: 'management-required' }), pkg({ name: '@acme/dsh-tool', enabled: false }), - // Selected by the profile but not a bundle: a problem the person can switch off, in the profile's own group. + // Selected by the profile but not a bundle: its layer is skipped, so it reads as not running. pkg({ name: 'dsh-selected', installed: false, error: { code: 'not-bundle' } }), pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', installed: false, optional: true, removable: false, enabled: false }), ], @@ -747,7 +747,7 @@ describe('PluginManagerPage', () => { expect(cards.map(card => card.getAttribute('data-plugin-package'))).toEqual([ '@deepseek-ai/dsh-experimental-voice-input-bundle', 'dsh-better-sidebar', 'dsh-broken', 'dsh-protected', '@acme/dsh-tool', 'dsh-selected', ]) - expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'problem']) + expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'not-running']) // Group titles have no counts; the official bundle retains its experimental marker. expect(screen.getByRole('heading', { name: en.bundlesTitle })).toBeTruthy() expect(screen.getByRole('heading', { name: en.extensionsTitle })).toBeTruthy() @@ -755,7 +755,8 @@ describe('PluginManagerPage', () => { expect(screen.getAllByText(en.statusBeta)).toHaveLength(1) expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', '@acme/dsh-tool') })).toHaveProperty('disabled', false) expect(screen.getByText('A sidebar.')).toBeTruthy() - expect(screen.getAllByText(en.statusProblem)).toHaveLength(2) + expect(screen.getAllByText(en.statusProblem)).toHaveLength(1) + expect(screen.getAllByText(en.statusNotRunning)).toHaveLength(1) // The switch acts on the bundle; a bundle the Host cannot read stays off, a protected one stays as it is. fireEvent.click(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })) expect(actions.setEnabled).toHaveBeenCalledWith('dsh-better-sidebar', false) @@ -904,6 +905,51 @@ describe('PluginManagerPage', () => { expect(screen.getByText(`${en.reasonLabel}: native preparation unavailable`)).toBeTruthy() }) + it.each([en, zh])('marks a selected bundle the Host skipped as not running with its reason, keeping its switch on', (dict) => { + const name = 'dsh-late' + const { actions, setLanguage } = renderTab({ packages: [pkg({ name, error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] } })] }) + setLanguage(dict) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('not-running') + expect(within(card).getByText(dict.statusNotRunning)).toBeTruthy() + expect(within(card).queryByText(dict.statusProblem)).toBeNull() + // The card names the incompatibility without the requirement list the page carries. + expect(within(card).getByText(`${dict.reasonIncompatibleVersionUnnamed}${dict.sentenceSeparator}${dict.reasonIncompatibleInstalled}`)).toBeTruthy() + const toggle = within(card).getByRole('switch', { name: dict.enableToggle.replace('{name}', name) }) + expect(toggle.getAttribute('aria-checked')).toBe('true') + fireEvent.click(toggle) + expect(actions.setEnabled).toHaveBeenCalledExactlyOnceWith(name, false) + }) + + it('keeps a selected bundle whose rows run as a problem when the Host reports an error beside them', () => { + renderTab({ packages: [pkg({ error: { code: 'unsupported-platform' }, rows: [row()] })] }) + const card = document.querySelector('[data-plugin-package="dsh-better-sidebar"]') as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('problem') + expect(within(card).getByText(en.statusProblem)).toBeTruthy() + }) + + it('keeps a selected bundle running when only its metadata carries a diagnostic', () => { + const name = 'dsh-better-sidebar' + const error = 'dsh.bundle.listedByDefault must be a boolean' + renderTab({ packages: [pkg({ meta: { error }, rows: [row()] })] }) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('running') + expect(within(card).queryByText(en.statusNotRunning)).toBeNull() + expect(within(card).getByText(en.metadataError.replace('{error}', error))).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(detail.querySelector('[data-plugin-rows]')).not.toBeNull() + }) + + it('lists the rows of a skipped layer whose patch the Host read, none of them live', () => { + const name = 'dsh-late' + renderTab({ packages: [pkg({ name, error: { code: 'unsupported-platform' }, rows: [{ rowId: 'late', moduleName: name, enabled: false, phase: null }] })] }) + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(within(detail).getByText(en.statusNotRunning)).toBeTruthy() + expect(within(detail).getAllByRole('listitem').filter(item => item.hasAttribute('data-plugin-row'))).toHaveLength(1) + }) + it('shows Computer Use permission guidance on the experimental plugins page', () => { const description = 'Review application access before use.' const { actions } = renderTab({ packages: [pkg({ @@ -1617,14 +1663,20 @@ describe('PluginManagerPage', () => { expect(actions.uninstall).toHaveBeenCalledWith('dsh-better-sidebar') fireEvent.click(within(detail).getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })) expect(actions.setEnabled).toHaveBeenCalledWith('dsh-better-sidebar', false) + // A bundle without rows says so. + set({ packages: [pkg()] }) + expect(within(detail).getByText(en.partsEmpty)).toBeTruthy() // A problem and a protection the Host reports read on the page in the dictionary's words; the page leaves with the crumb. set({ packages: [pkg({ error: { code: 'operation-error', diagnostic: 'unreadable' }, readOnlyReason: 'management-required' })] }) expect(within(detail).getByText(`${en.reasonLabel}: unreadable`)).toBeTruthy() expect(within(detail).getByText(en.reasonManagementRequired)).toBeTruthy() expect(within(detail).getByRole('button', { name: en.uninstallLabel.replace('{name}', 'dsh-better-sidebar') })).toHaveProperty('disabled', true) - expect(within(detail).getByText(en.partsEmpty)).toBeTruthy() set({ packages: [pkg({ error: { code: 'not-bundle' } })] }) expect(within(detail).getByText(`${en.reasonLabel}: ${en.reasonNotBundle}`)).toBeTruthy() + // The Host skipped this selected bundle's layer without reading its patch: it is not running, and its rows are unknown. + expect(within(detail).getByText(en.statusNotRunning)).toBeTruthy() + expect(within(detail).queryByText(en.statusProblem)).toBeNull() + expect(detail.querySelector('[data-plugin-rows]')).toBeNull() set({ packages: [pkg({ error: { code: 'operation-error' } })] }) expect(within(detail).getByText(`${en.reasonLabel}: ${en.reasonOperationError}`)).toBeTruthy() // An incompatibility reads from its structured packages in the dictionary's words, one sentence per package. diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index b15c957779..15fa719825 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -45,8 +45,8 @@ en: 45f4cd1ef96bb6d2 zh: f264d25b780ad1dc /deepseek-ai-dsh-client-ui-primitives/further-exploration: - en: daa908e173136285 - zh: 5f8492ce8a4c4e48 + en: 19f1407f92cb8264 + zh: 16205d2db9c91ad1 /deepseek-ai-dsh-client-ui-primitives/model-experience: en: 3120df665299c634 zh: 1d9f365d091d0d2a diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 60151abe0f..825c56a8a2 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -209,7 +209,7 @@ These pages place the atoms in the client stack and the design system. ----- -`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text; editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation. +`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text unless the owner supplies a `QuoteSummary`: its label and body then replace the inline excerpt, assistive technology reads the title and optional detail in place of the label, and the popover shows its title, optional detail, and body on every hover. Editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation. `MarkdownDelegate.getTriggerProps` receives explicit file, URL, or original-image targets and returns gesture props. File paths and line numbers are carried by callbacks. File mentions can supply `contextMenuProps`; `ImageLightbox.contextMenuProps` delegates the original image gesture. An image menu owns Escape and Tab while it holds focus, returning to the preview before closing it. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 83dc9032e7..95f4afe55f 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -209,7 +209,7 @@ kind: "package-library" ----- -`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文;可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。 +`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文,除非所有者提供 `QuoteSummary`:此时行内摘录改为显示其 label 和 body,辅助技术以 title 和可选的 detail 代替 label 朗读,每次悬停时弹层显示其 title、可选的 detail 和 body。可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。 `MarkdownDelegate.getTriggerProps` 接收明确的文件、链接或原图目标并返回手势 props。文件路径与行号通过回调传递。文件引用可提供 `contextMenuProps`;`ImageLightbox.contextMenuProps` 转发原图手势。图片菜单持有焦点时负责 Escape 与 Tab,先返回预览再关闭预览。 diff --git a/packages/client/ui-primitives/src/QuotePreview.module.css b/packages/client/ui-primitives/src/QuotePreview.module.css index 1418d8393c..19be7febf6 100644 --- a/packages/client/ui-primitives/src/QuotePreview.module.css +++ b/packages/client/ui-primitives/src/QuotePreview.module.css @@ -22,6 +22,43 @@ white-space: pre-wrap; } +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.inlineBody { + color: var(--dsw-alias-label-secondary); +} + +.summary { + display: flex; + flex-direction: column; + gap: 4px; + padding: 8px 10px; + font-size: 14px; + line-height: 20px; +} + +.summaryTitle { + color: var(--dsw-alias-state-business-primary); + overflow-wrap: anywhere; +} + +.summaryDetail { + color: var(--dsw-alias-label-secondary); +} + +.summaryBody { + color: var(--dsw-alias-label-primary); + overflow-wrap: anywhere; + white-space: pre-wrap; +} + .source { min-width: 0; padding: 0; diff --git a/packages/client/ui-primitives/src/QuotePreview.tsx b/packages/client/ui-primitives/src/QuotePreview.tsx index 4cc56d2cec..f9a9eb5cd0 100644 --- a/packages/client/ui-primitives/src/QuotePreview.tsx +++ b/packages/client/ui-primitives/src/QuotePreview.tsx @@ -25,10 +25,24 @@ export interface QuotePreviewRemoval { readonly onRemove: () => void } +/** Owner-supplied readable form of a quote whose exact text is long structured content. */ +export interface QuoteSummary { + /** Short inline label shown before `body` in place of the exact text; assistive technology reads `title` and `detail` instead. */ + readonly label: string + /** First popover line, such as a file path; also the label's accessible text. */ + readonly title: string + /** Secondary popover line, such as a line range. */ + readonly detail?: string | undefined + /** Main text, such as a user's comment, shown inline after `label` and in full in the popover. */ + readonly body: string +} + /** Presentation inputs for one compact quote excerpt. */ export interface QuotePreviewProps { - /** Exact selected text rendered inline and exposed in a popover while clipped. */ + /** Exact selected text rendered inline and exposed in a popover while clipped, unless `summary` replaces it. */ readonly text: string + /** Readable replacement for `text`: its label renders inline and its popover opens on every hover. */ + readonly summary?: QuoteSummary | undefined /** Composer-only removal action; omit for inert sent quotes. */ readonly removal?: QuotePreviewRemoval | undefined } @@ -36,10 +50,10 @@ export interface QuotePreviewProps { /** * Render one width-capped quote preview shared by editable drafts and sent messages. * Clipped excerpts open a content-sized, scrollable popover that fits within the viewport. - * @param props - selected text and optional localized removal action. - * @returns a non-navigating quote preview with a full-text popover only while clipped. + * @param props - selected text, optional summary, and optional localized removal action. + * @returns a non-navigating quote preview with a full-text popover only while clipped, or a summary popover. */ -export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element { +export function QuotePreview({ text, summary, removal }: QuotePreviewProps): JSX.Element { const sourceRef = useRef(null) const [truncated, setTruncated] = useState(false) useLayoutEffect(() => { @@ -86,7 +100,15 @@ export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element )} - {text} + + {summary === undefined ? text : ( + <> + + {summary.detail === undefined ? summary.title : `${summary.title} ${summary.detail}`} + {' '}{summary.body} + + )} + ) return ( @@ -95,9 +117,17 @@ export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element grouped fitContent openDelayMs={0} - disabled={!truncated} + disabled={summary === undefined && !truncated} anchor={preview} - content={} + content={summary === undefined + ? + : ( + + )} /> ) } diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 3d590e865e..44dbcd8871 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -136,7 +136,7 @@ export { ImageLightbox } from './ImageLightbox.tsx' export type { ImageLightboxLabels } from './ImageLightbox.tsx' export { QuotePreview } from './QuotePreview.tsx' -export type { QuotePreviewProps, QuotePreviewRemoval } from './QuotePreview.tsx' +export type { QuotePreviewProps, QuotePreviewRemoval, QuoteSummary } from './QuotePreview.tsx' export { formatQuoteText } from './markdown/quote-text.ts' export type { MarkdownMenuTarget } from './markdown/MarkdownDelegate.tsx' diff --git a/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx b/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx index 985dc710ba..740977901d 100644 --- a/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx +++ b/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx @@ -112,6 +112,29 @@ describe('QuotePreview', () => { } }) + it('shows an owner summary inline and in a popover that opens without clipping', async () => { + const text = '## User Comment 1\nFile: src/index.ts\nComment:\nrename this' + const view = render() + const quote = view.container.querySelector('[data-quote-preview]')! + const inline = quote.querySelector('[data-quote-preview-text]')! + expect([...inline.children].map(part => [part.textContent, part.getAttribute('aria-hidden')])) + .toEqual([['index.ts L78', 'true'], ['src/index.ts L78', null], ['rename this', null]]) + expect(view.queryByText(text)).toBeNull() + fireEvent.pointerEnter(quote) + await waitFor(() => { + expect([...document.querySelector('[data-quote-popover]')!.children].map(line => line.textContent)) + .toEqual(['src/index.ts', 'L78', 'rename this']) + }) + view.unmount() + + render() + expect(document.querySelector('[data-quote-preview-text]')?.children[1]?.textContent).toBe('src/index.ts') + fireEvent.pointerEnter(document.querySelector('[data-quote-preview]')!) + await waitFor(() => { + expect([...document.querySelector('[data-quote-popover]')!.children].map(line => line.textContent)).toEqual(['src/index.ts', 'rename this']) + }) + }) + it('contains keyboard and pointer removal events inside the editable preview', () => { const onRemove = vi.fn() const onPointerDown = vi.fn() diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 96bad805a3..1371e74c19 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: 99626c29eb801b6f - zh: 9693d278f467ad90 + en: 68526e7df25338d4 + zh: 3bfdfa01dc9afaec /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index 2db007cce9..fbd7582bd2 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -35,7 +35,7 @@ The destination menu offers a new conversation that the first delivery creates a The repeat editor offers once, minute, hour, day, week, month, and custom rules. Date and clock controls reuse existing pickers. Guided presets produce RRULE; minute and hour intervals start from the current minute in the selected zone. The Custom choice and Customize input do not name either syntax; the input accepts a two-line RRULE or a five-field Cron expression with an explicit zone. RRULE retains the zone in `DTSTART`; Cron retains its expression and selected zone as Cron timing. Complex RRULE values remain verbatim. The shared time parser checks new or changed Custom text before enabling Save; invalid or empty input keeps the draft and explains which field to change. Invalid Custom text offers manual correction, another repeat option, or correction by the Agent. The Host performs the final validation on save. Stored After and At tasks show date and clock fields immediately; a repeated local time uses UTC when needed to retain the exact instant. Every, Daily, and Weekly tasks show the matching controls when their interval or wall-clock precision is representable. Other stored timings remain in Custom and keep their typed timing until replaced. Viewing a task or editing other fields preserves its timing and committed occurrence. -Pause and resume update lifecycle state. Unsaved changes hold pause, resume, Run now, and Delete until you save or discard them. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables its fields, Save, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt. +Pause and resume update lifecycle state. While a pause or resume, a catalog reload, or a deletion is in progress, the toggle keeps its look and focus and ignores activation. During a pause, resume, or Run now request, the rule fields reject input without turning grey, and Close and Discard keep their look and ignore activation. Unsaved changes hold pause, resume, Run now, and Delete until you save or discard them. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables its fields, Save, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt. The list, detail, header, and Session hover show the later of the scheduled occurrence and the Host delivery floor as the next run. Creation and editing show one short minimum-interval hint for per-run conversation targets, read from `schedule.deliveryLimits`; a failed read offers Retry. Scheduled and immediate runs share this limit. diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index b51f75b673..51b523d0b9 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -35,7 +35,7 @@ kind: "package-reference" 重复编辑提供仅一次、每分钟、每小时、每天、每周、每月和自定义规则。日期和时间控件复用已有选择器。引导选项生成 RRULE;分钟和小时间隔从所选时区的当前分钟开始。自定义选项和自定义输入框不提示任何语法名称;输入框接受两行 RRULE 或带显式时区的五字段 Cron。RRULE 在 `DTSTART` 中保留时区;Cron 将表达式和所选时区保留为 Cron 时间类型。复杂 RRULE 保持原文。新的或已修改的自定义文本由共享时间解析器校验,校验通过后才能保存;无效或空输入保留草稿,并说明需要修改的字段。自定义文本无效时,提示手动修改规则、选择其他重复方式,或让智能体修改规则。宿主在保存时执行最终校验。已有 After、At 任务直接显示日期和时间控件;本地时间重复时,必要时使用 UTC 保留准确时点。Every、Daily、Weekly 任务在控件可表示其间隔或钟表时间精度时直接显示对应控件;其他时间规则仍在自定义中显示描述,并在替换前保留原类型。查看任务或编辑其他字段保留其时间规则及已提交发生时点。 -暂停和恢复修改生命周期状态。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用字段、保存、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。 +暂停和恢复修改生命周期状态。暂停或恢复请求、目录重读或删除进行期间,切换按钮保持原有外观和焦点,并忽略点击。暂停、恢复或立即执行请求期间,规则字段拒绝输入但不变灰,关闭和“放弃”保持原有外观并忽略点击。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用字段、保存、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。 列表、详情、页头和会话悬浮内容的下次运行时间,取计划发生时间和宿主最早允许投递时间中较晚的一项。创建和编辑“每次新建对话”时,通过 `schedule.deliveryLimits` 读取宿主配置,以一句短提示显示最小间隔;读取失败可重试。定时与立即执行共用此限制。 diff --git a/packages/client/ui-schedule/src/client/TaskDetail.tsx b/packages/client/ui-schedule/src/client/TaskDetail.tsx index cafd802378..8c1f612643 100644 --- a/packages/client/ui-schedule/src/client/TaskDetail.tsx +++ b/packages/client/ui-schedule/src/client/TaskDetail.tsx @@ -215,10 +215,13 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { ? JSON.stringify(draft) !== JSON.stringify({ ...initial, cwd: initial.cwd || projects.defaultCwd }) : storedDirty const issue = dirty ? taskDraftIssue(draft, changes) : undefined const valid = issue === undefined - const [actionPending, setPending] = useState(false) + const [actionPending, setPending] = useState<'toggle' | 'run' | 'delete' | null>(null) const [actionFailure, setFailure] = useState(null) const saving = cached?.pending === true - const pending = actionPending || saving + const pending = actionPending !== null || saving + // A pause, resume, or run would otherwise flash its controls grey between two enabled states. + const actionHold = actionPending === 'toggle' || actionPending === 'run' + const nativeHold = pending && !actionHold const failure = !pending && dirty && base !== undefined && task !== undefined && base.updatedAt !== task.updatedAt ? 'host.conflict' : actionFailure ?? cached?.failure ?? null const [menuOpen, setMenuOpen] = useState(false) @@ -281,18 +284,20 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } else props.actions.setDraft(key, { base, draft, failure: outcome.failed, ...(task === undefined ? { initial } : {}) }) } const setActive = async (task: ScheduleCatalogEntry): Promise => { - setPending(true) + // The toggle stays focusable while busy, so a second press is ignored here instead of by `disabled`. + if (busy) return + setPending('toggle') const outcome = await hostActions.edit({ id: task.id, action: 'update', patch: { active: task.status !== 'active' }, expectedUpdatedAt: task.updatedAt ?? null }) if (!mounted.current) return - setPending(false) + setPending(null) setFailure(outcome === 'saved' ? null : outcome.failed) } const run = async (id: ScheduleId): Promise => { setMenuOpen(false) - setPending(true) + setPending('run') const outcome = await hostActions.run(id) if (!mounted.current) return - setPending(false) + setPending(null) setFailure(outcome === 'queued' ? null : outcome.failed) } @@ -321,8 +326,10 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
}
{task !== undefined && <> - @@ -346,7 +353,8 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } {onClose !== undefined && } + disabled={nativeHold} aria-disabled={actionHold || undefined} + onClick={() => { if (!actionHold) onClose() }}>}
: failure === 'host.executionPending' ?

{t(failure)}

: failure !== null &&

{t(failure)}

} {draft.target === 'new' && } @@ -404,8 +412,8 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } {(tab === 'rule' || dirty) &&