Merge origin/master into feat/cua-windows-2
This commit is contained in:
commit
0c2d8cb5b0
1018 files changed
+28223
-23843
No files matched your search
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: ab63c8127d68d294
|
||||
zh: d3f99489c96ff1d4
|
||||
/agent-note-open-the-session-when-migration-is-required/decision:
|
||||
en: 32627d744a6e7410
|
||||
zh: 2836a95ee5390111
|
||||
en: 310ff84cece51901
|
||||
zh: a9a29e3ba30e03a8
|
||||
/agent-note-open-the-session-when-migration-is-required/alternatives-considered:
|
||||
en: baea781018a49252
|
||||
zh: bcc452029bf229fd
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ Other fork callers omit that option and allow automatic migration.
|
||||
|
||||
The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history.
|
||||
|
||||
When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
|
||||
When migration is required and `subagentCatalog` is absent, Web keeps the Session row's history-opening actions without a format notice, descendant expansion, or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
|
||||
|
||||
Create/adopt, full-text search, and ordinary history opening allow automatic migration.
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho
|
||||
|
||||
`stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。
|
||||
|
||||
在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
|
||||
在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
|
||||
|
||||
create/adopt、全文搜索和普通历史打开允许自动迁移。
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: cdc04139c8d69415
|
||||
zh: a3fe3e78ada08d95
|
||||
/agent-note-continuous-cua-hover-without-cross-call-ownership/decision:
|
||||
en: d1ea8fdc05927896
|
||||
zh: d3039bbb82bc949c
|
||||
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
|
||||
|
||||
An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before falling back to system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check.
|
||||
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
|
||||
|
||||
## 决策
|
||||
|
||||
显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,禁用控件可使用系统鼠标移动路径。调用结束、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 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。
|
||||
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: f96bf1ebc0719fb0
|
||||
zh: e9a1144f0e76572d
|
||||
/agent-note-background-hover-and-screenshot-coordinates/decision:
|
||||
en: 6ac0b77bea25fcf7
|
||||
zh: e50fec9049926fdc
|
||||
en: bdf4d3386521ce00
|
||||
zh: 96db93177ad96a76
|
||||
/agent-note-background-hover-and-screenshot-coordinates/alternatives-considered:
|
||||
en: 5fc4beaf79761c50
|
||||
zh: 4948333b0020be28
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ 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`, `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.
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ 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`、`mouseMove`、`scroll` 和 `drag` 传入 `relative: true` 时接受 0~999 的千分比整数,仅用于坐标目标。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。
|
||||
|
||||
|
||||
+2
-2
@@ -15,5 +15,5 @@
|
||||
en: 32c970ae153e0f6c
|
||||
zh: 8431be0a10ffed15
|
||||
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences:
|
||||
en: 5c6ec60b77f1bff0
|
||||
zh: e1ae568ef3501b7b
|
||||
en: c4b12ca80865e670
|
||||
zh: 396426fad0105eaa
|
||||
@@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps
|
||||
|
||||
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.
|
||||
Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. 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.
|
||||
+1
-1
@@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
|
||||
|
||||
元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。
|
||||
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
|
||||
|
||||
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-07-forge-changes-view-responsiveness.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/bug-fix/2026-11-07-forge-changes-view-responsiveness.md
|
||||
/agent-note-forge-changes-view-responsiveness:
|
||||
en: e809ffea0d880a4b
|
||||
zh: 6725e6a9bd1c3bd1
|
||||
/agent-note-forge-changes-view-responsiveness/problem:
|
||||
en: 77fab27f3d4a4a59
|
||||
zh: 46e0fa8b9ef978a7
|
||||
/agent-note-forge-changes-view-responsiveness/decision:
|
||||
en: 40550cf129ab4c0c
|
||||
zh: 2e9a3597d03ce185
|
||||
/agent-note-forge-changes-view-responsiveness/alternatives-considered:
|
||||
en: c9833999164e8b67
|
||||
zh: 9459a95f307db854
|
||||
/agent-note-forge-changes-view-responsiveness/consequences:
|
||||
en: 2d74147e306ed174
|
||||
zh: f1369020f27f92c0
|
||||
@@ -0,0 +1,41 @@
|
||||
# Agent Note: Forge changes view responsiveness
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-07-forge-changes-view-responsiveness.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The forge changes view of a large change request froze the browser. Opening #7985 (366 files, 37,563 drawn lines) kept the main thread busy for about five seconds, "expand all" for fifteen, and every later state change, such as a poll result, a tool result, a file jump, or a keystroke in the file filter, re-rendered every file section. While the view was visible, the whole app slowed down: two subject-less `:has()` rules in `ui-sidebar-files` made each DOM change restyle the entire document, and the view's hundred thousand nodes made each restyle cost 170–260 ms, so a streaming Agent turn kept the main thread saturated.
|
||||
|
||||
## Decision
|
||||
|
||||
**Scoped `:has()` rules.** The navigator's covering rules name their row through `data-files-navigator-row`, which both hosts of `sidebar.files.navigator` set, so a DOM change outside such a row schedules no document-wide invalidation.
|
||||
|
||||
**Sections draw what changed and what the reader reaches.** `ChangesTab` passes each memoized `DiffFile` values whose identity survives its renders: one handler object, one comment-actions object, and per-file strings and booleans. Tab visibility is a prop of every section, so a visibility change redraws them all; leaving the view measured +57 ms against reading it from a React context, which the client packages forbid business components to do. The scrollport's reach tracker travels in the handler object. An expanded file holds a 22 px row per drawn line until its section first comes within 1200 px of the scrollport, then draws its lines and keeps them. After a jump, the browser's scroll anchoring keeps the target in place while the sections above it draw.
|
||||
|
||||
**Highlighting in the drawing render.** A section highlights its lines in the same render that draws them, as before, so the drawn text is always the file's current text and a native selection keeps its text nodes.
|
||||
|
||||
**Fewer serial reads.** A panel state equal to the published one reaches no follower. `changeRequestDiff` reads the patch and `.gitattributes` together. Snapshots carry the base commit as `baseSha`; `ForgeService.diff` passes it to the provider, and forge-github starts the compare read while its GraphQL read confirms the head.
|
||||
|
||||
**Pixel measurement.** Whether a section is near the scrollport decides whether React renders its lines at all, which CSS cannot express: `content-visibility` only skips layout and paint of nodes that already exist. The client packages offer no injected measurement hook, so one `IntersectionObserver` on the scrollport measures it off the main thread.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**`content-visibility: auto` alone** cut style work as much as scoping the rules did, but kept the React render and Shiki tokenization of every expanded file at open, about 3 s of script, and its placeholder sizes would need estimates for every collapsed and expanded section.
|
||||
|
||||
**Full virtualization that also unmounts far sections** would bound the DOM after long scrolls, but a section holds a comment draft and a text selection, which unmounting loses.
|
||||
|
||||
**Deferred idle-time highlighting** drew plain text and applied tokens once the page was idle and the scrollport still. It kept fast scrolling smooth, but tokens carry their own text, so a file whose content changed at the same path showed its previous text until the next pass, and replacing the plain text nodes collapsed a selection made in the meantime. Against it, highlighting while drawing raised the blocking time of scrolling all of #7985 from 22 ms to 1,634 ms and its longest frame gap from 34 ms to 817 ms; other operations stayed within 0.1 s.
|
||||
|
||||
**The CSS Custom Highlight API** would paint token colors over unchanged text nodes and keep deferral without either defect, but it cannot apply the themes' bold and italic, and its cost over tens of thousands of ranges is unmeasured.
|
||||
|
||||
**Re-aligning a jumped-to section every frame for a second** kept the last file flush with the end of the list, but it also pulled back any scroll it did not start, such as one from find in page; scroll anchoring already holds every other target at the top.
|
||||
|
||||
**Highlighting in a Web Worker** removes tokenization from the main thread entirely, including a heavy grammar's first use, but the shared highlighter in `ui-primitives` owns Shiki; moving it is a separate change for every consumer.
|
||||
|
||||
**A provider-private cache of base commits** would avoid the optional `baseSha` field, but it adds retained state without an owner that knows when a change request stops being watched.
|
||||
|
||||
## Consequences
|
||||
|
||||
Opening #7985 now takes 0.5 s of main-thread work instead of 5.2 s, and file jumps, filtering, polling, and Agent turns no longer produce long tasks. In exchange, the browser's find in page does not see lines of files the reader has not approached, and scrolling onto files in a slow grammar's language, such as C++, highlights them during the scroll, up to about 0.8 s of main-thread work when that grammar is first used. A diff read costs a second compare request when the base commit changed after the latest status.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Agent Note: Forge 变更视图的响应速度
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-07-forge-changes-view-responsiveness.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
大型变更请求的 forge 变更视图会让浏览器卡住。打开 #7985(366 个文件、37,563 个绘制行)时主线程忙约 5 秒,“全部展开”约 15 秒;之后的每次状态变化,例如轮询结果、工具结果、跳转文件或在文件筛选框中按键,都会重渲染所有文件段。视图可见时整个应用都变慢:`ui-sidebar-files` 中两条没有主体的 `:has()` 规则让每次 DOM 变化都重算整个文档的样式,而视图的十万个节点让每次重算耗时 170–260 ms,所以 Agent 流式输出的回合会让主线程一直饱和。
|
||||
|
||||
## Decision
|
||||
|
||||
**限定 `:has()` 规则。** 导航器的遮盖规则通过 `data-files-navigator-row` 指定所在行,`sidebar.files.navigator` 的两个宿主都会设置它,因此这类行之外的 DOM 变化不再触发全文档失效。
|
||||
|
||||
**文件段只绘制变化的部分和读者接近的部分。** `ChangesTab` 传给每个 memo 化的 `DiffFile` 的值在多次渲染之间保持同一标识:一个处理函数对象、一个评论操作对象,以及每个文件的字符串和布尔值。标签页可见性作为每个文件段的参数传入,可见性变化时全部文件段都会重绘;离开视图实测比从 React context 读取多 57 ms,而客户端包禁止业务组件读取 context。滚动区域的接近跟踪对象放在处理函数对象中传递。展开的文件在它的段第一次进入滚动区域 1200 px 范围之前,按每个绘制行 22 px 占位,之后绘制各行并一直保留。跳转后,上方文件段绘制时,浏览器的滚动锚定让目标保持原位。
|
||||
|
||||
**在绘制的渲染中高亮。** 文件段与修复前一样,在绘制各行的同一次渲染中完成高亮,所以画出的始终是文件当前的文本,原生选区所在的文本节点也不会被替换。
|
||||
|
||||
**减少串行读取。** 与已发布状态相同的面板状态不会通知任何关注方。`changeRequestDiff` 同时读取补丁和 `.gitattributes`。快照把基准提交作为 `baseSha` 携带;`ForgeService.diff` 把它传给提供方,forge-github 在 GraphQL 读取确认 head 的同时就开始 compare 读取。
|
||||
|
||||
**像素测量。** 文件段是否接近滚动区域,决定 React 是否渲染它的各行,这一点 CSS 无法表达:`content-visibility` 只能跳过已有节点的布局与绘制。客户端包没有可注入的测量 hook,所以在滚动区域上用一个 `IntersectionObserver`,在主线程之外测量。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只用 `content-visibility: auto`** 减少的样式工作与限定规则相当,但打开时仍要对每个展开文件做 React 渲染和 Shiki 分词,约 3 秒脚本时间,而且每个折叠和展开的段都需要估计占位尺寸。
|
||||
|
||||
**同时卸载远处文件段的完整虚拟化** 可以在长距离滚动后限制 DOM 规模,但文件段持有评论草稿和文本选区,卸载会丢失它们。
|
||||
|
||||
**空闲时延迟高亮** 先画纯文本,等页面空闲且滚动区域静止后再应用 token。它让快速滚动保持流畅,但 token 自带文本,同一路径内容变化后会显示旧文本直到下一轮高亮完成;替换纯文本节点还会清掉期间做出的选区。与它相比,绘制时高亮让滚动整个 #7985 的阻塞时间从 22 ms 增到 1,634 ms,最长帧间隔从 34 ms 增到 817 ms;其他操作的差异在 0.1 秒以内。
|
||||
|
||||
**CSS Custom Highlight API** 可以在不变的文本节点上绘制 token 颜色,保留延迟高亮又没有上述两个问题,但它无法应用主题中的粗体和斜体,几万个范围的绘制成本也没有测过。
|
||||
|
||||
**跳转后一秒内每帧重新对齐** 能让最后一个文件贴紧列表末端,但它也会把不是它发起的滚动拉回去,例如页内查找引起的滚动;而对其他目标,滚动锚定已经能让它们保持在顶部。
|
||||
|
||||
**在 Web Worker 中高亮** 能把分词完全移出主线程,包括重型语法的首次使用,但 Shiki 由 `ui-primitives` 中的共享高亮器持有;迁移它是影响所有使用方的另一项改动。
|
||||
|
||||
**由提供方私有缓存基准提交** 可以省去可选的 `baseSha` 字段,但会引入保留状态,而且没有一个知道变更请求何时不再被 watch 的所有者。
|
||||
|
||||
## Consequences
|
||||
|
||||
打开 #7985 的主线程工作从 5.2 秒降到 0.5 秒,跳转文件、筛选、轮询和 Agent 回合不再产生长任务。代价是:浏览器的页内查找看不到读者尚未接近的文件中的行;滚动到慢语法(例如 C++)的文件时会在滚动中完成高亮,该语法首次使用时最多约 0.8 秒的主线程工作。最新状态之后基准提交有变化时,一次 diff 读取会多一次 compare 请求。
|
||||
@@ -18,11 +18,11 @@
|
||||
en: 16c4ee08b65ead23
|
||||
zh: df80d6e49982615b
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations:
|
||||
en: e112957ed8a48039
|
||||
zh: 37d63f9ea4968fb2
|
||||
en: 082e5a02b092b656
|
||||
zh: ca674a08323d8cc1
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/verification:
|
||||
en: 224b6838130c113f
|
||||
zh: f3d7eb68ab5932fb
|
||||
en: 20d0e1724ebc1247
|
||||
zh: baa89694cea135c8
|
||||
/agent-note-parallel-tool-call-execution-by-per-call-safety/alternatives-considered:
|
||||
en: 17becc038bb7df7c
|
||||
zh: 673d9a9bdfa39edf
|
||||
|
||||
@@ -60,13 +60,13 @@ Any shared state touched during execution must be concurrency-safe. This include
|
||||
|
||||
`maxParallelToolCalls` is a positive AgentLoop deployment cap shared by every agent the factory creates. It defaults to `10`; `1` preserves serial execution. Exact fields and defaults live in the generated [configuration catalog](../../../../docs/config-catalog.md).
|
||||
|
||||
The shipped declarations are conservative. Web search, web fetch, filesystem read, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Filesystem writes and edits, bash tools, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive.
|
||||
The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md).
|
||||
|
||||
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`.
|
||||
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration.
|
||||
Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration, and the working-directory service tests pin per-Session serialization of concurrent directory changes.
|
||||
|
||||
Snapshot coverage pins the visible multi-call transcript: pending calls may overlap while completed results remain model-ordered. PTC mode coverage pins its serial boundary. No provider-backed e2e is required because scheduling is deterministic loop behavior.
|
||||
|
||||
|
||||
@@ -60,13 +60,13 @@ Status: implemented
|
||||
|
||||
`maxParallelToolCalls` 是 AgentLoop 的正整数部署上限,由工厂创建的所有 agent(智能体)共享。默认值为 `10`;`1` 保持串行执行。字段和默认值的精确定义见生成的[配置目录](../../../../docs/config-catalog.zh.md)。
|
||||
|
||||
当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。文件系统写入与编辑、bash 工具、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。
|
||||
当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。
|
||||
|
||||
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。
|
||||
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。
|
||||
|
||||
## 验证
|
||||
|
||||
单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。
|
||||
单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明,工作目录服务测试固定了按会话串行化并发目录变更。
|
||||
|
||||
快照测试固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。PTC mode 测试固定了其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: 12ab239ab0c58e31
|
||||
zh: c32874442ce66041
|
||||
/agent-note-explicit-worktree-creation/decision:
|
||||
en: 92782d5964d1a021
|
||||
zh: 37b385836e9ae2b9
|
||||
en: 571a2d4c5352170b
|
||||
zh: aeb12b849c5f8d31
|
||||
/agent-note-explicit-worktree-creation/alternatives-considered:
|
||||
en: 72d42e892a37b94c
|
||||
zh: 92a14a51c6a89c53
|
||||
|
||||
@@ -18,7 +18,7 @@ Git and directory creation use the mounted subprocess and sandbox providers with
|
||||
|
||||
Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a branch merge policy or a task association database.
|
||||
|
||||
The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
|
||||
The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Inspection trusts `git status` alone, as peer agent products do: edits to skip-worktree or assume-unchanged files are discarded with the checkout, because sparse checkout sets skip-worktree on every file outside its cone and inspecting those bits would retain every sparse checkout. A checkout whose administrative directory holds submodule repositories is retained; a committed embedded repository is not inspected, and Git's refusal of that removal settles the attempt as failed. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用
|
||||
|
||||
离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有分支合并策略或任务关联数据库。
|
||||
|
||||
服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
|
||||
服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。检查与同类 Agent 产品一样只依据 `git status`:skip-worktree 或 assume-unchanged 文件的改动随检出目录一起丢弃,因为 sparse checkout 会给稀疏范围之外的每个文件设置 skip-worktree,检查这些标记会保留每个稀疏检出目录。管理目录中含子模块仓库的检出目录会保留;已提交的内嵌仓库不在检查范围内,Git 拒绝这类删除,本次尝试以失败结束。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
|
||||
+1
-1
@@ -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 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。
|
||||
@@ -16,3 +16,12 @@ docs/persistence-changes/historical-formats/*.schema.json linguist-generated=tru
|
||||
|
||||
# Unified patch blank context lines require their leading space.
|
||||
patches/*.patch whitespace=-blank-at-eol
|
||||
|
||||
# Review layers of the forge changes view (dsh-review-layer), for this repository's own conventions:
|
||||
# plugin locale dictionaries and the session snapshot tree hide with test files, generated bilingual
|
||||
# pairing records join them, and a package's types-only module is part of its interface.
|
||||
packages/*/*/locale/*.json dsh-review-layer=test
|
||||
locales.ts dsh-review-layer=test
|
||||
snapshots/** dsh-review-layer=test
|
||||
*.i18n.yaml dsh-review-layer=test
|
||||
packages/*/*/src/types.ts dsh-review-layer=interface
|
||||
@@ -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` |
|
||||
|
||||
+2
-2
@@ -17,8 +17,8 @@
|
||||
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}}
|
||||
{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}}
|
||||
{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
|
||||
{"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
|
||||
@@ -289,6 +289,55 @@ describe('the shipped Web composition', () => {
|
||||
expect(ctx.agentPresets.defaultId).toBe('standard')
|
||||
})
|
||||
|
||||
it.each(['standard', 'cordis', 'ptc'] as const)('keeps interruption disabled in %s with Team mode off or on', async (preset) => {
|
||||
const handle = await ctx.agents.create({
|
||||
sessionId: SessionId(`preset-interrupt-${preset}`),
|
||||
setup: agentCtx => ctx.agentPresets.mount(agentCtx, preset).then(() => undefined),
|
||||
})
|
||||
try {
|
||||
for (const enabled of [false, true]) {
|
||||
await ctx.agentTeams.setEnabled(handle.agent, enabled)
|
||||
const names = toolNames(ctx, handle.agent)
|
||||
expect(names).not.toContain('interrupt_agent')
|
||||
expect(names).toEqual(expect.arrayContaining(['send_message', 'list_agents', 'wait_agent']))
|
||||
}
|
||||
} finally {
|
||||
await handle.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['standard', 'cordis', 'ptc'] as const)('restores interruption through a complete %s declaration override', async (preset) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-preset-interrupt-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const declaration = composeEntries([webPatches('interrupt migration')])
|
||||
.find(row => row.id === `preset-${preset}`)!.config as {
|
||||
id: string
|
||||
order: number
|
||||
plugins: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[]
|
||||
}
|
||||
const configured = await bootWeb(root, [{
|
||||
id: `preset-${preset}`,
|
||||
config: {
|
||||
...declaration,
|
||||
plugins: composeEntries([[{ insert: declaration.plugins }, {
|
||||
id: 'tool-subagent-control', config: { interrupt: true },
|
||||
}]]),
|
||||
},
|
||||
}])
|
||||
try {
|
||||
const handle = await configured.agents.create({
|
||||
sessionId: SessionId(`preset-interrupt-enabled-${preset}`),
|
||||
setup: agentCtx => configured.agentPresets.mount(agentCtx, preset).then(() => undefined),
|
||||
})
|
||||
try {
|
||||
expect(toolNames(configured)).not.toContain('interrupt_agent')
|
||||
expect(toolNames(configured, handle.agent)).toEqual(expect.arrayContaining([
|
||||
'interrupt_agent', 'send_message', 'list_agents', 'wait_agent',
|
||||
]))
|
||||
} finally { await handle.dispose() }
|
||||
} finally { await configured.fiber.dispose() }
|
||||
})
|
||||
|
||||
it('composes the full agent from `standard`', async () => {
|
||||
const handle = await ctx.agents.create({
|
||||
sessionId: SessionId('preset-standard'),
|
||||
@@ -302,7 +351,7 @@ describe('the shipped Web composition', () => {
|
||||
// depend on ripgrep being present on the machine.
|
||||
expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
|
||||
'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
|
||||
'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image',
|
||||
'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image',
|
||||
'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view',
|
||||
'send_message', 'skill',
|
||||
'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search',
|
||||
@@ -599,9 +648,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 +658,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 +935,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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 恢复失败打开原生致命故障恢复弹窗。
|
||||
|
||||
|
||||
@@ -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() }
|
||||
})
|
||||
|
||||
@@ -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…',
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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,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'
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
@@ -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 })
|
||||
|
||||
@@ -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> => {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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([])
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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,8 +1,12 @@
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- button "全部 2 个文件"
|
||||
- button "分层透镜:全部": 全部
|
||||
- switch "隐藏测试文件"
|
||||
- progressbar "已审阅的文件": 已审阅 0 / 2
|
||||
- text: +4 −2
|
||||
- button "刷新变更"
|
||||
- button "全部折叠"
|
||||
@@ -11,6 +15,7 @@
|
||||
- region "全部 2 个文件":
|
||||
- button "收起 panel.md" [expanded]
|
||||
- text: docs/panel.md 新文件 +2 −0
|
||||
- checkbox "将 panel.md 标记为已审阅"
|
||||
- button "panel.md 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ # Panel"
|
||||
@@ -18,6 +23,7 @@
|
||||
- text: + Shows the change requests of a Session.
|
||||
- button "收起 panel.ts" [expanded]
|
||||
- text: src/panel.ts +2 −2
|
||||
- checkbox "将 panel.ts 标记为已审阅"
|
||||
- button "panel.ts 的更多操作"
|
||||
- button "选择第 L1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 2" [checked]
|
||||
- radio "接口 0"
|
||||
- radio "实现 2"
|
||||
- radio "测试 0"
|
||||
- button "全部 2 个文件"
|
||||
- switch "隐藏测试文件"
|
||||
- progressbar "已审阅的文件": 已审阅 0 / 2
|
||||
- text: +4 −2
|
||||
- button "刷新变更"
|
||||
- button "全部折叠"
|
||||
@@ -12,6 +20,7 @@
|
||||
- region "全部 2 个文件":
|
||||
- button "收起 panel.md" [expanded]
|
||||
- text: docs/panel.md 新文件 +2 −0
|
||||
- checkbox "将 panel.md 标记为已审阅"
|
||||
- button "panel.md 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ # Panel"
|
||||
@@ -19,6 +28,7 @@
|
||||
- text: + Shows the change requests of a Session.
|
||||
- button "收起 panel.ts" [expanded]
|
||||
- text: src/panel.ts +2 −2
|
||||
- checkbox "将 panel.ts 标记为已审阅"
|
||||
- button "panel.ts 的更多操作"
|
||||
- button "选择第 L1 行": "1"
|
||||
- text: export const n1 = 1
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
- text: main
|
||||
- button "基准分支:origin/main": origin/main
|
||||
- text: 包含未提交的修改
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "创建变更请求"
|
||||
- button "分支"
|
||||
- button "全部 0 个文件" [disabled]
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: "Add the pull request panel #7"
|
||||
- button "查看的提交:全部提交": 全部提交
|
||||
- button "提交评审"
|
||||
- button "在浏览器中打开"
|
||||
- radiogroup "分层透镜":
|
||||
- radio "全部 3" [checked]
|
||||
- radio "接口 1"
|
||||
- radio "实现 2"
|
||||
- radio "测试" [disabled]
|
||||
- button "全部 3 个文件"
|
||||
- switch "隐藏测试文件" [checked]
|
||||
- progressbar "已审阅的文件": 已审阅 2 / 3
|
||||
- text: +5 −2
|
||||
- button "刷新变更"
|
||||
- button "全部折叠"
|
||||
- button "左右对比" [pressed]
|
||||
- button "自动换行" [pressed]
|
||||
- button "将文件树移到右侧" [expanded]
|
||||
- region "全部 3 个文件":
|
||||
- button "展开 panel.md"
|
||||
- text: docs/panel.md 新文件 +2 −0
|
||||
- checkbox "将 panel.md 标记为已审阅" [checked]
|
||||
- button "panel.md 的更多操作"
|
||||
- button "展开 panel.ts"
|
||||
- text: src/panel.ts +2 −2
|
||||
- checkbox "将 panel.ts 标记为已审阅" [checked]
|
||||
- button "panel.ts 的更多操作"
|
||||
- button "收起 package.json" [expanded]
|
||||
- text: package.json 新文件 +1 −0
|
||||
- checkbox "将 package.json 标记为已审阅"
|
||||
- button "package.json 的更多操作"
|
||||
- button "选择第 R1 行": "1"
|
||||
- text: "+ { \"name\": \"demo\" }"
|
||||
- separator "调整文件树宽度"
|
||||
- navigation "全部 3 个文件":
|
||||
- textbox "筛选文件…"
|
||||
- button "docs" [expanded]
|
||||
- button "docs/panel.md": panel.md +2 −0
|
||||
- button "src" [expanded]
|
||||
- button "src/panel.ts": panel.ts +2 −2
|
||||
- button "package.json": package.json +1 −0
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Before opening the child
|
||||
|
||||
- tree "Subagent sessions":
|
||||
- treeitem "historical researcher migration-catalog-child · Migration required · not running" [level=1]:
|
||||
- text: historical researcher migration-catalog-child Migration required
|
||||
- treeitem "historical researcher migration-catalog-child · continuable · not running" [level=1]:
|
||||
- text: historical researcher migration-catalog-child
|
||||
- button "Open historical researcher in sidebar"
|
||||
|
||||
# After opening the child
|
||||
|
||||
- tree "Subagent sessions":
|
||||
- treeitem "historical editor migration-catalog-grandchild · Migration required · not running" [level=1]:
|
||||
- text: historical editor migration-catalog-grandchild Migration required
|
||||
- treeitem "historical editor migration-catalog-grandchild · continuable · not running" [level=1]:
|
||||
- text: historical editor migration-catalog-grandchild
|
||||
- button "Open historical editor in sidebar"
|
||||
@@ -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
@@ -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
|
||||
@@ -43,10 +43,14 @@ 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
|
||||
* contents API serves `contents.json`, keyed by `path@commit`. Every invocation
|
||||
* is appended to `calls.jsonl`.
|
||||
* queries report, through `state.json`, which can also move the head of pull
|
||||
* request 9. The compare API serves `compare.json`, keyed by `base...head`, and
|
||||
* otherwise, 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`, and the commit listing of pull
|
||||
* request 7 serves `commits.json`, oldest first. Every invocation is appended to
|
||||
* `calls.jsonl`.
|
||||
*/
|
||||
const GH = `#!/usr/bin/env node
|
||||
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
@@ -87,13 +91,29 @@ 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 chosen = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined
|
||||
if (chosen !== undefined) {
|
||||
process.stdout.write(chosen)
|
||||
process.exit(0)
|
||||
}
|
||||
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 +140,42 @@ 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,
|
||||
updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40),
|
||||
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), baseRefOid: BASE,
|
||||
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', baseRefOid: BASE, 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('commits(first: $first')) {
|
||||
const commits = existsSync(join(here, 'commits.json')) ? JSON.parse(readFileSync(join(here, 'commits.json'), 'utf8')) : []
|
||||
process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40), commits: {
|
||||
totalCount: commits.length, pageInfo: { hasNextPage: false, endCursor: null },
|
||||
nodes: commits.map(commit => ({ commit: {
|
||||
oid: commit.sha, messageHeadline: commit.title, authoredDate: '2026-10-08T00:00:00Z',
|
||||
author: { name: 'Octo', user: { login: 'octo' } }, parents: { nodes: [{ oid: commit.parent }] },
|
||||
} })),
|
||||
} } } } }))
|
||||
process.exit(0)
|
||||
}
|
||||
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 +202,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 {
|
||||
@@ -204,6 +242,53 @@ const PR7_DIFF = [
|
||||
'',
|
||||
].join('\n')
|
||||
|
||||
/** A patch section that adds `lines` as the new file `path`. */
|
||||
function addedSection(path: string, lines: readonly string[]): string[] {
|
||||
return [`diff --git a/${path} b/${path}`, 'new file mode 100644', 'index 0000000..4444444', '--- /dev/null', `+++ b/${path}`,
|
||||
`@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)]
|
||||
}
|
||||
|
||||
/** Commits of pull request 7 in the review fixture, oldest first; the last is its head. */
|
||||
const REVIEW_COMMITS = [
|
||||
{ sha: '1'.repeat(40), parent: 'f'.repeat(40), title: 'Add the pull request panel' },
|
||||
{ sha: '2'.repeat(40), parent: '1'.repeat(40), title: 'Test the panel and translate it' },
|
||||
{ sha: HEAD7, parent: '2'.repeat(40), title: 'Publish the panel schema' },
|
||||
] as const
|
||||
|
||||
/** New files of each review fixture commit after the first, which changes `src/panel.ts` and adds `docs/panel.md`. */
|
||||
const REVIEW_SECTIONS = {
|
||||
test: [
|
||||
...addedSection('src/panel.spec.ts', ['it(\'shows the panel\', () => {})']),
|
||||
...addedSection('locale/zh.json', ['{ "title": "面板" }']),
|
||||
],
|
||||
schema: [
|
||||
...addedSection('package.json', ['{ "name": "demo" }']),
|
||||
...addedSection('docs/schema.json', ['{ "type": "object" }']),
|
||||
],
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is
|
||||
* interface, and the spec, the locale dictionary, which `.gitattributes` places in the test layer, and
|
||||
* `docs/schema.json`, which it marks generated, are tests.
|
||||
*/
|
||||
const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n')
|
||||
|
||||
/** Write the review fixture of pull request 7: its patch, commits, commit ranges, and root `.gitattributes`. */
|
||||
async function writeReviewFixture(root: string): Promise<void> {
|
||||
await writeFile(join(root, 'pr-7.diff'), REVIEW_DIFF)
|
||||
await writeFile(join(root, 'commits.json'), JSON.stringify(REVIEW_COMMITS))
|
||||
await writeFile(join(root, 'compare.json'), JSON.stringify({
|
||||
[`${'1'.repeat(40)}...${'2'.repeat(40)}`]: [...REVIEW_SECTIONS.test, ''].join('\n'),
|
||||
[`${'1'.repeat(40)}...${HEAD7}`]: [...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n'),
|
||||
}))
|
||||
const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record<string, string>
|
||||
for (const commit of ['2'.repeat(40), HEAD7]) {
|
||||
contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\nlocale/*.json dsh-review-layer=test\n'
|
||||
}
|
||||
await writeFile(join(root, 'contents.json'), JSON.stringify(contents))
|
||||
}
|
||||
|
||||
async function git(cwd: string, ...args: string[]): Promise<string> {
|
||||
const { stdout } = await run('git', args, { cwd, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } })
|
||||
return stdout.trim()
|
||||
@@ -243,7 +328,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')
|
||||
@@ -462,10 +547,14 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi
|
||||
await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
|
||||
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
|
||||
expect(events.flatMap((event) => {
|
||||
const record = pluginRecordOf(event)
|
||||
return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
|
||||
})).toEqual([{ action: 'reference', url: PULL }])
|
||||
await expect.poll(async () => {
|
||||
await scaffold.ctx.sessionPersistence.flush()
|
||||
const boundEvents = await readPersistedEvents(scaffold, sessionId)
|
||||
return boundEvents.flatMap((event) => {
|
||||
const record = pluginRecordOf(event)
|
||||
return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
|
||||
})
|
||||
}).toEqual([{ action: 'reference', url: PULL }])
|
||||
const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
|
||||
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url'])
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
@@ -1005,21 +1094,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}`,
|
||||
])
|
||||
@@ -1064,6 +1175,8 @@ it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across
|
||||
return { path: element.getAttribute('data-forge-diff-file'), line: line.dataset.newLine,
|
||||
offset: line.getBoundingClientRect().top - top, scrollTop: viewport.scrollTop }
|
||||
})
|
||||
// An expanded file draws its lines once the reader scrolls near it.
|
||||
await file.scrollIntoViewIfNeeded()
|
||||
await code.waitFor()
|
||||
for (const width of [240, 320]) {
|
||||
if (width === 320) {
|
||||
@@ -1141,6 +1254,11 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre
|
||||
expect(await scroll.evaluate(element => document.activeElement === element)).toBe(true)
|
||||
await page.keyboard.press('ArrowRight')
|
||||
await expect.poll(() => tree.getByRole('button', { name: 'README.md', exact: true }).getAttribute('aria-current')).toBe('true')
|
||||
// The last file draws its lines after the jump, and scroll anchoring adjusts the position at the next layout.
|
||||
await c.locator('[data-review-code]').first().waitFor()
|
||||
await scroll.evaluate(() => new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) })
|
||||
}))
|
||||
const lastPosition = await scroll.evaluate(element => element.scrollTop)
|
||||
const lastBox = await c.boundingBox(), viewport = await scroll.boundingBox()
|
||||
if (lastBox === null || viewport === null) throw new Error('The last file and scroll viewport must be rendered')
|
||||
@@ -1604,3 +1722,184 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i
|
||||
await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor()
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
/** Open the change request view of pull request 7 in full screen, its tree on the left. */
|
||||
async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly view: ReturnType<Page['locator']>; readonly sessionId: SessionId }> {
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
const sessionId = await settled
|
||||
const session = scaffold.ctx.sessions.get(sessionId)
|
||||
if (session === undefined) throw new Error('Session must stay loaded')
|
||||
scaffold.ctx.forgeSession.track(session, PULL)
|
||||
await page.locator('[data-forge-header]').click()
|
||||
await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
|
||||
await page.getByRole('button', { name: '全屏', exact: true }).click()
|
||||
const view = page.locator('[data-forge-changes="change"]')
|
||||
await view.locator('[data-forge-diff-file="src/panel.ts"]').waitFor({ timeout: 20_000 })
|
||||
return { view, sessionId }
|
||||
}
|
||||
|
||||
/** Paths of the diff sections a changes view shows, in order. */
|
||||
async function shownPaths(view: ReturnType<Page['locator']>): Promise<(string | null)[]> {
|
||||
return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file')))
|
||||
}
|
||||
|
||||
it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => {
|
||||
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers')
|
||||
await writeReviewFixture(root)
|
||||
const { view } = await openReview(page, scaffold)
|
||||
const lens = view.getByRole('radiogroup', { name: '分层透镜', exact: true })
|
||||
const tree = view.getByRole('navigation')
|
||||
await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部6', '接口1', '实现2', '测试3'])
|
||||
// The lens spans the file tree with the filter field's insets, and its divider continues the tree's border.
|
||||
const [lensBox, fieldBox, cellBox, treeBox] = await Promise.all([
|
||||
lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=..').boundingBox(), tree.locator('xpath=..').boundingBox(),
|
||||
])
|
||||
if (lensBox === null || fieldBox === null || cellBox === null || treeBox === null) throw new Error('Lens and tree must be visible')
|
||||
expect([lensBox.x, lensBox.x + lensBox.width]).toEqual([fieldBox.x, fieldBox.x + fieldBox.width])
|
||||
expect(cellBox.x + cellBox.width).toBe(treeBox.x + treeBox.width)
|
||||
|
||||
await lens.getByRole('radio', { name: /^接口/ }).click()
|
||||
await expect.poll(() => shownPaths(view)).toEqual(['package.json'])
|
||||
await lens.getByRole('radio', { name: /^测试/ }).click()
|
||||
await expect.poll(() => shownPaths(view)).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts'])
|
||||
await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click()
|
||||
await expect.poll(() => shownPaths(view)).toEqual(['docs/panel.md', 'src/panel.ts', 'package.json'])
|
||||
expect(await tree.getByRole('button', { name: 'src/panel.spec.ts', exact: true }).count()).toBe(0)
|
||||
expect(await lens.getByRole('radio', { name: /^测试/ }).isDisabled()).toBe(true)
|
||||
|
||||
const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true })
|
||||
await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 0 / 3')
|
||||
const docs = view.locator('[data-forge-diff-file="docs/panel.md"]')
|
||||
await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).check()
|
||||
await expect.poll(() => docs.getAttribute('data-expanded')).toBe(null)
|
||||
await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 3')
|
||||
const panel = view.locator('[data-forge-diff-file="src/panel.ts"]')
|
||||
await panel.getByText('export const n2 = \'two\'', { exact: true }).first().click()
|
||||
await page.keyboard.press('v')
|
||||
await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed')
|
||||
await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3')
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'),
|
||||
await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE)
|
||||
|
||||
await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click()
|
||||
const commits = view.getByRole('button', { name: '查看的提交:全部提交', exact: true })
|
||||
await commits.click()
|
||||
const menu = page.locator('[data-forge-commit-menu]')
|
||||
await expect.poll(() => menu.getByRole('menuitem').evaluateAll(rows => rows.map(row => row.querySelector('[data-forge-commit]')?.getAttribute('data-forge-commit') ?? 'all')))
|
||||
.toEqual(['all', '1'.repeat(40), '2'.repeat(40), HEAD7])
|
||||
await menu.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click()
|
||||
await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts'])
|
||||
expect(await view.getByRole('button', { name: '提交评审', exact: true }).isDisabled()).toBe(true)
|
||||
await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click()
|
||||
await page.locator(`[data-forge-commit="${HEAD7}"]`).click({ modifiers: ['Shift'] })
|
||||
await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).waitFor()
|
||||
await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json'])
|
||||
await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3'])
|
||||
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[])
|
||||
// The whole pull request is read from its recorded base; chosen commits are read from the first one's parent.
|
||||
expect(calls.filter(args => args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')).map(args => args.at(-1))
|
||||
.filter(path => path?.includes(`/compare/${'e'.repeat(40)}...`) === false)).toEqual([
|
||||
`repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`,
|
||||
])
|
||||
await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click()
|
||||
await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click()
|
||||
await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6)
|
||||
await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a mark when the file changes again, and views branch commits', async () => {
|
||||
const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-review-local', 'normal', { branch: 'feat' })
|
||||
await git(project, 'update-ref', 'refs/remotes/origin/main', 'main')
|
||||
await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
|
||||
await mkdir(join(project, 'src'))
|
||||
for (const [path, text, message] of [
|
||||
['src/app.ts', 'export const app = 1\n', 'Add the app'],
|
||||
['src/app.spec.ts', 'it(\'runs\', () => {})\n', 'Test the app'],
|
||||
] as const) {
|
||||
await writeFile(join(project, path), text)
|
||||
await git(project, 'add', path)
|
||||
await git(project, 'commit', '--quiet', '-m', message)
|
||||
}
|
||||
await writeFile(join(project, 'notes.md'), 'note\n')
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
|
||||
await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
|
||||
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
|
||||
const card = page.locator('[data-forge-local]')
|
||||
await card.getByRole('button', { name: /^查看本会话的变更:3 个文件/ }).click({ timeout: 20_000 })
|
||||
const local = page.locator('[data-forge-changes="local"]')
|
||||
const app = local.locator('[data-forge-diff-file="src/app.ts"]')
|
||||
await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).check({ timeout: 20_000 })
|
||||
await expect.poll(() => app.getAttribute('data-expanded')).toBe(null)
|
||||
|
||||
await page.reload()
|
||||
await page.locator('[data-forge-changes="local"] [data-forge-diff-file="src/app.ts"]').waitFor({ timeout: 20_000 })
|
||||
await expect.poll(() => app.getAttribute('data-viewed')).toBe('viewed')
|
||||
expect(await app.getAttribute('data-expanded')).toBe(null)
|
||||
await writeFile(join(project, 'src', 'app.ts'), 'export const app = 2\n')
|
||||
await local.getByRole('button', { name: '刷新变更', exact: true }).click()
|
||||
await expect.poll(() => app.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed')
|
||||
await app.getByText('有新改动', { exact: true }).waitFor()
|
||||
await expect.poll(() => app.getAttribute('data-expanded')).toBe('')
|
||||
expect(await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).isChecked()).toBe(false)
|
||||
|
||||
await local.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click()
|
||||
const menu = page.locator('[data-forge-commit-menu]')
|
||||
await menu.getByRole('menuitem', { name: /Test the app/ }).click()
|
||||
await expect.poll(() => shownPaths(local), { timeout: 20_000 }).toEqual(['src/app.spec.ts'])
|
||||
// Without the file tree beside the diff, the toolbar offers the lens as a menu.
|
||||
await local.getByRole('button', { name: '分层透镜:全部', exact: true }).click()
|
||||
await expect.poll(() => page.getByRole('menu').getByRole('menuitem').allTextContents()).toEqual(['全部1', '接口0', '实现0', '测试1'])
|
||||
await page.keyboard.press('Escape')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu inside its card and its name under the pointer', async () => {
|
||||
const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-narrow-header', 'normal', { branch: 'feat' })
|
||||
const from = 'src/original-review-module-with-a-long-name.ts'
|
||||
const to = 'src/renamed-review-module-with-an-even-longer-name.ts'
|
||||
const body = Array.from({ length: 20 }, (_, index) => `export const value${index} = ${index}\n`).join('')
|
||||
await mkdir(join(project, 'src'))
|
||||
await writeFile(join(project, from), body)
|
||||
await git(project, 'add', from)
|
||||
await git(project, 'commit', '--quiet', '-m', 'Add the module')
|
||||
// The base holds the old path, so the branch shows a rename.
|
||||
await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
|
||||
await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
|
||||
await git(project, 'mv', from, to)
|
||||
await writeFile(join(project, to), `${body}export const extra = 1\n`)
|
||||
await git(project, 'commit', '--quiet', '-am', 'Rename the module')
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
await settled
|
||||
await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
|
||||
await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
|
||||
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
|
||||
await page.locator('[data-forge-local]').getByRole('button', { name: /^查看本会话的变更/ }).click({ timeout: 20_000 })
|
||||
const local = page.locator('[data-forge-changes="local"]')
|
||||
const name = 'renamed-review-module-with-an-even-longer-name.ts'
|
||||
const file = local.locator(`[data-forge-diff-file="${to}"]`)
|
||||
const viewed = file.getByRole('checkbox', { name: `将 ${name} 标记为已审阅`, exact: true })
|
||||
await viewed.check({ timeout: 20_000 })
|
||||
await writeFile(join(project, to), `${body}export const extra = 2\n`)
|
||||
await local.getByRole('button', { name: '刷新变更', exact: true }).click()
|
||||
await expect.poll(() => file.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed')
|
||||
await file.getByText('由 original-review-module-with-a-long-name.ts 重命名', { exact: true }).waitFor()
|
||||
|
||||
// The changed tag, the rename badge, and the long path compete for one narrow header with the counts and actions.
|
||||
await page.setViewportSize({ width: 390, height: 780 })
|
||||
const label = file.locator('[data-forge-file-label]')
|
||||
const [card, mark, menu, labelBox] = await Promise.all([
|
||||
file.boundingBox(), viewed.boundingBox(), file.getByRole('button', { name: `${name} 的更多操作`, exact: true }).boundingBox(), label.boundingBox(),
|
||||
])
|
||||
if (card === null || mark === null || menu === null || labelBox === null) throw new Error('The header controls must be rendered')
|
||||
expect(mark.x + mark.width).toBeLessThanOrEqual(card.x + card.width)
|
||||
expect(menu.x + menu.width).toBeLessThanOrEqual(card.x + card.width)
|
||||
expect(labelBox.width).toBeGreaterThan(40)
|
||||
await label.hover()
|
||||
await page.getByRole('tooltip').filter({ hasText: `${from} → ${to}` }).waitFor()
|
||||
await viewed.check()
|
||||
await expect.poll(() => file.getAttribute('data-viewed')).toBe('viewed')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
@@ -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',
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/** Reasoning rows of one Assistant message keep the 4px process-row gap, and display-empty reasoning adds none. */
|
||||
import { chromium } from 'playwright'
|
||||
import { expect, it, onTestFinished } from 'vitest'
|
||||
import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
|
||||
import { launchWebScaffold, seedSession, watchConsole } from './scaffold.ts'
|
||||
import { newEnglishPage } from './support.ts'
|
||||
|
||||
type Block = readonly ['reasoning' | 'signature' | 'text' | 'bash', string]
|
||||
|
||||
/** Turn 1: reasoning around a signature-only block. Turn 2: signature-only blocks before and after reasoning. */
|
||||
const TURNS: readonly (readonly (readonly Block[])[])[] = [
|
||||
[[['reasoning', 'a'], ['signature', 's1'], ['reasoning', 'b'], ['bash', 'k1']], [['text', 'Answer one']]],
|
||||
[
|
||||
[['reasoning', 'c'], ['bash', 'k2']],
|
||||
[['signature', 's2'], ['signature', 's3'], ['reasoning', 'd'], ['bash', 'k3']],
|
||||
[['reasoning', 'e'], ['signature', 's4'], ['signature', 's5'], ['bash', 'k4']],
|
||||
[['text', 'Answer two']],
|
||||
],
|
||||
]
|
||||
|
||||
function bashArguments(label: string): string {
|
||||
return JSON.stringify({ command: `echo ${label}`, description: `Run ${label}` })
|
||||
}
|
||||
|
||||
function content([kind, label]: Block): Record<string, string> {
|
||||
switch (kind) {
|
||||
case 'reasoning': return { type: 'reasoning', text: `Thinking ${label}\n\nDetails for ${label}.` }
|
||||
case 'signature': return { type: 'reasoning', text: `<signature>${label}</signature>` }
|
||||
case 'text': return { type: 'text', text: label }
|
||||
case 'bash': return {
|
||||
type: 'tool-call', id: `call_${label}`, name: 'bash', arguments: bashArguments(label),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One closed Session whose Assistant messages carry the block layouts above. */
|
||||
function sessionLog(): string {
|
||||
const header = {
|
||||
type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, cwd: '{{cwd}}',
|
||||
isSeeded: false, delegationDepth: 0,
|
||||
}
|
||||
const events: Record<string, unknown>[] = []
|
||||
let message = 0
|
||||
const id = (): string => `{{message:${String(++message)}}}`
|
||||
TURNS.forEach((steps, index) => {
|
||||
const turn = index + 1
|
||||
events.push({ type: 'turn/start', data: { turn } })
|
||||
steps.forEach((blocks, stepIndex) => {
|
||||
const step = stepIndex + 1
|
||||
events.push({ type: 'step/start', data: { turn, step } })
|
||||
if (step === 1) {
|
||||
events.push({
|
||||
type: 'user/message', surfaceOp: 'append',
|
||||
data: { content: [{ type: 'text', text: `Turn ${String(turn)}` }], source: { kind: 'user' }, role: 'user', id: id() },
|
||||
})
|
||||
}
|
||||
events.push({
|
||||
type: 'assistant/message', surfaceOp: 'append',
|
||||
data: {
|
||||
turn, step, stream: [],
|
||||
message: {
|
||||
role: 'assistant', content: blocks.map(content), id: id(),
|
||||
source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-v4-flash' },
|
||||
},
|
||||
},
|
||||
})
|
||||
for (const [kind, label] of blocks) {
|
||||
if (kind !== 'bash') continue
|
||||
const callId = `call_${label}`
|
||||
events.push({ type: 'tool/call', data: { turn, step, callId, name: 'bash', arguments: bashArguments(label) } })
|
||||
events.push({
|
||||
type: 'tool/result', surfaceOp: 'append', sourceEventSeqs: [events.length - 1],
|
||||
data: {
|
||||
turn, step, meta: { cwd: '{{cwd}}' },
|
||||
message: {
|
||||
role: 'tool', source: { kind: 'tool', callId }, toolCallId: callId,
|
||||
content: [{ type: 'text', text: `${label}\n` }], isError: false, id: id(),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
events.push({ type: 'step/end', data: { turn, step } })
|
||||
})
|
||||
events.push({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
|
||||
})
|
||||
return [header, ...events].map(line => JSON.stringify(line)).join('\n')
|
||||
}
|
||||
|
||||
it('keeps 4px between reasoning and tool rows around display-empty reasoning blocks', async () => {
|
||||
const scaffold = await launchWebScaffold({})
|
||||
onTestFinished(() => scaffold.close())
|
||||
await scaffold.ctx.settings.update('ui-chat', { transcriptView: 'verbose' })
|
||||
await seedSession(scaffold, sessionLog(), 'reasoning-spacing')
|
||||
const browser = await chromium.launch()
|
||||
onTestFinished(() => browser.close())
|
||||
const page = await newEnglishPage(browser)
|
||||
const console = 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.getByText('Answer two', { exact: true }).waitFor()
|
||||
|
||||
// Rows in reading order; signature-only reasoning renders no row of its own.
|
||||
const rows = await page.evaluate(() => [...document.querySelectorAll('[data-variant="think"], [data-chat-call-id]')]
|
||||
.filter(row => row.getBoundingClientRect().height > 0)
|
||||
.map((row) => {
|
||||
const { top, bottom } = row.getBoundingClientRect()
|
||||
const name = row.matches('[data-variant="think"]')
|
||||
? /Thinking (\w+)/.exec(row.textContent ?? '')?.[1]
|
||||
: row.getAttribute('data-chat-call-id')?.replace('call_', '')
|
||||
return { name: name ?? '?', top, bottom }
|
||||
})
|
||||
.sort((left, right) => left.top - right.top))
|
||||
expect(rows.map(row => row.name)).toEqual(['a', 'b', 'k1', 'c', 'k2', 'd', 'k3', 'e', 'k4'])
|
||||
const gaps = Object.fromEntries(rows.slice(1).map((row, index) =>
|
||||
[`${rows[index]!.name}→${row.name}`, Math.round(row.top - rows[index]!.bottom)]))
|
||||
expect(gaps).toMatchObject({ 'a→b': 4, 'b→k1': 4, 'c→k2': 4, 'k2→d': 4, 'd→k3': 4, 'k3→e': 4, 'e→k4': 4 })
|
||||
expect(console.pageErrors).toEqual([])
|
||||
})
|
||||
@@ -124,14 +124,24 @@ describe('web e2e: fresh round trip through the real assembly', () => {
|
||||
let accepted = false
|
||||
try {
|
||||
await input.fill(PROMPT)
|
||||
// Hold the prompt POST at the browser boundary so the Host cannot accept
|
||||
// the message before the pre-accept snapshot is read.
|
||||
const promptSent = Promise.withResolvers<undefined>()
|
||||
const releasePrompt = Promise.withResolvers<undefined>()
|
||||
const holdPrompt = async (route: Route): Promise<void> => {
|
||||
promptSent.resolve(undefined)
|
||||
await releasePrompt.promise
|
||||
await route.continue()
|
||||
}
|
||||
await page.route('**/api/session/prompt', holdPrompt, { times: 1 })
|
||||
const admitted = page.waitForResponse('**/api/session/prompt')
|
||||
const [echoSnapshot, response] = await Promise.all([
|
||||
input.evaluate(async (element, prompt) => {
|
||||
try {
|
||||
const echoCapture = input.evaluate(async (element, prompt) => {
|
||||
element.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key: 'Enter', code: 'Enter', bubbles: true, cancelable: true,
|
||||
}))
|
||||
// sendSession registered its paint yield first. This frame observes the
|
||||
// composer holding the message while the Host has not accepted it yet.
|
||||
// sendSession registered its paint yield first; this frame observes the
|
||||
// composer holding the message while the POST is still held.
|
||||
await new Promise<void>((resolve) => { requestAnimationFrame(() => { resolve() }) })
|
||||
const echo = document.querySelector<HTMLElement>('[data-submission-echo]')
|
||||
return [
|
||||
@@ -139,12 +149,15 @@ describe('web e2e: fresh round trip through the real assembly', () => {
|
||||
`composer: ${JSON.stringify(element.textContent ?? '')}`,
|
||||
`contenteditable: ${element.getAttribute('contenteditable')}`,
|
||||
].join('\n')
|
||||
}, PROMPT),
|
||||
admitted,
|
||||
])
|
||||
}, PROMPT)
|
||||
await promptSent.promise
|
||||
await compareOrRefreshGolden(ECHO_EXPECTED, await echoCapture, MODE)
|
||||
} finally {
|
||||
releasePrompt.resolve(undefined)
|
||||
}
|
||||
const response = await admitted
|
||||
expect(await response.json()).toMatchObject({ result: { ok: true, value: { accepted: true } } })
|
||||
accepted = true
|
||||
await compareOrRefreshGolden(ECHO_EXPECTED, echoSnapshot, MODE)
|
||||
// Acceptance publishes the echo and clears the composer; maintenance keeps the Turn from starting.
|
||||
await page.locator('[data-submission-echo]', { hasText: PROMPT }).waitFor()
|
||||
await expect.poll(() => input.textContent()).toBe('')
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }) })
|
||||
}),
|
||||
|
||||
@@ -479,7 +479,6 @@ const EXPECTED_TOOLS = [
|
||||
'edit',
|
||||
'exit_plan_mode',
|
||||
'get_goal',
|
||||
'interrupt_agent',
|
||||
'job_kill',
|
||||
'job_list',
|
||||
'job_output',
|
||||
|
||||
@@ -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 } })
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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 }) })
|
||||
}),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -365,6 +365,61 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
|
||||
})
|
||||
|
||||
it('retries a failed cold catalog and discovers descendants without reopening the menu', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog'))
|
||||
const reads = apiCalls.filter(path => path === '/api/session/projections').length
|
||||
const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
|
||||
const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections')
|
||||
try {
|
||||
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
|
||||
await page.locator('[data-composer-input]').first().hover()
|
||||
await trigger.hover()
|
||||
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
|
||||
const child = tree.getByRole('treeitem', { name: new RegExp(LABEL) })
|
||||
await child.waitFor()
|
||||
expect(await child.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
|
||||
expect(await tree.getByText(/Loading subagents|unknown/u).count()).toBe(0)
|
||||
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads)
|
||||
expect(observe).not.toHaveBeenCalled()
|
||||
const parentUrl = page.url()
|
||||
await page.route('**/api/session/projections', route => route.abort('failed'), { times: 1 })
|
||||
await trigger.click()
|
||||
const retry = tree.getByRole('button', { name: 'Retry', exact: true })
|
||||
await retry.waitFor()
|
||||
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
|
||||
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads + 1)
|
||||
expect(projections).not.toHaveBeenCalled()
|
||||
await retry.click()
|
||||
await retry.waitFor({ state: 'detached' })
|
||||
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
|
||||
await expand.waitFor()
|
||||
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId])
|
||||
expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
|
||||
const lastRead = page.waitForResponse('**/api/session/projections')
|
||||
await expand.click()
|
||||
await (await lastRead).finished()
|
||||
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId))
|
||||
.toEqual([parentId, childId, oneShotId, grandchildId])
|
||||
const grandchild = tree.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
|
||||
await grandchild.waitFor()
|
||||
expect(await grandchild.getAttribute('aria-expanded')).toBeNull()
|
||||
await compareOrRefreshGolden(
|
||||
TREE_EXPECTED,
|
||||
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
|
||||
)
|
||||
expect(page.url()).toBe(parentUrl)
|
||||
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
|
||||
expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
|
||||
await page.keyboard.press('Escape')
|
||||
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
|
||||
} finally {
|
||||
await page.unroute('**/api/session/projections')
|
||||
observe.mockRestore()
|
||||
projections.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('lists direct subagents by label in the reference menu', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-reference-title'))
|
||||
expect(liveReferenceOptions.some(text => text.includes(LABEL))).toBe(true)
|
||||
@@ -424,7 +479,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
}
|
||||
expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `)
|
||||
expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0)
|
||||
expect(await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).count()).toBe(1)
|
||||
await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
|
||||
expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1)
|
||||
expect(page.url()).toBe(originalUrl)
|
||||
expect(await page.getByRole('tooltip').count()).toBe(0)
|
||||
@@ -438,9 +493,34 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
}
|
||||
})
|
||||
|
||||
it('recovers a current-format cold child catalog cache miss without activating either level', async () => {
|
||||
it('expands locally available cold catalogs without requesting or activating either level', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree'))
|
||||
await page.getByRole('button', { name: '2 subagents' }).hover()
|
||||
const warningStart = tripwire.warnings.length
|
||||
await page.reload({ waitUntil: 'load' })
|
||||
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
|
||||
await trigger.waitFor()
|
||||
acknowledgeReloadConnectionLoss(tripwire, warningStart)
|
||||
const siblingsRead = page.waitForResponse((response) => {
|
||||
if (!response.url().endsWith('/api/session/projections')) return false
|
||||
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
|
||||
return body.payload.args.request.sessionId === oneShotId
|
||||
})
|
||||
await trigger.click()
|
||||
await (await siblingsRead).finished()
|
||||
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
|
||||
await expand.waitFor()
|
||||
const descendantsRead = page.waitForResponse((response) => {
|
||||
if (!response.url().endsWith('/api/session/projections')) return false
|
||||
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
|
||||
return body.payload.args.request.sessionId === grandchildId
|
||||
})
|
||||
await expand.click()
|
||||
await (await descendantsRead).finished()
|
||||
await page.keyboard.press('Escape')
|
||||
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
|
||||
const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
|
||||
await page.locator('[data-composer-input]').first().hover()
|
||||
await trigger.hover()
|
||||
const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
|
||||
expect(await catalogTree.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
@@ -453,6 +533,10 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
name: `Expand ${ONE_SHOT_LABEL} descendants`,
|
||||
})
|
||||
expect(await oneShotDisclosure.count()).toBe(0)
|
||||
await compareOrRefreshGolden(
|
||||
fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/disclosures.expected.md', import.meta.url)),
|
||||
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
|
||||
)
|
||||
const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
|
||||
expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1)
|
||||
expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
|
||||
@@ -501,18 +585,13 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
expect(await page.getByText(PARENT_PROMPT, { exact: true }).isVisible()).toBe(true)
|
||||
expect(await page.locator('[data-sidebar-chat]').count()).toBe(0)
|
||||
}
|
||||
const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
|
||||
try {
|
||||
const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections')
|
||||
await clickDisclosureGutter(3)
|
||||
await projections
|
||||
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
|
||||
expect(await sectionHeader.count()).toBe(0)
|
||||
expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true)
|
||||
expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
|
||||
} finally {
|
||||
observe.mockRestore()
|
||||
}
|
||||
await clickDisclosureGutter(3)
|
||||
const grandchildRow = page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
|
||||
await grandchildRow.waitFor({ timeout: 15_000 })
|
||||
expect(await catalogTree.getByText('Loading subagents…', { exact: true }).count()).toBe(0)
|
||||
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await grandchildRow.getByRole('button', { name: `Expand ${NESTED_LABEL} descendants` }).count()).toBe(0)
|
||||
expect(await sectionHeader.count()).toBe(0)
|
||||
await clickDisclosureGutter(26)
|
||||
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' })
|
||||
expect(await childRow.getAttribute('aria-expanded')).toBe('false')
|
||||
@@ -571,6 +650,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
scaffold.workspaceCwd,
|
||||
)
|
||||
await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
|
||||
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads)
|
||||
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click()
|
||||
await page.getByText(NESTED_PROMPT).waitFor()
|
||||
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
|
||||
@@ -994,10 +1074,9 @@ describe('web e2e: migration-required subagent catalog', () => {
|
||||
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
|
||||
const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) })
|
||||
await childRow.waitFor()
|
||||
await expect.poll(() => childRow.textContent()).toContain('Migration required')
|
||||
await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0)
|
||||
expect(await childRow.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await childRow.textContent()).toContain('Migration required')
|
||||
expect(await childRow.textContent()).not.toContain('Migration required')
|
||||
expect(await childRow.textContent()).not.toContain('unknown mode')
|
||||
expect(await childRow.getByRole('button', { name: `Open ${childLabel} in sidebar`, exact: true }).isEnabled()).toBe(true)
|
||||
expect(await tree.getByRole('treeitem').count()).toBe(1)
|
||||
@@ -1015,7 +1094,7 @@ describe('web e2e: migration-required subagent catalog', () => {
|
||||
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
|
||||
const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) })
|
||||
await grandchildRow.waitFor()
|
||||
expect(await grandchildRow.textContent()).toContain('Migration required')
|
||||
expect(await grandchildRow.textContent()).not.toContain('Migration required')
|
||||
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
|
||||
expect(await grandchildRow.getByRole('button', { name: `Expand ${grandchildLabel} descendants`, exact: true }).count()).toBe(0)
|
||||
expect(projections).not.toHaveBeenCalled()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
"tests/trajectory-virtualization.e2e.ts",
|
||||
"tests/lifecycle-chrome.e2e.ts",
|
||||
"tests/reasoning-preview.e2e.ts",
|
||||
"tests/reasoning-spacing.e2e.ts",
|
||||
"tests/details-session-lifecycle.e2e.ts",
|
||||
"tests/sessionless-header.e2e.ts",
|
||||
"tests/document-preview.e2e.ts",
|
||||
@@ -210,6 +211,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 +233,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",
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 20ef882e44b06a10
|
||||
zh: c10c3934ed5570e9
|
||||
/deepseek-harness-architecture/events:
|
||||
en: ddebac7cfd41ec73
|
||||
zh: 51e6d0866a9e7839
|
||||
en: 0d4481070a0ba352
|
||||
zh: 026be77a9f3db68e
|
||||
/deepseek-harness-architecture/turn-flow:
|
||||
en: 1d496f1893bdbb8d
|
||||
zh: f16d162a803fc791
|
||||
|
||||
@@ -74,7 +74,7 @@ Events provide extension points in three domains.
|
||||
|
||||
Subagent Activations own runtime tree membership.
|
||||
|
||||
AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; unload retains resources through teardown ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)).
|
||||
AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown cancels and awaits active work despite queue-cleanup failures before releasing resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)).
|
||||
|
||||
[Event producers and consumers](event-producer-consumer.md).
|
||||
|
||||
|
||||
Loaded 100 of 1018 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user