Merge remote-tracking branch 'origin/master' into chore/cordis-core-rc12

# Conflicts:
#	vendor/README.md
This commit is contained in:
Shigma committed 2026-11-07 14:18:03 +08:00
commit 862e699e27
981 files changed
+24926 -22660

No files matched your search

@@ -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
@@ -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
@@ -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`,成功结果被取消替换前延后附加的上下文仍会保留。
### 进入时已中止会在物化后短路
@@ -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
@@ -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
@@ -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` 来自已校验的截图结果。桥接保留这些元数据,不再次上传或输出图片。调用方落盘或声明图片时使用返回的格式和尺寸。
## 考虑过的替代方案
@@ -9,8 +9,8 @@
en: cdc04139c8d69415
zh: a3fe3e78ada08d95
/agent-note-continuous-cua-hover-without-cross-call-ownership/decision:
en: a25e8c472c084852
zh: 12250574113e110a
en: 125c860c1c568960
zh: 8a2ece1101358200
/agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered:
en: 18d917ee2e909b93
zh: 5b5ad0530f138cda
@@ -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 with `systemPointerHover` enabled. 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 allowing opt-in 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.
@@ -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` 报告执行路径。悬停不按下鼠标按钮,启用 `systemPointerHover` 后可通过系统鼠标悬停禁用控件。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,只有启用该配置时才回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。
[共享 helper](2026-10-09-cua-shared-native-helper.zh.md)串行执行完整的单次操作,不分配跨调用的应用所有权。先发起请求、持有 app 对象和 Session 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。
@@ -9,8 +9,8 @@
en: f96bf1ebc0719fb0
zh: e9a1144f0e76572d
/agent-note-background-hover-and-screenshot-coordinates/decision:
en: 0f45528ea6c5988c
zh: 9bde9df417ddb1ce
en: bdf4d3386521ce00
zh: 96db93177ad96a76
/agent-note-background-hover-and-screenshot-coordinates/alternatives-considered:
en: 5fc4beaf79761c50
zh: 4948333b0020be28
@@ -10,9 +10,9 @@ Hover-only controls can sometimes be revealed without moving the user's pointer.
## Decision
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).
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 returns `HOVER_UNAVAILABLE` by default. Enabling `systemPointerHover` permits the real system pointer fallback. 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.
@@ -10,9 +10,9 @@ Status: implemented
## 决策
原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时回退到真实系统鼠标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。
原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时默认返回 `HOVER_UNAVAILABLE`。启用 `systemPointerHover` 后才允许移动系统光标。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 元数据必须与解码后的原图尺寸一致。
@@ -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
@@ -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.
@@ -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` 结果仍是权限和会话锁定状态的运行时来源。
@@ -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
@@ -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.
@@ -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` 作为它的归属位置。
@@ -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
@@ -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.
@@ -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`;完整浏览器登录路径由源码追踪确认。
@@ -0,0 +1,34 @@
# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption-details.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md
/agent-note-chat-history-consumption-classes-and-interactions:
en: 69ce0866b2608208
zh: 55fdeded5d7a4779
/agent-note-chat-history-consumption-classes-and-interactions/problem:
en: edaa7ca0e55a9c33
zh: 33d2b5ac07760988
/agent-note-chat-history-consumption-classes-and-interactions/proposal:
en: 5e5553981c48d0e2
zh: 1195ac8d64180451
/agent-note-chat-history-consumption-classes-and-interactions/proposal/owners-and-interfaces:
en: efbe7ccc25cf1f42
zh: 3bb8f803677824bd
/agent-note-chat-history-consumption-classes-and-interactions/proposal/data-lifetimes:
en: ffdbe0e796463624
zh: f10bd2ced5748017
/agent-note-chat-history-consumption-classes-and-interactions/proposal/consumption-intent-and-wakeups:
en: db8763250020e58c
zh: 4d9a17f1b209d4f2
/agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads:
en: 21df3db6bc83e702
zh: 43b49ceb7407a422
/agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered:
en: 7b3b9b0c7b8f293b
zh: e20045fc3080418f
/agent-note-chat-history-consumption-classes-and-interactions/acceptance-criteria:
en: 1b22cf3616302960
zh: 418ead8421a91bee
/agent-note-chat-history-consumption-classes-and-interactions/risks:
en: 9a61970e311751ac
zh: b24d0eac7b12af62
@@ -0,0 +1,104 @@
# Agent Note: Chat history consumption classes and interactions
Status: proposed
English | [中文](2026-11-06-chat-history-consumption-details.zh.md)
## Problem
Session owns a history page's network lifetime, while Chat owns whether that page can safely enter the current view. Two-phase loading must reuse existing publication and scrolling capabilities without copying business data, consumption intent, and DOM preservation state into one owner.
## Proposal
[History prefetch and safe consumption](2026-11-06-chat-history-consumption.md) defines user-visible behavior and trade-offs. This note defines class interactions and lifetimes without adding an independent scroll animation or React commit manager.
### Owners and interfaces
| Owner | Data and operations |
|---|---|
| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` prepares and optionally consumes a page; `consumeOlder()` synchronously publishes a valid staged page; `historyLoadStatus` is idle/loading/pendingConsumption/error, and `loadingOlder` derives from loading, including Turn jumps |
| Session request record | Holds generation, starting cursor, page entries, hasMore, Promise, and consumption/invalidation flags; staging does not advance the visible window cursor |
| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; automatic consumption waits or falls back by blocker, while manual consumption captures an anchor and consumes without blocker-wait subscriptions |
| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | Reads internal input/motion state and scrollTop, returns a blocker or native/preserve/prepend, and performs distance measurement and existing anchor algorithms |
| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | Connects existing reading, scroll, content, and size notifications to consumption checks and settles a pending one-shot correction during commit handling |
| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | Requests and consumes through injected callbacks and reads state through useSession; renders a fixed-height history control without retaining Session history data or accumulating historyWasPartial |
```text
ChatNavigation.checkHistory
├─ pendingConsumption + intent=none → retain page until clicked
├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder
├─ pendingConsumption + intent=auto → viewport.historyConsumption
│ ├─ touch/inner-scroll → retain automatic intent before checking motion
│ ├─ motion/pointer/unavailable → return to button
│ ├─ native → consumeOlder
│ ├─ prepend → capture paging position → consumeOlder → correct once after commit
│ └─ preserve → beginPreserving → consumeOlder
├─ loading → no duplicate request; a click records manual intent
├─ error → wait for explicit retry
└─ idle + hasMore + (manual intent or near top without following) → request a page
Session.loadOlder
→ prepareOlder reuses or creates the request
→ await the captured request Promise
→ consumeOlder when request identity remains valid and consumption is not deferred
Session.prepareOlder
→ network prepend → capture the page without publishing eventSource
→ validate progress → pendingConsumption or error
Session.consumeOlder
→ check generation/cursor/consuming
→ synchronous eventSource.prepend → existing Conversation merge and flush
→ clear the request record and publish final status
```
### Data lifetimes
`isOpen` means only that Session `openState === 'open'`; it is independent of whether a page is `pendingConsumption`. `historyWasPartial` is monotonic for one Client Session instance: once its visible window has `hasMore=true`, the fact remains until the instance ends, across component remounts and reconnects, without entering the persistent log.
`prepareOlder()` returns an existing request or creates one, and `loadOlder()` rechecks identity after awaiting that captured request Promise. An obsolete Promise cannot consume a newer page. A default call consumes the prepared page; `deferConsumption` retains a valid nonempty page, while an empty terminal page can immediately confirm exhaustion. Consumption retains the request record and sets `consuming` to prevent synchronous subscriber reentry without borrowing the network loading state.
An ordinary request captures the transport page first. It can be consumed only after the request succeeds and its cursor advances, or an empty page explicitly confirms exhaustion. Failures and empty pages that still claim more history enter error without automatic retry. Window replacement, reconnect, and disposal invalidate old pages; when an in-flight request may have advanced the transport cursor, the existing stream restart restores a baseline before another page is allowed.
`loadThrough(seq)` is explicit navigation: it first adopts a staged page and then uses existing Turn-aligned paging. An ordinary in-flight request remains exclusive, and the caller continues after it settles. A jump publishes its successful prefix once at completion or a later failure, without delaying live appends. `loadingOlder` always equals `historyLoadStatus === 'loading'`.
### Consumption intent and wakeups
An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Touch and actual inner-scroll retain auto before motion is evaluated; after release the current state is checked again. Motion, pointer, or unavailable positioning otherwise returns auto to none. Manual intent bypasses these automatic blockers once a page is available: `beginManualPaging()` uses `beginPaging()` at `scrollTop ≤ 0.5`; elsewhere it calls `beginPreserving()` with `beginPaging()` as fallback. Consumption proceeds even if no anchor is produced. Loading and processing clicks join the current request rather than duplicating it.
Prefetch reuses the existing 500ms reading sample, scrollend, content commits, and size notifications, coalescing them into one rAF check. It uses no IntersectionObserver or additional sample timer and measures nothing in the raw scroll event. Only a ResizeObserver entry for the scroller itself refreshes cached clientHeight during the callback's read phase; column growth does not reread viewport height. Once internal state permits an automatic request, it reads the history control's distance from the viewport and compares it with two cached viewport heights.
`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained automatic intent. Manual consumption has no fold-completion waiting subscription. Without consumption intent, these notifications do not revive an abandoned automatic page.
### Shared anchors and layout reads
For automatic consumption at `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`.
Persistent preservation and one-shot correction use the same `applyPaging()` formula to restore the captured screen position, compensating the inner scrollport before the outer one. They do not add changes in scrollTop since capture: native anchoring may have caused those changes. Their lifetimes differ: one-shot correction neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. A committed transition from `pendingConsumption` to `idle` settles the one-shot record even when the visible Node order is unchanged; a closed view or `error` discards the record without applying it. Geometry invalidation remains conditional on the existing layout-change signal, and no new page token or React publication mechanism is introduced. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation.
Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence.
## Alternatives considered
**Pause publication globally in Conversation.** That also blocks live tail output and expands the cross-view impact.
**Retain a complete window snapshot in Chat.** That copies business data and can overwrite messages received while waiting.
**Store separate coordinates and continuously track the first row for one-shot correction.** That duplicates existing paging anchors and can expand scroll ownership; share the position record and calculations while keeping lifetimes separate.
**Add captured-to-current scroll deltas through `preserveMovement`.** The deltas cannot distinguish reader input from native anchoring for the same prepend, so adding them can compensate twice.
## Acceptance criteria
- Default single-stage calls, deferred consumption, and Turn jumps coexist; an old request cannot consume or overwrite a new one.
- Ordinary events do not revive automatic fallback; touch/inner-scroll continuation, manual completion, and unmount cleanup have focused verification.
- One-shot correction uses the existing screen-restoration formula without persistent observation or duplicate native compensation; persistent and inner preservation do not regress.
- Distance checks use cached viewport height; raw scroll listeners and consumption admission perform no layout reads.
## Risks
Screen restoration uses the measured residual displacement after native anchoring rather than adding scroll-position deltas. It does not preserve arbitrary input movement between capture and application or guarantee an uninterrupted momentum trajectory. Near-zero outer positions, native inner anchoring, and input arriving around the prepend require current-build browser verification.
Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual consumption establishes persistent preservation at consumption time; an already active touch can then enter the paging scroll branch instead of reader sampling, constraining movement until a new input releases the anchor. This [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work) remains unresolved. Manual consumption proceeds without preservation if no anchor can be captured, so that structure has no position-stability guarantee. Cancellation, reconnect, and removal of the selected anchor remain distinct lifecycle cases; a missing anchor cannot provide position preservation. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build.
Reports must identify source/artifact versions, real or synthetic inputs, missing conditions, and cleanup results. V8 function or range hits are not TypeScript line/branch percentages; earlier iteration recordings, Chrome/Safari manual feedback, or a successful build do not establish a complete matrix pass for this proposal.
@@ -0,0 +1,104 @@
# Agent Note: Chat 历史消费的类与交互
Status: proposed
[English](2026-11-06-chat-history-consumption-details.md) | 中文
## Problem
历史页的网络生命周期属于 Session,能否安全进入当前页面属于 Chat。两阶段加载需要复用现有事件发布与滚动能力,不能把业务数据、消费意图和 DOM 保位状态复制到同一个所有者。
## Proposal
用户可见行为与取舍由[历史预取与安全消费](2026-11-06-chat-history-consumption.zh.md)定义。本文规定类之间的调用与生命周期,不增加独立的滚动动画或 React 提交管理。
### 所有者与接口
| 所有者 | 数据与操作 |
|---|---|
| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` 准备并按选项消费一页;`consumeOlder()` 同步发布有效暂存页;`historyLoadStatus` 表达 idle/loading/pendingConsumption/error,`loadingOlder` 从 loading 派生并包含 Turn 跳转 |
| Session 请求记录 | 保存 generation、请求前游标、页内容、hasMore、Promise 与消费/失效标记;缓存页不提前改变可见窗口游标 |
| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;自动按阻塞原因等待或退回按钮,手动采集锚点后消费,不注册阻塞结束等待 |
| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | 读取内部输入/动画状态与 scrollTop,报告阻塞原因或 native/preserve/prepend;执行距离测量和已有锚点算法 |
| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | 把既有阅读、滚动、内容及尺寸通知接到消费检查;在提交阶段结算待执行的一次补偿 |
| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | 通过注入回调请求/消费,通过 useSession 读取状态;固定高度显示历史控件,不保存 Session 历史数据或累计 historyWasPartial |
```text
ChatNavigation.checkHistory
├─ pendingConsumption + intent=none → retain page until clicked
├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder
├─ pendingConsumption + intent=auto → viewport.historyConsumption
│ ├─ touch/inner-scroll → retain automatic intent before checking motion
│ ├─ motion/pointer/unavailable → return to button
│ ├─ native → consumeOlder
│ ├─ prepend → capture paging position → consumeOlder → correct once after commit
│ └─ preserve → beginPreserving → consumeOlder
├─ loading → no duplicate request; a click records manual intent
├─ error → wait for explicit retry
└─ idle + hasMore + (manual intent or near top without following) → request a page
Session.loadOlder
→ prepareOlder reuses or creates the request
→ await the captured request Promise
→ consumeOlder when request identity remains valid and consumption is not deferred
Session.prepareOlder
→ network prepend → capture the page without publishing eventSource
→ validate progress → pendingConsumption or error
Session.consumeOlder
→ check generation/cursor/consuming
→ synchronous eventSource.prepend → existing Conversation merge and flush
→ clear the request record and publish final status
```
### 数据生命周期
`isOpen` 只表达会话 `openState === 'open'`,与某页是否 `pendingConsumption` 无关。`historyWasPartial` 是客户端 Session 实例的单调事实:可见窗口曾有 `hasMore=true` 后保留到实例结束,不随组件重挂载或重连清除,不写持久化日志。
`prepareOlder()` 返回已有请求或创建一个请求,`loadOlder()` 等待捕获的请求 Promise 后再核对身份。旧 Promise 完成不能消费随后创建的新页。默认调用消费准备好的页;`deferConsumption` 保留有效非空页,终态空页可以直接确认耗尽。消费期间保持请求记录并设置 `consuming`,阻止同步订阅者重入,不借用网络 loading 状态。
普通请求先捕获传输返回页,只有请求成功且游标前进,或空页明确表示耗尽时才能消费。失败或空页仍声称有更多则进入 error,不自动重试。窗口替换、重连和销毁使旧页失效;如果在途请求可能已推进传输游标,现有流重启先恢复基线,再允许下一页。
`loadThrough(seq)` 是显式导航:先采用已有待消费页,再沿既有 Turn 对齐规则加载;普通请求在途时保持互斥,由调用方在其结算后继续。跳转的成功前缀在完成或后续失败时一次发布,实时追加不等待它。`loadingOlder` 始终等价于 `historyLoadStatus === 'loading'`。
### 消费意图与唤醒
自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。touch 与实际 inner-scroll 优先于 motion 判断保留 auto,释放后重新检查当前状态;其余 motion、pointer 或 unavailable 使 auto 退回 none。manual 在页面可用时绕过这些自动阻塞:`beginManualPaging()` 在 `scrollTop ≤ 0.5` 时调用 `beginPaging()`;其他位置调用 `beginPreserving()`,并以 `beginPaging()` 兜底。没有产生锚点时仍继续消费。加载和处理状态的点击加入当前请求,不重复请求。
历史预取复用已有 500ms 阅读采样、scrollend、内容提交和尺寸通知,并合并为一次 rAF 检查。不使用 IntersectionObserver,不新增采样计时器,不在原始 scroll 事件中测量。仅 scroller 自身的 ResizeObserver 条目在回调读阶段更新 clientHeight 缓存,column 增长不重新读取视口高度。内部状态允许自动请求时,读取历史控件相对视口的位置,与缓存的两屏高度比较。
`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的自动意图;手动消费不注册折叠结束等待。没有消费意图时这些通知不恢复已经放弃的自动页。
### 锚点复用与布局读取
自动消费在顶部 `scrollTop ≤ 0.5` 时使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。
持续保位和一次补偿用相同的 `applyPaging()` 公式恢复采集时的屏幕位置,先补内层、再补外层。计算不叠加采集后 scrollTop 的变化,因为这些变化可能已经来自原生锚定。两者只区分生命周期:一次补偿不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。已提交的 `pendingConsumption` 到 `idle` 状态转换,即使可见 Node 顺序未变化,也会结算一次补偿记录;视图关闭或进入 `error` 时丢弃记录,不应用补偿。几何失效仍只由已有布局变化信号触发,不增加页 token 或 React 发布机制。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。
距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。
## Alternatives considered
**在 Conversation 全局暂停发布。** 会同时阻止尾部实时输出,扩大跨视图影响。
**在 Chat 保存完整窗口快照。** 复制业务数据,消费时可能覆盖等待期间的新消息。
**为一次补偿另存坐标并持续追踪首行。** 与既有分页锚点重复,并可能扩大滚动控制;共享位置记录和计算,只区分生命周期。
**通过 `preserveMovement` 叠加采集后滚动增量。** 该增量无法区分读者输入与同一次前插的原生锚定,叠加后可能重复补偿。
## Acceptance criteria
- 默认单阶段调用、延迟消费及 Turn 跳转共存,旧请求不能消费或覆盖新请求。
- auto 回退不会被普通事件恢复;触摸与内层滚动续接、manual 完成承诺和卸载清理都有定向验证。
- 一次补偿使用既有屏幕位置恢复公式,不注册持续观察、不重复原生补偿;持续保位和内层补偿不退化。
- 距离读取使用缓存视口高度;原始滚动监听与消费准入不读取布局。
## Risks
屏幕位置恢复使用原生锚定后测得的剩余位移,而不是叠加滚动位置增量。它不保留采集到应用之间任意输入造成的移动,也不保证惯性轨迹连续。外层近零位置、内层原生锚定以及前插附近到达的输入,都需要当前构建的浏览器验证。
显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动消费在消费时建立持续保位;已经进行的触摸随后可能进入 paging 滚动分支而非读者采样,移动受限直到新输入释放锚点。这项[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)仍未解决。手动消费在无法采集锚点时仍继续,因此该结构不保证位置稳定。取消、重连和所选锚点被移除属于不同生命周期情况;锚点缺失时无法提供位置保留。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。
验收报告应列明源码/产物版本、真实或合成输入、未覆盖条件以及清理结果。V8 函数或区间命中不等于 TypeScript 行/分支百分比;早期迭代的录像、Chrome/Safari 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。
@@ -0,0 +1,31 @@
# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md
/agent-note-chat-history-prefetch-and-safe-consumption:
en: b0bb85f8780edc41
zh: f3576c234a2f1a99
/agent-note-chat-history-prefetch-and-safe-consumption/problem:
en: fbdf714be9ea6c90
zh: d9b6c07347812fc1
/agent-note-chat-history-prefetch-and-safe-consumption/proposal:
en: bda6c4b3dfff143e
zh: 4316f6dec6adaa50
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/manual-and-automatic-loading:
en: 9f3707f7d6c3d98e
zh: f8903e2d1d652535
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation:
en: 33f2466b802f3957
zh: 095227215a22b403
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions:
en: dd4eeadd2fccab4b
zh: e05d53e63cc44ddf
/agent-note-chat-history-prefetch-and-safe-consumption/alternatives-considered:
en: 7c6d9d470c5b5c93
zh: dc12846ee0f56aae
/agent-note-chat-history-prefetch-and-safe-consumption/acceptance-criteria:
en: f9efd25288474b8a
zh: 9271fde45be71de6
/agent-note-chat-history-prefetch-and-safe-consumption/risks:
en: ff3b2da49f5fb541
zh: b11afa7556f3f313
@@ -0,0 +1,74 @@
# Agent Note: Chat history prefetch and safe consumption
Status: proposed
English | [中文](2026-11-06-chat-history-consumption.zh.md)
## Problem
With only a Load earlier button, readers must reach the beginning of loaded history before clicking. Prefetch can reduce interruption, but a request that starts in a suitable state can return during touch dragging, a navigation change, or a fold animation. History prepending must not change the existing fold driver or simulate momentum.
## Proposal
Separate requesting history from consuming it. The Client Session retains at most one unconsumed page, and Chat decides whether and when to publish it. It retains the new page rather than an old window snapshot, so waiting does not block streaming at the tail. Class ownership and calls are described in the [technical details](2026-11-06-chat-history-consumption-details.md).
### Manual and automatic loading
A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. Once data is available, the click bypasses automatic motion and input blockers: it uses the first paging anchor at the top, or captures the current reading anchor elsewhere with the paging anchor as fallback, and consumes through existing preservation without waiting for an animation callback. If neither anchor is available, consumption still proceeds without a position guarantee. The operation ends with consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent.
Automatic loading requests history after the reader leaves tail following and comes within two viewport heights of the history control. It reuses the existing 500ms reading sample, scroll completion, content commits, and size notifications, without another polling loop or IntersectionObserver. Detection can therefore wait until the next existing sample.
A cached page and an intent to continue automatically are separate facts. Automatic loading falls back to a button on occasional conflicts instead of waiting for every state to recover. Touch and actual inner scrolling retain continuation so mobile readers need not click after every finger release.
| State when data is ready | Automatic intent | Manual intent |
|---|---|---|
| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume through current-anchor preservation |
| Stationary reading away from the top | Consume with existing reading preservation | Consume with existing reading preservation |
| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Consume through current-anchor preservation |
| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Consume the available page through existing preservation |
| A finger held down or actual inner scrolling | Retain intent before testing motion blockers; recheck afterward | Consume the available page through existing preservation |
| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Consume the available page; no anchor means no position guarantee |
| Tail following resumes after automatic prefetch | Keep the page and cancel automatic consumption | The click has paused tail following |
| Streaming continues at the tail | Does not itself block consumption | Does not itself block consumption |
After fallback, scrolling, animation completion, and content notifications cannot reactivate that cached page; only a click or explicit navigation can adopt it. Requests and unconsumed pages remain mutually exclusive: no duplicate request for a cached page and no timeout that forces insertion.
### Position and status presentation
The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. An automatic prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; manual consumption and stationary preservation retain their existing persistent lifetime. Both modes restore the screen position captured immediately before consumption with the same formula; they differ only in whether preservation remains active afterward. The one-shot path does not reconstruct intervening reader movement or restart momentum. Consumption completion also settles and clears the one-shot record when the visible Node order does not change; view closure or history failure discards it without applying it.
The history control keeps the same height across states. Loading and Processing remain clickable to join the current request or consume the cached page; only confirmed exhaustion disables the button. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row.
### Scope and retained decisions
Do not add `flushSync` or change Conversation publication cadence, fold-batch targets, or ScrollFollow policy. Consumption admission reads only internal state and `scrollTop`; DOM geometry reads belong to distance confirmation and position correction. Do not add an independent persistent head-anchor controller, `batchShift`, or a per-frame compensator.
[One fold motion](../../implemented/architecture/2026-10-13-chat-single-fold-motion.md) and [group-tree exchanges](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.md) retain ownership of folding and grouping decisions; this proposal does not supersede them.
## Alternatives considered
**Prepend every response immediately and compensate continuously.** That makes pagination take over existing motion; this design corrects once at the top and waits or falls back on conflicts.
**Automatically wait for every unsafe state to recover.** That adds coordination obligations for occasional animations, navigation, and automatic continuation; retain touch continuation and manual completion, but return other automatic conflicts to the button.
**Remove staging entirely or discard conflicting pages.** Conflicts can start during a request, and the transport history cursor may already have advanced; retaining one page is simpler than rolling back that cursor.
**Disable loading whenever a Turn is running.** Readers still need history during long replies, so execution state cannot replace the current presentation conditions.
**Separate IO prefetch wakeups and React synchronous-commit control.** Reuse existing sampling and publication, accepting sample latency; do not add commit scheduling without evidence of a concrete failure.
## Acceptance criteria
- Requests, staging, and consumption never duplicate a page request; tail streaming continues.
- Ordinary events do not revive automatic fallback; touch, inner scrolling, and manual clicks retain their specified continuation.
- Stationary and top-edge prepends preserve old content position; ordinary automatic momentum consumption adds no outer JS scroll write.
- Failure, no progress, exhaustion, reconnect, and explicit navigation have defined outcomes without request loops or stale-page consumption.
- Control states have equal height; existing fold-driver behavior is retained, and browser evidence identifies the current build, simulated inputs, and missing cases.
## Risks
One-shot correction restores a captured screen position rather than estimating reader velocity. Input or browser movement between capture and application can therefore affect the resulting motion; validation must cover the actual browser and input sequence. The shared formula does not add scroll-position deltas that could already include native anchoring. See the [technical risks](2026-11-06-chat-history-consumption-details.md#risks).
CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. Manual consumption without a usable anchor can move visible content. It can also establish persistent preservation during an already active touch gesture, constraining that gesture or its momentum until a new reading input releases the anchor; see the [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work).
Audit and measurement are ongoing, so this record remains proposed. Earlier Chrome/Safari manual feedback and headless results from different iterations do not establish a complete matrix pass for the final source; actual scrollbar dragging, same-document reconnect, cross-platform input, and exceptional cleanup paths require separately attributed evidence.
@@ -0,0 +1,74 @@
# Agent Note: Chat 历史预取与安全消费
Status: proposed
[English](2026-11-06-chat-history-consumption.md) | 中文
## Problem
只提供“加载更早”按钮时,读者必须到达已加载历史的开头再点击。提前请求可以减少中断,但请求发出时适合加载,不代表返回时适合前插:读者可能开始触摸拖动、切换导航目标,或者遇到折叠动画。分页不应为了前插历史改变已有折叠驱动或模拟惯性。
## Proposal
将历史请求与消费分开。客户端 Session 最多保留一页未消费的数据,Chat 决定是否以及何时发布它。数据保存为新页而不是旧窗口快照,所以等待不阻止尾部流式输出。类与调用关系见[技术细节](2026-11-06-chat-history-consumption-details.zh.md)。
### 手动与自动加载
手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。数据可用后,点击绕过自动路径的动画和输入阻塞:在顶部使用首条分页锚点,其他位置采集当前阅读锚点并以分页锚点兜底,再通过既有保位路径消费,不等待动画回调。两个锚点都不存在时仍消费,但不保证位置稳定。该操作以消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。
自动加载在读者离开底部跟随、进入距历史控件两屏以内时请求。它复用已有 500ms 阅读采样及滚动结束、内容提交、尺寸通知,不新增轮询或 IntersectionObserver。代价是发现进入预取范围可能延后至下一次已有采样。
缓存是否存在与是否需要自动续接是两个事实。自动操作在低频冲突下退回按钮,不承诺等所有状态恢复;触摸与实际内层滚动仍保留续接,避免要求手机用户每次松手后再点击。
| 数据就绪时的状态 | 自动意图 | 手动意图 |
|---|---|---|
| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 通过当前锚点保位消费 |
| 非顶部静止阅读 | 既有阅读保位,消费 | 既有阅读保位,消费 |
| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 通过当前锚点保位消费 |
| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 数据可用即通过既有保位消费 |
| 手指按住或实际内层滚动 | 优先于动画判断保留意图,结束后重查 | 数据可用即通过既有保位消费 |
| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 消费可用页;没有锚点时不保证位置稳定 |
| 自动预取后恢复底部跟随 | 保留缓存,取消自动消费 | 点击已暂停底部跟随 |
| 底部继续流式输出 | 本身不阻止消费 | 本身不阻止消费 |
退回按钮后,滚动、动画结束和内容通知都不能重新激活该缓存页;只有点击或显式导航可以采用它。请求和待消费页仍然互斥,不为缓存页重复请求,也不超时强行插入。
### 位置与状态展示
会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。自动顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;手动消费和静止保位保持原有持续保位生命周期。两种模式用相同公式恢复消费前刚采集的屏幕位置,只区别于应用后是否继续保位。一次补偿不重建采集期间的读者移动,也不重新启动惯性。即使可见 Node 顺序未变化,消费完成也会结算并清除一次补偿记录;视图关闭或历史失败时直接丢弃,不再应用。
历史控件各状态保持同高。“正在加载”和“正在处理”仍可点击,以加入当前请求或消费缓存;只有确认到头才禁用按钮。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。
### 范围与既有决策
不新增 `flushSync`,不改变 Conversation 发布节奏、折叠批次目标或 ScrollFollow 的跟随策略。消费准入只读内部状态和 `scrollTop`;DOM 几何读取留在距离确认和位置补偿处。不新增独立的持续开头锚点控制器、`batchShift` 或每帧补偿器。
[单一折叠运动](../../implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md)与[分组树交互段](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md)仍拥有折叠和分组决策,本提案不取代它们。
## Alternatives considered
**任意状态下数据到达即前插,再持续补偿。** 需要分页接管已有运动;本方案只在顶部补偿一次,冲突时等待或退回按钮。
**所有不安全状态都自动等待恢复。** 增加低频动画、导航与自动续接的协调义务;保留触摸续接和手动完成,其他自动冲突退回按钮。
**完全取消暂存或直接丢弃冲突页。** 请求途中仍可能发生冲突,而且传输历史游标可能已经前移;保留一页比回滚游标更直接。
**运行中的 Turn 禁止加载。** 长回复期间仍需阅读历史,运行状态不能代替当前界面的消费条件。
**独立 IO 预取唤醒与 React 同步提交控制。** 复用已有采样和发布路径,接受采样延迟;没有具体失败证据时不增加提交调度机制。
## Acceptance criteria
- 请求、暂存与消费期间不重复取页;尾部流式继续更新。
- 自动退回按钮后不会被普通事件恢复;触摸、内层滚动和手动点击保留约定的续接。
- 静止和顶部前插保持旧内容位置;普通自动惯性消费不新增 JS 外层滚动写入。
- 页面失败、无进展、到头、重连和显式导航均有明确结果,不循环请求或消费过期页。
- 控件各状态同高;既有折叠驱动保持行为,真实浏览器验收区分当前构建、输入模拟和未覆盖情况。
## Risks
一次补偿恢复采集的屏幕位置,不估算读者速度。采集到应用之间的输入或浏览器移动可能影响最终运动,因此需要验证实际浏览器和输入序列。共享公式不叠加可能已包含原生锚定的滚动位置增量。见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。
原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。没有可用锚点的手动消费可能移动可见内容。手动消费也可能在已有触摸手势进行中建立持续保位,约束该手势或其惯性,直到新的阅读输入释放锚点;见[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)。
审计与测量尚在进行,本记录保持 proposed。此前 Chrome/Safari 手工反馈和不同迭代的 headless 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。
+5 -5
View File
@@ -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).
@@ -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
+2 -2
View File
@@ -54,7 +54,7 @@ flowchart LR
cfg --> plugin_dsh_base_settings
plugin_dsh_base_authorization["authorization<br/>@deepseek-ai/dsh-authorization"]
cfg --> plugin_dsh_base_authorization
plugin_dsh_base_deepseek_account["deepseek-account<br/>@deepseek-ai/dsh-deepseek-account-platform"]
plugin_dsh_base_deepseek_account["deepseek-account<br/>@deepseek-ai/dsh-deepseek-account"]
cfg --> plugin_dsh_base_deepseek_account
plugin_dsh_base_credentials["credentials<br/>@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` |
+176 -4
View File
@@ -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 {
@@ -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<DeepSeekAccount, 'getPlatformSession' | 'watch'> {
constructor(ctx: Context) { super(ctx, 'deepseekAccount') }
fail = false
identityChangesRequested = false
ended = Promise.withResolvers<undefined>()
reading = Promise.withResolvers<undefined>()
finished = Promise.withResolvers<undefined>()
read: () => Promise<PlatformSession | null> = 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<AccountUpdate> {
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 {
+4 -4
View File
@@ -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
+3 -3
View File
@@ -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.
+3 -3
View File
@@ -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 恢复失败打开原生致命故障恢复弹窗。
+17 -6
View File
@@ -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), {
+8 -1
View File
@@ -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() }
})
+16
View File
@@ -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…',
+15
View File
@@ -1012,6 +1012,21 @@ async function main(): Promise<void> {
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')
+2 -1
View File
@@ -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 {
+2 -1
View File
@@ -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'
+11 -3
View File
@@ -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<undefined>()
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()
})
+71 -1
View File
@@ -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 })
+15 -2
View File
@@ -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<string, string | null>; officeKit: boolean; tools: string[] }
const skills = JSON.parse(body) as {
names: string[]
content: Record<string, string | null>
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([])
+35
View File
@@ -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()
})
})
+1 -1
View File
@@ -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<void> => {
+13 -3
View File
@@ -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<void>((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<void>((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<void> => {
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)
+269 -62
View File
@@ -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<string, Granted>()
/** 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<void>((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }),
close: () => new Promise<void>((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([])
+144 -37
View File
@@ -6,7 +6,7 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import type { Browser, Page, Route } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import type { StreamChunk } from '@deepseek-ai/dsh-llm'
@@ -367,13 +367,71 @@ async function flingTranscript(page: Page, deltaY: number): Promise<void> {
await nextPaint(page)
}
async function wheelToHistoryStart(page: Page): Promise<void> {
for (let attempt = 0; attempt < 12; attempt += 1) {
if ((await scrollGeometry(page)).scrollTop <= 1) break
await wheelTranscript(page, -2_400)
/**
* Hold paging responses so auto-prefetch cannot publish a page mid-gesture.
* @param page - Chat page under test.
* @returns an idempotent release that resumes held responses and awaits them.
*/
async function holdHistoryPages(page: Page): Promise<() => Promise<void>> {
const gate = Promise.withResolvers<undefined>()
const pending = new Set<Promise<void>>()
const hold = (route: Route): Promise<void> => {
const work = gate.promise.then(() => route.continue())
pending.add(work)
return work.finally(() => { pending.delete(work) })
}
await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 })
.toBeLessThanOrEqual(1)
await page.route('**/api/session/page', hold)
let released = false
return async () => {
if (released) return
released = true
gate.resolve(undefined)
// Resume held requests before removing the handler: unregistering with a
// hold still pending lets Playwright handle that route itself, after which
// the delayed continue() fails with "Route is already handled".
while (pending.size > 0) await Promise.all([...pending])
await page.unroute('**/api/session/page', hold)
}
}
/**
* Wait until a released page has landed and the history control stopped changing.
* @param page - Chat page under test.
* @returns the settled rendered row count.
*/
async function settleHistoryPaging(page: Page): Promise<number> {
let rows = -1
await expect.poll(async () => {
if (await page.locator('[data-chat-history]').getAttribute('data-chat-history') === 'loading') return false
const current = await loadedFlowRows(page)
const stable = current === rows
rows = current
return stable
}, { timeout: 30_000 }).toBe(true)
await nextPaint(page)
return rows
}
/**
* Wheel back to the start of the loaded window.
* @param page - Chat page under test.
* @param options - holdPaging keeps auto-prefetch from publishing a page that re-anchors the viewport mid-scroll.
*/
async function wheelToHistoryStart(page: Page, options: { holdPaging?: boolean } = {}): Promise<void> {
const release = options.holdPaging === true ? await holdHistoryPages(page) : undefined
try {
for (let attempt = 0; attempt < 12; attempt += 1) {
if ((await scrollGeometry(page)).scrollTop <= 1) break
await wheelTranscript(page, -2_400)
}
await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 })
.toBeLessThanOrEqual(1)
} finally {
await release?.()
}
// A held page is released at the history edge, where the client publishes it
// as soon as it arrives; settle that prepend before the caller measures.
if (options.holdPaging === true) await settleHistoryPaging(page)
}
async function wheelUntilMounted(page: Page, selector: string, deltaY: number): Promise<void> {
@@ -476,23 +534,32 @@ async function expectMarkerAboveComposer(page: Page, marker: string): Promise<vo
expect(geometry.rowBottom).toBeLessThanOrEqual(geometry.composerTop + GEOMETRY_TOLERANCE)
}
async function loadEarlierWithAnchor(page: Page): Promise<void> {
await wheelToHistoryStart(page)
const older = page.getByRole('button', { name: 'Load earlier', exact: true })
const loading = page.getByRole('button', { name: 'Loading…', exact: true })
await older.waitFor({ timeout: 10_000 })
const anchor = await visibleFlowAnchor(page)
const before = await loadedFlowRows(page)
await older.click()
await expect.poll(async () => (
await loadedFlowRows(page) > before && await loading.count() === 0
), { timeout: 30_000 }).toBe(true)
await nextPaint(page)
if (await page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) {
expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0)
return
async function loadEarlierWithAnchor(page: Page): Promise<boolean> {
// Auto-prefetch may start while scrolling to the button. Hold its response until the reading anchor is captured.
const release = await holdHistoryPages(page)
try {
await wheelToHistoryStart(page)
const history = page.locator('[data-chat-history]')
const older = history.getByRole('button')
await older.waitFor({ timeout: 10_000 })
if (await older.isDisabled()) return false
const anchor = await visibleFlowAnchor(page)
const before = await loadedFlowRows(page)
await older.click()
await release()
await expect.poll(async () => (
await loadedFlowRows(page) > before && await history.getAttribute('data-chat-history') === 'idle'
), { timeout: 30_000 }).toBe(true)
await nextPaint(page)
if (await older.isDisabled()) {
expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0)
return true
}
await expectSameFlowTop(page, anchor)
return true
} finally {
await release()
}
await expectSameFlowTop(page, anchor)
}
async function fileExists(path: string): Promise<boolean> {
@@ -1300,6 +1367,8 @@ describe('web e2e: long Chat scroll contract', () => {
let releaseHistory = (): void => {}
let held = false
let historyRequests = 0
const heldContinued = Promise.withResolvers<undefined>()
let releaseGate: (() => void) | undefined
const gate = new Promise<void>((resolve) => { releaseGate = resolve })
releaseHistory = () => { releaseGate?.() }
@@ -1308,12 +1377,17 @@ describe('web e2e: long Chat scroll contract', () => {
method?: string
payload?: { args?: { request?: { beforeSeq?: number } } }
}
if (!held && request.method === 'session/page'
&& request.payload?.args?.request?.beforeSeq !== undefined) {
const historyRequest = request.method === 'session/page' && request.payload?.args?.request?.beforeSeq !== undefined
if (historyRequest) historyRequests += 1
if (!held && historyRequest) {
held = true
await gate
}
await route.continue()
try {
await route.continue()
} finally {
heldContinued.resolve(undefined)
}
} else await route.continue()
})
const settled = world.scaffold.whenTurnSettled(60_000)
@@ -1325,8 +1399,12 @@ describe('web e2e: long Chat scroll contract', () => {
await world.page.getByText(LIVE_TEXT_FIRST, { exact: false }).last().waitFor({ timeout: 15_000 })
await wheelToHistoryStart(world.page)
const beforeRows = await loadedFlowRows(world.page)
await world.page.getByRole('button', { name: 'Load earlier', exact: true }).click()
await expect.poll(() => held, { timeout: 10_000 }).toBe(true)
const history = world.page.locator('[data-chat-history]')
await expect.poll(() => history.getAttribute('data-chat-history')).toBe('loading')
// The upward gesture already requested the page. A click joins that request even though its label is loading.
await history.getByRole('button').click()
expect(historyRequests).toBe(1)
await wheelTranscript(world.page, 420)
const readerAnchor = await visibleFlowAnchor(world.page)
@@ -1344,6 +1422,9 @@ describe('web e2e: long Chat scroll contract', () => {
} finally {
releaseText()
releaseHistory()
if (held) await heldContinued.promise
// Release both producers before disposing the Session even if an assertion above fails.
await settled
}
await settled
@@ -1353,10 +1434,10 @@ describe('web e2e: long Chat scroll contract', () => {
let additionalPages = 0
while (additionalPages < 8) {
await wheelToHistoryStart(world.page)
if (await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) break
await loadEarlierWithAnchor(world.page)
additionalPages += 1
const before = await loadedFlowRows(world.page)
const consumed = await loadEarlierWithAnchor(world.page)
if (consumed || await loadedFlowRows(world.page) > before) additionalPages += 1
if (await world.page.locator('[data-chat-history]').getByRole('button').isDisabled()) break
}
expect(additionalPages).toBeGreaterThan(0)
// The whole log is loaded: turn 1's unique marker renders in the
@@ -1364,7 +1445,9 @@ describe('web e2e: long Chat scroll contract', () => {
// page remains.
expect(await world.page.locator('[data-conversation-scroll]')
.getByText(HISTORY_FIXTURE.markers.user(1), { exact: false }).count()).toBe(1)
expect(await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count()).toBe(0)
const history = world.page.locator('[data-chat-history]')
expect(await history.getAttribute('data-chat-history')).toBe('idle')
expect(await history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled()).toBe(true)
assertClean(world)
})
}, 180_000)
@@ -1669,9 +1752,33 @@ describe('web e2e: long Chat scroll contract', () => {
await liveRow.click()
await expect.poll(() => liveRow.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
await expectSameFlowTop(world.page, toolAnchor)
await wheelToHistoryStart(world.page)
await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
await expectBottom(world.page)
// This cycle tests disclosure retention, not pagination: keep auto-prefetch from moving its scroll-away endpoint.
const historyGate = Promise.withResolvers<undefined>()
const pendingHistory = new Set<Promise<void>>()
let historyHeld = false
const holdHistory = (route: Route): Promise<void> => {
historyHeld = true
const work = historyGate.promise.then(() => route.continue())
pendingHistory.add(work)
return work.finally(() => { pendingHistory.delete(work) })
}
await world.page.route('**/api/session/page', holdHistory, { times: 1 })
try {
const beforeRows = await loadedFlowRows(world.page)
await wheelToHistoryStart(world.page)
await expect.poll(() => historyHeld, { timeout: 10_000 }).toBe(true)
expect(await loadedFlowRows(world.page)).toBe(beforeRows)
await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
await expectBottom(world.page)
} finally {
historyGate.resolve(undefined)
await Promise.all([...pendingHistory])
await world.page.unroute('**/api/session/page', holdHistory)
}
await expect.poll(async () => {
const state = await world.page.locator('[data-chat-history]').getAttribute('data-chat-history')
return state === 'pendingConsumption' || state === 'idle'
}, { timeout: 10_000 }).toBe(true)
await wheelUntilMounted(world.page, liveRowSelector, -1_100)
const restoredRow = world.page.locator(liveRowSelector)
await restoredRow.waitFor({ timeout: 10_000 })
@@ -1696,7 +1803,7 @@ describe('web e2e: long Chat scroll contract', () => {
)
await loadEarlierWithAnchor(world.page)
await loadEarlierWithAnchor(world.page)
await wheelToHistoryStart(world.page)
await wheelToHistoryStart(world.page, { holdPaging: true })
await wheelTranscript(world.page, 1_300)
const sessionAnchor = await visibleFlowAnchor(world.page)
@@ -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<string, unknown>
value.id = fixtureId
return [JSON.stringify(value), ...eventLines, ''].join('\n')
}
async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise<void> {
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<void>(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<void> {
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<void> {
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()
}
})
})
+55
View File
@@ -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()
}
})
+4 -4
View File
@@ -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')
@@ -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<void> => {
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<void>((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()
+9 -9
View File
@@ -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' },
+7 -8
View File
@@ -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) {
@@ -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
@@ -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
@@ -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 地址":
@@ -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 "添加模型提供商"
@@ -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 请解释这行代码
@@ -1,4 +1,4 @@
- text: Ongoing Goal guard rapid clear clicks
- button "Pause goal"
- button "Edit goal"
- button "Clear goal"
- button "Pause goal"
@@ -1,4 +1,4 @@
- text: Blocked Goal retry with the edited plan
- button "Resume goal"
- button "Edit goal"
- button "Clear goal"
- button "Resume goal"
@@ -1,4 +1,4 @@
- text: Inactive Goal guard rapid clear clicks
- button "Resume goal"
- button "Edit goal"
- button "Clear goal"
- button "Resume goal"
@@ -36,6 +36,7 @@
- option "OpenAI Chat Completions" [selected]
- option "OpenAI Responses"
- option "Anthropic Messages"
- option "Gemini API"
- group "重试策略":
- text: 重试策略
- combobox "重试策略":
@@ -36,6 +36,7 @@
- option "OpenAI Chat Completions"
- option "OpenAI Responses"
- option "Anthropic Messages" [selected]
- option "Gemini API"
- group "重试策略":
- text: 重试策略
- combobox "重试策略":
@@ -36,6 +36,7 @@
- option "OpenAI Chat Completions"
- option "OpenAI Responses"
- option "Anthropic Messages" [selected]
- option "Gemini API"
- group "重试策略":
- text: 重试策略
- combobox "重试策略":
@@ -36,6 +36,7 @@
- option "OpenAI Chat Completions"
- option "OpenAI Responses"
- option "Anthropic Messages" [selected]
- option "Gemini API"
- group "重试策略":
- text: 重试策略
- combobox "重试策略":
@@ -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 地址":
@@ -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 地址":
@@ -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"
@@ -9,9 +9,9 @@
- 'row "CONTEXT, <system-reminder> 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 "<system-reminder> 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, <system-reminder> A skill is a reusable set of task-specific instructions. The following skills are available in this session: <available_skills> 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, <system-reminder> A skill is a reusable set of task-specific instructions. The following skills are available in this session: <available_skills> 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 "<system-reminder> A skill is a reusable set of task-specific instructions. The following skills are available in this session: <available_skills> 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 "<system-reminder> A skill is a reusable set of task-specific instructions. The following skills are available in this session: <available_skills> 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."'
@@ -18,7 +18,12 @@
- button "Split" [disabled]
- text: {{cwd}}/workspace
- button "Reload"
- button "Search files" [expanded]
- complementary "Workspace files":
- button "Search settings"
- searchbox "Search files"
- button "Show hidden entries"
- paragraph
- list:
- listitem:
- button "t6-refresh.txt"
@@ -21,6 +21,11 @@
- button "Split" [disabled]
- text: {{cwd}}/workspace
- button "Reload"
- button "Search files" [expanded]
- complementary "Workspace files":
- button "Search settings"
- searchbox "Search files"
- button "Show hidden entries"
- paragraph
- list:
- listitem: Empty directory
@@ -1,7 +1,9 @@
- text: {{cwd}}/keyboard-project
- button "Reload"
- button "Search files"
- button "Open in Finder"
- button "More ways to open"
- complementary "Workspace files":
- paragraph
- list:
- listitem: Empty directory
@@ -35,6 +35,7 @@
- button "Jump to turn 26"
- button "Jump to turn 27"
- button "Jump to turn 28"
- button "Start of conversation" [disabled]
- text: m1 7/25 {{clock}}
- button "Copy"
- status: Completed
+158 -4
View File
@@ -3,13 +3,13 @@
* workspace and the real dock, across docked and floating panes and a
* phone-width viewport. The package README owns the behavior asserted here.
*/
import { mkdir, writeFile } from 'node:fs/promises'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import { createLaunchEnvironmentSnapshot, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
import { launchWebScaffold, seedSession, watchConsole } from './scaffold.ts'
import { connectFreshWorkspace, saveFailureShot } from './support.ts'
/** Press at the centre of `from`, travel in steps, and release at `to`. */
@@ -290,11 +290,12 @@ it('browses workspace files in tabs that share one pane tree', async () => {
await page.setViewportSize({ width: 1680, height: 1000 })
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 460px !important; }' })
// The workspace command shows the pane's tree, moves the keyboard into it, and keeps the file.
// The workspace command shows the pane's tree, moves the keyboard to its search field, and keeps the file.
await input.focus()
await page.keyboard.press('Control+Alt+p')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => current.evaluate(node => node === document.activeElement)).toBe(true)
await expect.poll(() => navigator.locator('[data-files-search]').evaluate(node => node === document.activeElement)).toBe(true)
await expect.poll(() => current.textContent()).toBe('a.txt')
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await tabs.count()).toBe(tabCount + 1)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
@@ -537,3 +538,156 @@ it('moves a file between the docked column and a floating panel from the file me
await expect.poll(() => floatBody.evaluate(node => node.scrollTop)).toBe(600)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
})
it('searches the whole workspace, respects .gitignore on request, saves exclusion rules, restores the default list, and shows hidden entries', async () => {
const scaffold = await launchWebScaffold()
onTestFinished(() => scaffold.close())
// The scaffold's workspace is a private temporary directory that its close removes.
const root = scaffold.workspaceCwd
await mkdir(join(root, 'vendor', 'deep', 'nested'), { recursive: true })
await writeFile(join(root, 'vendor', 'deep', 'nested', 'widget-copy.ts'), 'export const copy = 3\n')
await mkdir(join(root, 'ignored'))
await writeFile(join(root, 'ignored', 'widget-ignored.ts'), 'export const ignored = 1\n')
await mkdir(join(root, '.git'), { recursive: true })
await writeFile(join(root, '.gitignore'), 'ignored/\n')
await writeFile(join(root, '.hidden-widget.txt'), 'hidden\n')
await writeFile(join(root, 'README.md'), '# Readme\n')
const seed = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links/session.v3.jsonl', import.meta.url))
await seedSession(scaffold, await readFile(seed, 'utf8'), 'file-search')
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const page = await browser.newPage({ locale: 'en-US', viewport: { width: 1680, height: 1000 } })
onTestFailed(() => saveFailureShot(page, 'web-e2e-file-search'))
const errors = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.locator('[role="treeitem"]').first().click()
await page.locator('[role="treeitem"]').nth(1).click()
await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).waitFor()
await page.locator('[data-sidebar-right-expand]').click()
const column = page.locator('[data-rightbar-col]')
await page.addStyleTag({ content: '[data-sidebar-right-panel] { width: 960px !important; }' })
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
const navigator = column.locator('[data-files-navigator]:visible')
const field = navigator.locator('[data-files-search]')
const body = navigator.locator('[data-files-body]')
const status = navigator.locator('[data-files-search-status]')
const eye = navigator.locator('[data-files-show-hidden]')
const row = (relative: string): Locator => body.locator(`[data-files-path="${root}/${relative}"]`)
await row('README.md').waitFor()
const searchToggle = column.locator('[data-files-search-toggle]')
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('false')
await expect.poll(() => field.count()).toBe(0)
await searchToggle.click()
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => field.evaluate(node => node === document.activeElement)).toBe(true)
// The eye starts closed: the tree leaves out entries whose name starts with `.`.
expect(await eye.getAttribute('aria-pressed')).toBe('false')
expect(await row('.hidden-widget.txt').count()).toBe(0)
// The search walks the whole workspace: a file three directories deep under one the tree never opened matches by name,
// ignoring case, with the match highlighted; the hidden file and the one `.gitignore` ignores are left out.
const deep = 'vendor/deep/nested/widget-copy.ts'
await field.fill('WIDGET')
await expect.poll(() => status.textContent()).toBe('Results: 1')
expect(await body.getAttribute('data-files-view')).toBe('search')
expect(await row(deep).locator('mark').textContent()).toBe('widget')
expect(await row('vendor/deep/nested').count()).toBe(1)
expect(await row('.hidden-widget.txt').count()).toBe(0)
expect(await row('ignored/widget-ignored.ts').count()).toBe(0)
expect(await row('README.md').count()).toBe(0)
expect(await body.locator('[data-files-row="search-incomplete"]').count()).toBe(0)
expect(await body.locator('[data-files-row="search-truncated"]').count()).toBe(0)
await searchToggle.click()
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('false')
await expect.poll(() => field.count()).toBe(0)
await expect.poll(() => searchToggle.evaluate(node => node === document.activeElement)).toBe(true)
expect(await status.textContent()).toBe('Results: 1')
await row(deep).waitFor()
await searchToggle.click()
await expect.poll(() => field.inputValue()).toBe('WIDGET')
await expect.poll(() => field.evaluate(node => node === document.activeElement)).toBe(true)
// A query with `/` matches workspace-relative paths.
await field.fill('nested/widget')
await expect.poll(() => status.textContent()).toBe('Results: 1')
await row(deep).waitFor()
// Clearing the `.gitignore` choice in the settings searches again at once, and the ignored file matches.
await field.fill('widget')
await expect.poll(() => status.textContent()).toBe('Results: 1')
await navigator.locator('[data-files-search-settings-toggle]').click()
const gitignore = navigator.locator('[data-files-search-settings]').getByRole('checkbox', { name: 'Respect ignore files (.gitignore, etc.)', exact: true })
expect(await gitignore.isChecked()).toBe(true)
await gitignore.uncheck()
await page.keyboard.press('Escape')
await expect.poll(() => status.textContent()).toBe('Results: 2')
await row('ignored/widget-ignored.ts').waitFor()
await navigator.locator('[data-files-search-settings-toggle]').click()
await gitignore.check()
await page.keyboard.press('Escape')
await expect.poll(() => status.textContent()).toBe('Results: 1')
// Clearing the text gives the listed tree back, never expanded below the root.
await navigator.getByRole('button', { name: 'Clear search', exact: true }).click()
await expect.poll(() => body.getAttribute('data-files-view')).toBe('tree')
expect(await row('vendor/deep').count()).toBe(0)
expect(await field.inputValue()).toBe('')
expect(await status.count()).toBe(1)
expect(await status.textContent()).toBe('')
await row('README.md').waitFor()
// The magnifier opens the settings; an added path is saved when Escape closes the panel.
const trigger = navigator.locator('[data-files-search-settings-toggle]')
const settings = navigator.locator('[data-files-search-settings]')
const restore = settings.locator('[data-files-settings-restore]')
await trigger.click()
await settings.waitFor()
expect(await settings.getByText('Excluded files and directories', { exact: true }).count()).toBe(1)
for (const name of ['.DS_Store', 'Thumbs.db', '$RECYCLE.BIN', 'System Volume Information']) {
expect(await settings.locator(`[data-files-rule="${name}"]`).count()).toBe(1)
}
// The list is the default list, so there is nothing to restore.
expect(await restore.count()).toBe(0)
const add = settings.getByRole('textbox', { name: 'Add file or directory', exact: true })
await expect.poll(() => add.evaluate(node => node === document.activeElement)).toBe(true)
await add.fill('vendor')
await add.press('Enter')
await settings.locator('[data-files-rule="vendor"]').waitFor()
await page.keyboard.press('Escape')
await expect.poll(() => settings.count()).toBe(0)
expect(await trigger.evaluate(node => node === document.activeElement)).toBe(true)
const stored = (): Promise<string | null> => page.evaluate(() => localStorage.getItem('dsh.sidebar-files.workspace-search.v1'))
expect(await stored()).toContain('"vendor"')
// Exclusion rules narrow only the search; the tree still lists the directory.
await field.fill('widget')
await expect.poll(() => status.textContent()).toBe('Results: 0')
await field.press('Escape')
await expect.poll(() => body.getAttribute('data-files-view')).toBe('tree')
expect(await row('vendor').count()).toBe(1)
// Closing with the magnifier saves an unchecked rule.
await trigger.click()
const excludeVendor = settings.getByRole('checkbox', { name: 'Exclude vendor', exact: true })
await excludeVendor.uncheck()
await trigger.click()
await expect.poll(() => settings.count()).toBe(0)
await trigger.click()
expect(await excludeVendor.isChecked()).toBe(false)
// The restore control, shown while the list differs from the default list, resets it to that list.
await restore.click()
await expect.poll(() => settings.locator('[data-files-rule="vendor"]').count()).toBe(0)
expect(await restore.count()).toBe(0)
await page.keyboard.press('Escape')
await expect.poll(() => settings.count()).toBe(0)
// Back to the defaults, the workspace's stored entry goes.
expect(await stored()).not.toContain('"vendor"')
// The open eye shows hidden entries in the tree.
await eye.click()
await expect.poll(() => eye.getAttribute('aria-pressed')).toBe('true')
await row('.hidden-widget.txt').waitFor()
await eye.click()
await expect.poll(() => row('.hidden-widget.txt').count()).toBe(0)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
}, 120_000)
@@ -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
+6 -2
View File
@@ -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
+177 -29
View File
@@ -43,8 +43,10 @@ const run = promisify(execFile)
* 7 with one failed and one passed check run, one unresolved thread, and a
* required review, and pull request 9, an approved draft whose checks passed.
* `gh pr ready 9` and the REST merge of pull request 9 change what later
* queries report, through `state.json`. `gh pr diff N` prints `pr-N.diff`, or
* fails with `pr-N.refused` on standard error when that file exists, and the raw
* queries report, through `state.json`, which can also move the head of pull
* request 9. The compare API between a pull request's recorded base and its
* head prints `pr-N.diff`, or, when `pr-N.refused` exists, fails with that JSON
* error body and the matching diagnostic as GitHub's HTTP 406 refusal. The raw
* contents API serves `contents.json`, keyed by `path@commit`. Every invocation
* is appended to `calls.jsonl`.
*/
@@ -87,13 +89,24 @@ if (args[0] === 'api' && args[4] === 'POST' && ['repos/octo/demo/pulls/7/comment
process.stdout.write(JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#pullrequestreview-1' }))
process.exit(0)
}
if (args[0] === 'pr' && args[1] === 'diff') {
const refused = join(here, 'pr-' + args[2] + '.refused')
if (existsSync(refused)) {
process.stderr.write(readFileSync(refused, 'utf8'))
const BASE = 'e'.repeat(40)
const heads = () => ({ 7: 'a'.repeat(40), 9: state.head ?? 'b'.repeat(40) })
if (args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')) {
const [, range] = args.at(-1).split('/compare/')
const [base, head] = range.split('...')
const number = Object.entries(heads()).find(([, oid]) => oid === head)?.[0]
if (base !== BASE || number === undefined) {
process.stderr.write('gh: Not Found (HTTP 404)\\n')
process.exit(1)
}
await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve))
const refused = join(here, 'pr-' + number + '.refused')
if (existsSync(refused)) {
const message = readFileSync(refused, 'utf8')
process.stdout.write(JSON.stringify({ message, errors: [{ resource: 'PullRequest', field: 'diff', code: 'too_large' }], status: '406' }))
process.stderr.write('gh: ' + message + ' (HTTP 406)\\n')
process.exit(1)
}
await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + number + '.diff'), 'utf8'), resolve))
process.exit(0)
}
if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.raw+json') {
@@ -120,25 +133,31 @@ if (args[0] === 'api' && args[1] === 'graphql') {
})
const pulls = {
7: {
number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false,
id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false,
updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40),
baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED',
reviewThreads: { nodes: [{ isResolved: false }] },
reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] },
commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: {
pageInfo: { hasNextPage: true, endCursor: 'checks-100' },
nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)),
} } } }] },
},
9: {
number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED',
id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED',
isDraft: !state.ready, updatedAt: '2026-10-09T00:00:00Z', closedAt: state.mergedAt, author: { login: 'octo' },
headRefName: 'feat/merge', headRefOid: state.head ?? 'b'.repeat(40), baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE',
mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', reviewThreads: { nodes: [] },
headRefName: 'feat/merge', headRefOid: heads()[9], baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE',
mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED',
reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: {
pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')],
} } } }] },
},
}
if (query.includes('pullRequest(number: $number)')) {
const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length))
process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, baseRefOid: BASE } } } }))
process.exit(0)
}
if (query.includes('node(id: $id)')) {
process.stdout.write(JSON.stringify({ data: { node: { contexts: {
pageInfo: { hasNextPage: false, endCursor: null },
@@ -165,13 +184,14 @@ process.exit(1)
/** Head commit of pull request 7 in the GitHub CLI double. */
const HEAD7 = 'a'.repeat(40)
/** What gh 2.100 prints for the diff of pull request 9 when GitHub refuses it for having over 300 files. */
const PR9_REFUSAL = [
'could not find pull request diff: HTTP 406: Sorry, the diff exceeded the maximum number of files (300). Consider using \'List pull '
+ 'requests files\' API or locally cloning the repository instead. (https://api.github.com/repos/octo/demo/pulls/9)',
'PullRequest.diff too_large',
'',
].join('\n')
/** Patch of pull request 9: one line added to each of 301 files, more than the pull request diff endpoint accepts. */
const PR9_DIFF = Array.from({ length: 301 }, (_, index) => [
`diff --git a/merge/m${index}.ts b/merge/m${index}.ts`, 'index 1111111..2222222 100644', `--- a/merge/m${index}.ts`, `+++ b/merge/m${index}.ts`,
'@@ -1 +1,2 @@', ' export {}', `+export const m${index} = ${index}`, '',
].join('\n')).join('')
/** Message of the double's HTTP 406 refusal, which it sends in the error body format GitHub uses for a diff over its size limit. */
const PR9_REFUSAL = 'Sorry, the diff exceeded the size limit.'
/** Line `n` of `src/panel.ts` before (`old`) or after (`new`) pull request 7, which changes lines 2 and 15 of its 20. */
function panelLine(n: number, side: 'old' | 'new'): string {
@@ -243,7 +263,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up'
await writeFile(gh, GH)
await chmod(gh, 0o755)
await writeFile(join(root, 'pr-7.diff'), PR7_DIFF)
await writeFile(join(root, 'pr-9.refused'), PR9_REFUSAL)
await writeFile(join(root, 'pr-9.diff'), PR9_DIFF)
const panelText = `${Array.from({ length: 20 }, (_, index) => panelLine(index + 1, 'new')).join('\n')}\n`
await writeFile(join(root, 'contents.json'), JSON.stringify({ [`src/panel.ts@${HEAD7}`]: panelText }))
const overlay = join(root, 'forge.patch.yml')
@@ -892,10 +912,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()
@@ -1002,21 +1025,43 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
expect(await reviewDialog.getByRole('radio', { name: '评论', exact: true }).isChecked()).toBe(true)
await page.keyboard.press('Escape')
// GitHub refuses the diff of pull request 9 as too large, so its view offers the web page instead of a retry.
// Pull request 9 changes 301 files, more than the pull request diff endpoint accepts; the compare read shows every file.
scaffold.ctx.forgeSession.track(session, DRAFT)
await expect.poll(() => header.getAttribute('aria-pressed'), { timeout: 20_000 }).toBe('false')
await header.click()
const draft = page.locator(`[data-forge-change="${DRAFT}"]`)
await draft.getByRole('button', { name: '展开 #9', exact: true }).click()
await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 })
const refused = page.locator('[data-forge-changes="change"]').filter({ hasText: 'Add the merge button' })
await refused.getByRole('status').filter({ hasText: '变更太大,无法在这里显示' }).waitFor({ timeout: 20_000 })
await refused.getByRole('button', { name: '在浏览器中查看', exact: true }).waitFor()
expect(await refused.getByRole('button', { name: '重试', exact: true }).count()).toBe(0)
const wide = page.locator('[data-forge-changes="change"]').filter({ hasText: 'Add the merge button' })
await wide.getByRole('region', { name: '全部 301 个文件', exact: true }).waitFor({ timeout: 20_000 })
expect(await wide.locator('[data-forge-diff-file]').count()).toBe(301)
// A push moves the head to a commit whose diff GitHub refuses over its size limit, so a newly opened view offers the web page
// instead of a retry.
await page.locator('[data-dockkit-tab]').filter({ hasText: '#9 的变更' }).locator('[data-dockkit-tab-close]').click()
await expect.poll(() => wide.count()).toBe(0)
await writeFile(join(root, 'state.json'), JSON.stringify({ ready: false, mergedAt: null, head: 'd'.repeat(40) }))
await writeFile(join(root, 'pr-9.refused'), PR9_REFUSAL)
scaffold.ctx.forge.refresh({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 })
await expect.poll(() => scaffold.ctx.forge.latest({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 }),
{ timeout: 20_000 }).toMatchObject({ snapshot: { headSha: 'd'.repeat(40) } })
if (await header.getAttribute('aria-pressed') !== 'true') await header.click()
const expand = draft.getByRole('button', { name: '展开 #9', exact: true })
if (await expand.count() > 0) await expand.click()
await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 })
await wide.getByRole('status').filter({ hasText: '变更太大,无法在这里显示' }).waitFor({ timeout: 20_000 })
await wide.getByRole('button', { name: '在浏览器中查看', exact: true }).waitFor()
expect(await wide.getByRole('button', { name: '重试', exact: true }).count()).toBe(0)
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls).toContainEqual(['pr', 'diff', '7', '--repo', 'github.com/octo/demo', '--color', 'never'])
expect(calls).toContainEqual(['pr', 'diff', '9', '--repo', 'github.com/octo/demo', '--color', 'never'])
const compared = (head: string) => [
'api', '--hostname', 'github.com', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff',
`repos/octo/demo/compare/${'e'.repeat(40)}...${head}`,
]
expect(calls).toContainEqual(compared(HEAD7))
expect(calls).toContainEqual(compared('b'.repeat(40)))
expect(calls).toContainEqual(compared('d'.repeat(40)))
expect(calls.some(call => call[0] === 'pr' && call[1] === 'diff')).toBe(false)
expect(calls).toContainEqual([
'api', '--hostname', 'github.com', '-H', 'Accept: application/vnd.github.raw+json', `repos/octo/demo/contents/src/panel.ts?ref=${HEAD7}`,
])
@@ -1170,6 +1215,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) =>
+4 -4
View File
@@ -53,9 +53,9 @@ describe('web e2e: goal bar clear convergence', () => {
const bar = page.locator('[data-goal-bar]')
await bar.waitFor({ timeout: 10_000 })
const pause = bar.getByRole('button', { name: 'Pause goal' })
await expect.poll(() => pause.count(), {
await expect.poll(() => pause.isEnabled(), {
timeout: 10_000,
}).toBe(1)
}).toBe(true)
await pause.hover()
const pauseTooltip = page.getByRole('tooltip', { name: 'Pause goal', exact: true })
await pauseTooltip.waitFor()
@@ -120,7 +120,7 @@ describe('web e2e: goal bar clear convergence', () => {
await input.fill('/goal retry after a blocker')
await input.press('Enter')
const bar = page.locator('[data-goal-bar]')
await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 })
await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true)
const agents = scaffold.ctx.agents.list()
expect(agents).toHaveLength(1)
@@ -140,7 +140,7 @@ describe('web e2e: goal bar clear convergence', () => {
await compareOrRefreshGolden(BLOCKED_EXPECTED, blocked, MODE)
await bar.getByRole('button', { name: 'Resume goal' }).click()
await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 })
await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true)
expect(scaffold.ctx.goals.get(agent)).toMatchObject({
phase: 'active', activation: 'armed', objective: 'retry with the edited plan',
})
+2 -2
View File
@@ -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' })
@@ -33,6 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
let page: Page
let tripwire: ReturnType<typeof watchConsole>
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()
+8 -1
View File
@@ -551,7 +551,14 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser
await catalog.getByRole('treeitem', { name: /Continue preview verification/ }).waitFor()
await catalog.press('Escape')
await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
// Auto-prefetch may already have published the page, and a pointer click can
// land on whatever moved under it; activate the control only while it still
// offers a page, then wait for the oldest seeded row.
const historyEdge = page.locator('[data-chat-history]')
await historyEdge.getByRole('button').evaluate((button) => {
if (!(button instanceof HTMLButtonElement)) throw new Error('history control is not a button')
if (!button.disabled) button.click()
})
await page.getByText(SHOWCASE_OLDEST, { exact: true }).waitFor({ timeout: 15_000 })
await requestLazyChunk(page, site, manifest)
+5
View File
@@ -371,6 +371,11 @@ describe('web e2e: seeded history renders through cold resume', () => {
payload: { args: { request: { maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } } } },
})
await expect.poll(() => page.getByText(PROMPT, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
const history = page.locator('[data-chat-history]')
await expect.poll(() => history.getAttribute('data-chat-history'), { timeout: 10_000 }).toBe('idle')
await expect.poll(() => history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled(), {
timeout: 10_000,
}).toBe(true)
await expect.poll(() => page.getByText('compact', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
await expect.poll(() => page.getByText(/^Compacted \d+ history items \(~\d+ tokens\)$/).count(), {
timeout: 10_000,
+1 -1
View File
@@ -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<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
}),
+1 -1
View File
@@ -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')
+3 -2
View File
@@ -120,8 +120,9 @@ it.each([
await selectDraft()
await deliverPrimary('KeyP')
expect(await files.count()).toBe(1)
expect(await panel.locator('[data-dockkit-pane]').evaluate(pane => document.activeElement === pane)).toBe(true)
expect(await page.evaluate(() => document.getSelection()?.toString())).toBe('Desktop')
// Once the files page is shown, the shortcut opens its search bar and the search field takes the keyboard.
await expect.poll(() => panel.locator('[data-files-search-toggle]').getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => panel.locator('[data-files-search]').evaluate(input => document.activeElement === input)).toBe(true)
await composer.click()
const pane = panel.locator('[data-dockkit-pane]')
await pane.click({ position: { x: 20, y: 2 } })
+2 -1
View File
@@ -183,7 +183,8 @@ describe.skipIf(process.platform === 'win32')('Web sidebar shortcuts', () => {
expect(await paneAppearance()).toEqual([plainPane])
await page.keyboard.press(`${primary}+Shift+,`)
expect(await panel.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }).count()).toBe(1)
expect(await panel.locator('[data-dockkit-pane]').evaluate(pane => document.activeElement === pane)).toBe(true)
await expect.poll(() => panel.locator('[data-files-search-toggle]').getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => panel.locator('[data-files-search]').evaluate(input => document.activeElement === input)).toBe(true)
// Once the reveal's glow has ended, the focused pane draws nothing of its own. file-browser.e2e.ts and the
// seat spec own the glow itself, so this waits for no marker rather than requiring the transient one.
await expect.poll(() => panel.locator('[data-dockkit-pane][data-sidebar-right-flash]').count()).toBe(0)
@@ -182,6 +182,10 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => {
await files.locator('[data-files-row="empty"]').waitFor()
// The directory opener sits in the files page's header, above the tree.
const opener = files.locator('[data-open-target="directory"]')
const tools = files.locator('[data-files-reload], [data-files-search-toggle], [data-open-target="directory"] button')
expect((await tools.evaluateAll(elements => elements.map(element => element.hasAttribute('data-files-reload')
? 'reload' : element.hasAttribute('data-files-search-toggle') ? 'search' : 'open'))).slice(0, 3))
.toEqual(['reload', 'search', 'open'])
await opener.getByRole('button', { name: 'Open in VS Code', exact: true }).click()
await expect.poll(() => launched).toEqual([
{ app: 'vscode', path: workspace.path }, { app: 'vscode', path: workspace.path },
+1 -1
View File
@@ -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<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
}),
+51
View File
@@ -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()
}
})
@@ -129,6 +129,11 @@ describe('web e2e: whole-session stats survive history paging', () => {
// counts, wall times, or token groups.
await page.getByRole('button', { name: 'Load earlier' }).click()
await expect.poll(() => page.getByText('m1', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
const history = page.locator('[data-chat-history]')
await expect.poll(() => history.getAttribute('data-chat-history'), { timeout: 10_000 }).toBe('idle')
await expect.poll(() => history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled(), {
timeout: 10_000,
}).toBe(true)
expect(await strip.textContent()).toBe(stripBeforePaging)
// With the whole log loaded, the window mounts one turn-tail footer per
// settled turn — the loaded-window probe the scroll/perf lanes count now
+10
View File
@@ -62,6 +62,16 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => {
expect(await row.locator('[class*="ioCard"]').count()).toBe(0)
expect(await row.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1)
}
const agentRow = page.locator('[data-tool="list_agents"]').getByRole('listitem').first()
expect(await agentRow.getByRole('button').count()).toBe(0)
expect(await agentRow.locator('svg').count()).toBe(0)
// Read both positions in one browser task so scrolling cannot move the viewport between measurements.
const agentLayout = await agentRow.evaluate((element) => {
const description = element.querySelector('[class*="heading"] > span')!.getBoundingClientRect()
const name = element.querySelector('[class*="subtitle"]')!.getBoundingClientRect()
return { descriptionBottom: description.bottom, nameTop: name.top }
})
expect(agentLayout.descriptionBottom).toBeLessThanOrEqual(agentLayout.nameTop)
const changedTodos = page.locator('[data-tool="todo_write"]').nth(1)
await changedTodos.getByText('1 added · 1 updated · 1 removed', { exact: true }).waitFor()
for (const summary of await page.locator('[data-tool] details > summary').all()) await summary.click()
+24 -1
View File
@@ -155,7 +155,30 @@ describe('web e2e: workspace recency', () => {
const blank = page.getByRole('treeitem').filter({ has: page.getByText('New Session', { exact: true }) })
await expect.poll(() => blank.getAttribute('draggable')).toBe('false')
const blankWarningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
const selectedRowKey = await blank.getAttribute('data-row-key')
expect(selectedRowKey).not.toBeNull()
const restoredRowKeys = await page.locator('[role="treeitem"]:not([aria-expanded])')
.evaluateAll(rows => rows.map(row => row.getAttribute('data-row-key')))
expect(restoredRowKeys).toHaveLength(4)
const workspaceRow = page.getByRole('treeitem').filter({ has: page.getByText(workspaceTitle, { exact: true }) })
// Document load does not restore the Workspace stream or the selected blank Session. Hold the baseline to exercise that gap.
const releaseHeldWorkspace = (): void => { releaseWorkspace?.() }
releaseWorkspace = undefined
holdWorkspace = true
try {
await page.reload({ waitUntil: 'load' })
await expect.poll(() => releaseWorkspace !== undefined, { timeout: 30_000 }).toBe(true)
expect(await workspaceRow.count()).toBe(0)
} finally {
holdWorkspace = false
releaseHeldWorkspace()
}
await workspaceRow.waitFor({ state: 'visible', timeout: 30_000 })
for (const rowKey of restoredRowKeys) {
await page.locator(`[data-row-key="${rowKey}"]`).waitFor({ state: 'visible', timeout: 30_000 })
}
await page.locator(`[data-row-key="${selectedRowKey}"][aria-selected="true"]`)
.waitFor({ state: 'visible', timeout: 30_000 })
await expect.poll(titles).toEqual(['New Session', ...TITLES])
acknowledgeReloadConnectionLoss(tripwire, blankWarningStart)
await pick('Last updated')
+3
View File
@@ -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",
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: bc25cf8be90065dc
zh: ae0def4872a9cdd9
en: b76743a3ff14d2f4
zh: 82431aa3ded14a89
+1 -5
View File
@@ -142,8 +142,6 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount<br/>DeepSeek account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
pkg_api_account_controller["api-account-controller"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -360,7 +358,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
@@ -518,7 +515,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
@@ -704,7 +700,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. |
+1 -5
View File
@@ -144,8 +144,6 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount<br/>DeepSeek account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
pkg_api_account_controller["api-account-controller"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -362,7 +360,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
@@ -520,7 +517,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
@@ -706,7 +702,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 反馈适配器通过同一个注入服务创建独立上报通道。 |
+54 -18
View File
@@ -367,10 +367,10 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page or one listing. */
/** Deployment caps on one page, one listing, or one search. */
export interface Config {
/**
* Inclusive byte cap on one page's text and on one byte window.
@@ -386,6 +386,22 @@ export interface Config {
readonly maxLines: number
/** Cap on returned directory entries; the rest is dropped and reported cut. */
readonly maxEntries: number
/** Budgets on one search's matches, listed files, deadline and ripgrep process. */
readonly search: SearchLimits
}
/** Deployment budgets on one search's results, listed files and process. */
export interface SearchLimits {
/** Cap on returned matches; additional matches report truncation after the bounded scan. */
readonly maxResults: number
/** Cap on files considered from rg output; an extra file terminates rg and reports the search incomplete. */
readonly maxEntries: number
/** Search process termination grace in milliseconds. */
readonly graceMs: number
/** Search deadline in milliseconds; expiry rejects rather than returning partial results. */
readonly timeoutMs: number
/** Byte cap on retained search-process stderr diagnostics. */
readonly stderrMaxBytes: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-api-workspace-files -->
@@ -578,6 +594,22 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<a id="deepseek-aidsh-client-ui-account-notifications"></a>
## `@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
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-plugin-manager -->
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
@@ -625,16 +657,12 @@ export interface Config extends ContactConfig {
developerTools: Volatile<boolean>
}
/** 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 +886,21 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-credentials-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<a id="deepseek-aidsh-deepseek-account-platform"></a>
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<a id="deepseek-aidsh-deepseek-account"></a>
## `@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 +911,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<string, string>
/** 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<string, string>
/** Deadline for each platform HTTP request. */
requestTimeoutMs?: number
@@ -897,7 +929,7 @@ export interface Config {
attemptTimeoutMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-experimental-api-speech-to-text -->
<a id="deepseek-aidsh-experimental-api-speech-to-text"></a>
@@ -1112,13 +1144,15 @@ 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:33`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1142,7 +1176,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1178,6 +1212,8 @@ export interface Config {
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -4990,7 +5026,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) |
@@ -5119,7 +5154,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) |
@@ -5157,6 +5191,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) |
@@ -5212,6 +5247,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them.
| `@deepseek-ai/dsh-util-code-language` | — | [`packages/util/code-language/src/index.ts`](../packages/util/code-language/src/index.ts) |
| `@deepseek-ai/dsh-util-crypto` | — | [`packages/util/crypto/src/index.ts`](../packages/util/crypto/src/index.ts) |
| `@deepseek-ai/dsh-util-file-drag` | — | [`packages/util/file-drag/src/index.ts`](../packages/util/file-drag/src/index.ts) |
| `@deepseek-ai/dsh-util-ripgrep` | — | [`packages/util/ripgrep/src/index.ts`](../packages/util/ripgrep/src/index.ts) |
| `@deepseek-ai/dsh-util-time` | — | [`packages/util/time/src/index.ts`](../packages/util/time/src/index.ts) |
| `@deepseek-ai/dsh-util-values` | — | [`packages/util/values/src/index.ts`](../packages/util/values/src/index.ts) |
| `@deepseek-ai/dsh-util-workspace-path` | — | [`packages/util/workspace-path/src/index.ts`](../packages/util/workspace-path/src/index.ts) |
+54 -18
View File
@@ -369,10 +369,10 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page or one listing. */
/** Deployment caps on one page, one listing, or one search. */
export interface Config {
/**
* Inclusive byte cap on one page's text and on one byte window.
@@ -388,6 +388,22 @@ export interface Config {
readonly maxLines: number
/** Cap on returned directory entries; the rest is dropped and reported cut. */
readonly maxEntries: number
/** Budgets on one search's matches, listed files, deadline and ripgrep process. */
readonly search: SearchLimits
}
/** Deployment budgets on one search's results, listed files and process. */
export interface SearchLimits {
/** Cap on returned matches; additional matches report truncation after the bounded scan. */
readonly maxResults: number
/** Cap on files considered from rg output; an extra file terminates rg and reports the search incomplete. */
readonly maxEntries: number
/** Search process termination grace in milliseconds. */
readonly graceMs: number
/** Search deadline in milliseconds; expiry rejects rather than returning partial results. */
readonly timeoutMs: number
/** Byte cap on retained search-process stderr diagnostics. */
readonly stderrMaxBytes: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-api-workspace-files -->
@@ -580,6 +596,22 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<a id="deepseek-aidsh-client-ui-account-notifications"></a>
## `@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
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-plugin-manager -->
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
@@ -627,16 +659,12 @@ export interface Config extends ContactConfig {
developerTools: Volatile<boolean>
}
/** 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 +888,21 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-credentials-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<a id="deepseek-aidsh-deepseek-account-platform"></a>
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<a id="deepseek-aidsh-deepseek-account"></a>
## `@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 +913,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<string, string>
/** 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<string, string>
/** Deadline for each platform HTTP request. */
requestTimeoutMs?: number
@@ -899,7 +931,7 @@ export interface Config {
attemptTimeoutMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-experimental-api-speech-to-text -->
<a id="deepseek-aidsh-experimental-api-speech-to-text"></a>
@@ -1114,13 +1146,15 @@ 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:33`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1144,7 +1178,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1180,6 +1214,8 @@ export interface Config {
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -4992,7 +5028,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) |
@@ -5121,7 +5156,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) |
@@ -5159,6 +5193,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) |
@@ -5214,6 +5249,7 @@ export interface Config {
| `@deepseek-ai/dsh-util-code-language` | — | [`packages/util/code-language/src/index.ts`](../packages/util/code-language/src/index.ts) |
| `@deepseek-ai/dsh-util-crypto` | — | [`packages/util/crypto/src/index.ts`](../packages/util/crypto/src/index.ts) |
| `@deepseek-ai/dsh-util-file-drag` | — | [`packages/util/file-drag/src/index.ts`](../packages/util/file-drag/src/index.ts) |
| `@deepseek-ai/dsh-util-ripgrep` | — | [`packages/util/ripgrep/src/index.ts`](../packages/util/ripgrep/src/index.ts) |
| `@deepseek-ai/dsh-util-time` | — | [`packages/util/time/src/index.ts`](../packages/util/time/src/index.ts) |
| `@deepseek-ai/dsh-util-values` | — | [`packages/util/values/src/index.ts`](../packages/util/values/src/index.ts) |
| `@deepseek-ai/dsh-util-workspace-path` | — | [`packages/util/workspace-path/src/index.ts`](../packages/util/workspace-path/src/index.ts) |
Loaded 100 of 981 files, more files were not shown because too many files have changed in this diff. Show more