Merge remote-tracking branch 'origin/master' into turtle/fix-web-fetch-error-58da60e9770f

Co-authored-by: Elevator14B <[email protected]>

# Conflicts:
#	packages/client/ui-tool/README.i18n.yaml
#	packages/client/ui-tool/README.md
#	packages/client/ui-tool/README.zh.md
This commit is contained in:
Turtle committed 2026-11-07 23:22:35 +08:00
commit 1a59fee340
723 files changed
+23890 -8673

No files matched your search

@@ -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
@@ -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.
@@ -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 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。
@@ -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
@@ -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.
@@ -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。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。
@@ -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.
@@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
@@ -21,8 +21,8 @@
en: 8a9578bbc700c0bf
zh: 8ee46e5ef1cf3972
/agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write:
en: 33312dc2b9813ef9
zh: ba2fb5fac770e698
en: c6b0d746185d0d3b
zh: a228633ecdf42800
/agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes:
en: 85fb2b564bc40230
zh: 97c3e794124f8044
@@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem
### Authorization loses required observation or an accepted credential write
**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts).
**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts).
**Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced.
@@ -36,7 +36,7 @@ Status: proposed
### Authorization 丢失必需的提交观察或已接受的凭据写入
**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts)。
**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。
**写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。
@@ -0,0 +1,34 @@
# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption-details.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md
/agent-note-chat-history-consumption-classes-and-interactions:
en: 69ce0866b2608208
zh: 55fdeded5d7a4779
/agent-note-chat-history-consumption-classes-and-interactions/problem:
en: edaa7ca0e55a9c33
zh: 33d2b5ac07760988
/agent-note-chat-history-consumption-classes-and-interactions/proposal:
en: 5e5553981c48d0e2
zh: 1195ac8d64180451
/agent-note-chat-history-consumption-classes-and-interactions/proposal/owners-and-interfaces:
en: efbe7ccc25cf1f42
zh: 3bb8f803677824bd
/agent-note-chat-history-consumption-classes-and-interactions/proposal/data-lifetimes:
en: ffdbe0e796463624
zh: f10bd2ced5748017
/agent-note-chat-history-consumption-classes-and-interactions/proposal/consumption-intent-and-wakeups:
en: db8763250020e58c
zh: 4d9a17f1b209d4f2
/agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads:
en: 21df3db6bc83e702
zh: 43b49ceb7407a422
/agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered:
en: 7b3b9b0c7b8f293b
zh: e20045fc3080418f
/agent-note-chat-history-consumption-classes-and-interactions/acceptance-criteria:
en: 1b22cf3616302960
zh: 418ead8421a91bee
/agent-note-chat-history-consumption-classes-and-interactions/risks:
en: 9a61970e311751ac
zh: b24d0eac7b12af62
@@ -0,0 +1,104 @@
# Agent Note: Chat history consumption classes and interactions
Status: proposed
English | [中文](2026-11-06-chat-history-consumption-details.zh.md)
## Problem
Session owns a history page's network lifetime, while Chat owns whether that page can safely enter the current view. Two-phase loading must reuse existing publication and scrolling capabilities without copying business data, consumption intent, and DOM preservation state into one owner.
## Proposal
[History prefetch and safe consumption](2026-11-06-chat-history-consumption.md) defines user-visible behavior and trade-offs. This note defines class interactions and lifetimes without adding an independent scroll animation or React commit manager.
### Owners and interfaces
| Owner | Data and operations |
|---|---|
| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` prepares and optionally consumes a page; `consumeOlder()` synchronously publishes a valid staged page; `historyLoadStatus` is idle/loading/pendingConsumption/error, and `loadingOlder` derives from loading, including Turn jumps |
| Session request record | Holds generation, starting cursor, page entries, hasMore, Promise, and consumption/invalidation flags; staging does not advance the visible window cursor |
| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; automatic consumption waits or falls back by blocker, while manual consumption captures an anchor and consumes without blocker-wait subscriptions |
| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | Reads internal input/motion state and scrollTop, returns a blocker or native/preserve/prepend, and performs distance measurement and existing anchor algorithms |
| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | Connects existing reading, scroll, content, and size notifications to consumption checks and settles a pending one-shot correction during commit handling |
| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | Requests and consumes through injected callbacks and reads state through useSession; renders a fixed-height history control without retaining Session history data or accumulating historyWasPartial |
```text
ChatNavigation.checkHistory
├─ pendingConsumption + intent=none → retain page until clicked
├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder
├─ pendingConsumption + intent=auto → viewport.historyConsumption
│ ├─ touch/inner-scroll → retain automatic intent before checking motion
│ ├─ motion/pointer/unavailable → return to button
│ ├─ native → consumeOlder
│ ├─ prepend → capture paging position → consumeOlder → correct once after commit
│ └─ preserve → beginPreserving → consumeOlder
├─ loading → no duplicate request; a click records manual intent
├─ error → wait for explicit retry
└─ idle + hasMore + (manual intent or near top without following) → request a page
Session.loadOlder
→ prepareOlder reuses or creates the request
→ await the captured request Promise
→ consumeOlder when request identity remains valid and consumption is not deferred
Session.prepareOlder
→ network prepend → capture the page without publishing eventSource
→ validate progress → pendingConsumption or error
Session.consumeOlder
→ check generation/cursor/consuming
→ synchronous eventSource.prepend → existing Conversation merge and flush
→ clear the request record and publish final status
```
### Data lifetimes
`isOpen` means only that Session `openState === 'open'`; it is independent of whether a page is `pendingConsumption`. `historyWasPartial` is monotonic for one Client Session instance: once its visible window has `hasMore=true`, the fact remains until the instance ends, across component remounts and reconnects, without entering the persistent log.
`prepareOlder()` returns an existing request or creates one, and `loadOlder()` rechecks identity after awaiting that captured request Promise. An obsolete Promise cannot consume a newer page. A default call consumes the prepared page; `deferConsumption` retains a valid nonempty page, while an empty terminal page can immediately confirm exhaustion. Consumption retains the request record and sets `consuming` to prevent synchronous subscriber reentry without borrowing the network loading state.
An ordinary request captures the transport page first. It can be consumed only after the request succeeds and its cursor advances, or an empty page explicitly confirms exhaustion. Failures and empty pages that still claim more history enter error without automatic retry. Window replacement, reconnect, and disposal invalidate old pages; when an in-flight request may have advanced the transport cursor, the existing stream restart restores a baseline before another page is allowed.
`loadThrough(seq)` is explicit navigation: it first adopts a staged page and then uses existing Turn-aligned paging. An ordinary in-flight request remains exclusive, and the caller continues after it settles. A jump publishes its successful prefix once at completion or a later failure, without delaying live appends. `loadingOlder` always equals `historyLoadStatus === 'loading'`.
### Consumption intent and wakeups
An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Touch and actual inner-scroll retain auto before motion is evaluated; after release the current state is checked again. Motion, pointer, or unavailable positioning otherwise returns auto to none. Manual intent bypasses these automatic blockers once a page is available: `beginManualPaging()` uses `beginPaging()` at `scrollTop ≤ 0.5`; elsewhere it calls `beginPreserving()` with `beginPaging()` as fallback. Consumption proceeds even if no anchor is produced. Loading and processing clicks join the current request rather than duplicating it.
Prefetch reuses the existing 500ms reading sample, scrollend, content commits, and size notifications, coalescing them into one rAF check. It uses no IntersectionObserver or additional sample timer and measures nothing in the raw scroll event. Only a ResizeObserver entry for the scroller itself refreshes cached clientHeight during the callback's read phase; column growth does not reread viewport height. Once internal state permits an automatic request, it reads the history control's distance from the viewport and compares it with two cached viewport heights.
`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained automatic intent. Manual consumption has no fold-completion waiting subscription. Without consumption intent, these notifications do not revive an abandoned automatic page.
### Shared anchors and layout reads
For automatic consumption at `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`.
Persistent preservation and one-shot correction use the same `applyPaging()` formula to restore the captured screen position, compensating the inner scrollport before the outer one. They do not add changes in scrollTop since capture: native anchoring may have caused those changes. Their lifetimes differ: one-shot correction neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. A committed transition from `pendingConsumption` to `idle` settles the one-shot record even when the visible Node order is unchanged; a closed view or `error` discards the record without applying it. Geometry invalidation remains conditional on the existing layout-change signal, and no new page token or React publication mechanism is introduced. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation.
Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence.
## Alternatives considered
**Pause publication globally in Conversation.** That also blocks live tail output and expands the cross-view impact.
**Retain a complete window snapshot in Chat.** That copies business data and can overwrite messages received while waiting.
**Store separate coordinates and continuously track the first row for one-shot correction.** That duplicates existing paging anchors and can expand scroll ownership; share the position record and calculations while keeping lifetimes separate.
**Add captured-to-current scroll deltas through `preserveMovement`.** The deltas cannot distinguish reader input from native anchoring for the same prepend, so adding them can compensate twice.
## Acceptance criteria
- Default single-stage calls, deferred consumption, and Turn jumps coexist; an old request cannot consume or overwrite a new one.
- Ordinary events do not revive automatic fallback; touch/inner-scroll continuation, manual completion, and unmount cleanup have focused verification.
- One-shot correction uses the existing screen-restoration formula without persistent observation or duplicate native compensation; persistent and inner preservation do not regress.
- Distance checks use cached viewport height; raw scroll listeners and consumption admission perform no layout reads.
## Risks
Screen restoration uses the measured residual displacement after native anchoring rather than adding scroll-position deltas. It does not preserve arbitrary input movement between capture and application or guarantee an uninterrupted momentum trajectory. Near-zero outer positions, native inner anchoring, and input arriving around the prepend require current-build browser verification.
Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual consumption establishes persistent preservation at consumption time; an already active touch can then enter the paging scroll branch instead of reader sampling, constraining movement until a new input releases the anchor. This [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work) remains unresolved. Manual consumption proceeds without preservation if no anchor can be captured, so that structure has no position-stability guarantee. Cancellation, reconnect, and removal of the selected anchor remain distinct lifecycle cases; a missing anchor cannot provide position preservation. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build.
Reports must identify source/artifact versions, real or synthetic inputs, missing conditions, and cleanup results. V8 function or range hits are not TypeScript line/branch percentages; earlier iteration recordings, Chrome/Safari manual feedback, or a successful build do not establish a complete matrix pass for this proposal.
@@ -0,0 +1,104 @@
# Agent Note: Chat 历史消费的类与交互
Status: proposed
[English](2026-11-06-chat-history-consumption-details.md) | 中文
## Problem
历史页的网络生命周期属于 Session,能否安全进入当前页面属于 Chat。两阶段加载需要复用现有事件发布与滚动能力,不能把业务数据、消费意图和 DOM 保位状态复制到同一个所有者。
## Proposal
用户可见行为与取舍由[历史预取与安全消费](2026-11-06-chat-history-consumption.zh.md)定义。本文规定类之间的调用与生命周期,不增加独立的滚动动画或 React 提交管理。
### 所有者与接口
| 所有者 | 数据与操作 |
|---|---|
| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` 准备并按选项消费一页;`consumeOlder()` 同步发布有效暂存页;`historyLoadStatus` 表达 idle/loading/pendingConsumption/error,`loadingOlder` 从 loading 派生并包含 Turn 跳转 |
| Session 请求记录 | 保存 generation、请求前游标、页内容、hasMore、Promise 与消费/失效标记;缓存页不提前改变可见窗口游标 |
| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;自动按阻塞原因等待或退回按钮,手动采集锚点后消费,不注册阻塞结束等待 |
| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | 读取内部输入/动画状态与 scrollTop,报告阻塞原因或 native/preserve/prepend;执行距离测量和已有锚点算法 |
| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | 把既有阅读、滚动、内容及尺寸通知接到消费检查;在提交阶段结算待执行的一次补偿 |
| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | 通过注入回调请求/消费,通过 useSession 读取状态;固定高度显示历史控件,不保存 Session 历史数据或累计 historyWasPartial |
```text
ChatNavigation.checkHistory
├─ pendingConsumption + intent=none → retain page until clicked
├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder
├─ pendingConsumption + intent=auto → viewport.historyConsumption
│ ├─ touch/inner-scroll → retain automatic intent before checking motion
│ ├─ motion/pointer/unavailable → return to button
│ ├─ native → consumeOlder
│ ├─ prepend → capture paging position → consumeOlder → correct once after commit
│ └─ preserve → beginPreserving → consumeOlder
├─ loading → no duplicate request; a click records manual intent
├─ error → wait for explicit retry
└─ idle + hasMore + (manual intent or near top without following) → request a page
Session.loadOlder
→ prepareOlder reuses or creates the request
→ await the captured request Promise
→ consumeOlder when request identity remains valid and consumption is not deferred
Session.prepareOlder
→ network prepend → capture the page without publishing eventSource
→ validate progress → pendingConsumption or error
Session.consumeOlder
→ check generation/cursor/consuming
→ synchronous eventSource.prepend → existing Conversation merge and flush
→ clear the request record and publish final status
```
### 数据生命周期
`isOpen` 只表达会话 `openState === 'open'`,与某页是否 `pendingConsumption` 无关。`historyWasPartial` 是客户端 Session 实例的单调事实:可见窗口曾有 `hasMore=true` 后保留到实例结束,不随组件重挂载或重连清除,不写持久化日志。
`prepareOlder()` 返回已有请求或创建一个请求,`loadOlder()` 等待捕获的请求 Promise 后再核对身份。旧 Promise 完成不能消费随后创建的新页。默认调用消费准备好的页;`deferConsumption` 保留有效非空页,终态空页可以直接确认耗尽。消费期间保持请求记录并设置 `consuming`,阻止同步订阅者重入,不借用网络 loading 状态。
普通请求先捕获传输返回页,只有请求成功且游标前进,或空页明确表示耗尽时才能消费。失败或空页仍声称有更多则进入 error,不自动重试。窗口替换、重连和销毁使旧页失效;如果在途请求可能已推进传输游标,现有流重启先恢复基线,再允许下一页。
`loadThrough(seq)` 是显式导航:先采用已有待消费页,再沿既有 Turn 对齐规则加载;普通请求在途时保持互斥,由调用方在其结算后继续。跳转的成功前缀在完成或后续失败时一次发布,实时追加不等待它。`loadingOlder` 始终等价于 `historyLoadStatus === 'loading'`。
### 消费意图与唤醒
自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。touch 与实际 inner-scroll 优先于 motion 判断保留 auto,释放后重新检查当前状态;其余 motion、pointer 或 unavailable 使 auto 退回 none。manual 在页面可用时绕过这些自动阻塞:`beginManualPaging()` 在 `scrollTop ≤ 0.5` 时调用 `beginPaging()`;其他位置调用 `beginPreserving()`,并以 `beginPaging()` 兜底。没有产生锚点时仍继续消费。加载和处理状态的点击加入当前请求,不重复请求。
历史预取复用已有 500ms 阅读采样、scrollend、内容提交和尺寸通知,并合并为一次 rAF 检查。不使用 IntersectionObserver,不新增采样计时器,不在原始 scroll 事件中测量。仅 scroller 自身的 ResizeObserver 条目在回调读阶段更新 clientHeight 缓存,column 增长不重新读取视口高度。内部状态允许自动请求时,读取历史控件相对视口的位置,与缓存的两屏高度比较。
`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的自动意图;手动消费不注册折叠结束等待。没有消费意图时这些通知不恢复已经放弃的自动页。
### 锚点复用与布局读取
自动消费在顶部 `scrollTop ≤ 0.5` 时使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。
持续保位和一次补偿用相同的 `applyPaging()` 公式恢复采集时的屏幕位置,先补内层、再补外层。计算不叠加采集后 scrollTop 的变化,因为这些变化可能已经来自原生锚定。两者只区分生命周期:一次补偿不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。已提交的 `pendingConsumption` 到 `idle` 状态转换,即使可见 Node 顺序未变化,也会结算一次补偿记录;视图关闭或进入 `error` 时丢弃记录,不应用补偿。几何失效仍只由已有布局变化信号触发,不增加页 token 或 React 发布机制。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。
距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。
## Alternatives considered
**在 Conversation 全局暂停发布。** 会同时阻止尾部实时输出,扩大跨视图影响。
**在 Chat 保存完整窗口快照。** 复制业务数据,消费时可能覆盖等待期间的新消息。
**为一次补偿另存坐标并持续追踪首行。** 与既有分页锚点重复,并可能扩大滚动控制;共享位置记录和计算,只区分生命周期。
**通过 `preserveMovement` 叠加采集后滚动增量。** 该增量无法区分读者输入与同一次前插的原生锚定,叠加后可能重复补偿。
## Acceptance criteria
- 默认单阶段调用、延迟消费及 Turn 跳转共存,旧请求不能消费或覆盖新请求。
- auto 回退不会被普通事件恢复;触摸与内层滚动续接、manual 完成承诺和卸载清理都有定向验证。
- 一次补偿使用既有屏幕位置恢复公式,不注册持续观察、不重复原生补偿;持续保位和内层补偿不退化。
- 距离读取使用缓存视口高度;原始滚动监听与消费准入不读取布局。
## Risks
屏幕位置恢复使用原生锚定后测得的剩余位移,而不是叠加滚动位置增量。它不保留采集到应用之间任意输入造成的移动,也不保证惯性轨迹连续。外层近零位置、内层原生锚定以及前插附近到达的输入,都需要当前构建的浏览器验证。
显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动消费在消费时建立持续保位;已经进行的触摸随后可能进入 paging 滚动分支而非读者采样,移动受限直到新输入释放锚点。这项[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)仍未解决。手动消费在无法采集锚点时仍继续,因此该结构不保证位置稳定。取消、重连和所选锚点被移除属于不同生命周期情况;锚点缺失时无法提供位置保留。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。
验收报告应列明源码/产物版本、真实或合成输入、未覆盖条件以及清理结果。V8 函数或区间命中不等于 TypeScript 行/分支百分比;早期迭代的录像、Chrome/Safari 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。
@@ -0,0 +1,31 @@
# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md
/agent-note-chat-history-prefetch-and-safe-consumption:
en: b0bb85f8780edc41
zh: f3576c234a2f1a99
/agent-note-chat-history-prefetch-and-safe-consumption/problem:
en: fbdf714be9ea6c90
zh: d9b6c07347812fc1
/agent-note-chat-history-prefetch-and-safe-consumption/proposal:
en: bda6c4b3dfff143e
zh: 4316f6dec6adaa50
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/manual-and-automatic-loading:
en: 9f3707f7d6c3d98e
zh: f8903e2d1d652535
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation:
en: 33f2466b802f3957
zh: 095227215a22b403
/agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions:
en: dd4eeadd2fccab4b
zh: e05d53e63cc44ddf
/agent-note-chat-history-prefetch-and-safe-consumption/alternatives-considered:
en: 7c6d9d470c5b5c93
zh: dc12846ee0f56aae
/agent-note-chat-history-prefetch-and-safe-consumption/acceptance-criteria:
en: f9efd25288474b8a
zh: 9271fde45be71de6
/agent-note-chat-history-prefetch-and-safe-consumption/risks:
en: ff3b2da49f5fb541
zh: b11afa7556f3f313
@@ -0,0 +1,74 @@
# Agent Note: Chat history prefetch and safe consumption
Status: proposed
English | [中文](2026-11-06-chat-history-consumption.zh.md)
## Problem
With only a Load earlier button, readers must reach the beginning of loaded history before clicking. Prefetch can reduce interruption, but a request that starts in a suitable state can return during touch dragging, a navigation change, or a fold animation. History prepending must not change the existing fold driver or simulate momentum.
## Proposal
Separate requesting history from consuming it. The Client Session retains at most one unconsumed page, and Chat decides whether and when to publish it. It retains the new page rather than an old window snapshot, so waiting does not block streaming at the tail. Class ownership and calls are described in the [technical details](2026-11-06-chat-history-consumption-details.md).
### Manual and automatic loading
A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. Once data is available, the click bypasses automatic motion and input blockers: it uses the first paging anchor at the top, or captures the current reading anchor elsewhere with the paging anchor as fallback, and consumes through existing preservation without waiting for an animation callback. If neither anchor is available, consumption still proceeds without a position guarantee. The operation ends with consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent.
Automatic loading requests history after the reader leaves tail following and comes within two viewport heights of the history control. It reuses the existing 500ms reading sample, scroll completion, content commits, and size notifications, without another polling loop or IntersectionObserver. Detection can therefore wait until the next existing sample.
A cached page and an intent to continue automatically are separate facts. Automatic loading falls back to a button on occasional conflicts instead of waiting for every state to recover. Touch and actual inner scrolling retain continuation so mobile readers need not click after every finger release.
| State when data is ready | Automatic intent | Manual intent |
|---|---|---|
| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume through current-anchor preservation |
| Stationary reading away from the top | Consume with existing reading preservation | Consume with existing reading preservation |
| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Consume through current-anchor preservation |
| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Consume the available page through existing preservation |
| A finger held down or actual inner scrolling | Retain intent before testing motion blockers; recheck afterward | Consume the available page through existing preservation |
| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Consume the available page; no anchor means no position guarantee |
| Tail following resumes after automatic prefetch | Keep the page and cancel automatic consumption | The click has paused tail following |
| Streaming continues at the tail | Does not itself block consumption | Does not itself block consumption |
After fallback, scrolling, animation completion, and content notifications cannot reactivate that cached page; only a click or explicit navigation can adopt it. Requests and unconsumed pages remain mutually exclusive: no duplicate request for a cached page and no timeout that forces insertion.
### Position and status presentation
The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. An automatic prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; manual consumption and stationary preservation retain their existing persistent lifetime. Both modes restore the screen position captured immediately before consumption with the same formula; they differ only in whether preservation remains active afterward. The one-shot path does not reconstruct intervening reader movement or restart momentum. Consumption completion also settles and clears the one-shot record when the visible Node order does not change; view closure or history failure discards it without applying it.
The history control keeps the same height across states. Loading and Processing remain clickable to join the current request or consume the cached page; only confirmed exhaustion disables the button. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row.
### Scope and retained decisions
Do not add `flushSync` or change Conversation publication cadence, fold-batch targets, or ScrollFollow policy. Consumption admission reads only internal state and `scrollTop`; DOM geometry reads belong to distance confirmation and position correction. Do not add an independent persistent head-anchor controller, `batchShift`, or a per-frame compensator.
[One fold motion](../../implemented/architecture/2026-10-13-chat-single-fold-motion.md) and [group-tree exchanges](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.md) retain ownership of folding and grouping decisions; this proposal does not supersede them.
## Alternatives considered
**Prepend every response immediately and compensate continuously.** That makes pagination take over existing motion; this design corrects once at the top and waits or falls back on conflicts.
**Automatically wait for every unsafe state to recover.** That adds coordination obligations for occasional animations, navigation, and automatic continuation; retain touch continuation and manual completion, but return other automatic conflicts to the button.
**Remove staging entirely or discard conflicting pages.** Conflicts can start during a request, and the transport history cursor may already have advanced; retaining one page is simpler than rolling back that cursor.
**Disable loading whenever a Turn is running.** Readers still need history during long replies, so execution state cannot replace the current presentation conditions.
**Separate IO prefetch wakeups and React synchronous-commit control.** Reuse existing sampling and publication, accepting sample latency; do not add commit scheduling without evidence of a concrete failure.
## Acceptance criteria
- Requests, staging, and consumption never duplicate a page request; tail streaming continues.
- Ordinary events do not revive automatic fallback; touch, inner scrolling, and manual clicks retain their specified continuation.
- Stationary and top-edge prepends preserve old content position; ordinary automatic momentum consumption adds no outer JS scroll write.
- Failure, no progress, exhaustion, reconnect, and explicit navigation have defined outcomes without request loops or stale-page consumption.
- Control states have equal height; existing fold-driver behavior is retained, and browser evidence identifies the current build, simulated inputs, and missing cases.
## Risks
One-shot correction restores a captured screen position rather than estimating reader velocity. Input or browser movement between capture and application can therefore affect the resulting motion; validation must cover the actual browser and input sequence. The shared formula does not add scroll-position deltas that could already include native anchoring. See the [technical risks](2026-11-06-chat-history-consumption-details.md#risks).
CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. Manual consumption without a usable anchor can move visible content. It can also establish persistent preservation during an already active touch gesture, constraining that gesture or its momentum until a new reading input releases the anchor; see the [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work).
Audit and measurement are ongoing, so this record remains proposed. Earlier Chrome/Safari manual feedback and headless results from different iterations do not establish a complete matrix pass for the final source; actual scrollbar dragging, same-document reconnect, cross-platform input, and exceptional cleanup paths require separately attributed evidence.
@@ -0,0 +1,74 @@
# Agent Note: Chat 历史预取与安全消费
Status: proposed
[English](2026-11-06-chat-history-consumption.md) | 中文
## Problem
只提供“加载更早”按钮时,读者必须到达已加载历史的开头再点击。提前请求可以减少中断,但请求发出时适合加载,不代表返回时适合前插:读者可能开始触摸拖动、切换导航目标,或者遇到折叠动画。分页不应为了前插历史改变已有折叠驱动或模拟惯性。
## Proposal
将历史请求与消费分开。客户端 Session 最多保留一页未消费的数据,Chat 决定是否以及何时发布它。数据保存为新页而不是旧窗口快照,所以等待不阻止尾部流式输出。类与调用关系见[技术细节](2026-11-06-chat-history-consumption-details.zh.md)。
### 手动与自动加载
手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。数据可用后,点击绕过自动路径的动画和输入阻塞:在顶部使用首条分页锚点,其他位置采集当前阅读锚点并以分页锚点兜底,再通过既有保位路径消费,不等待动画回调。两个锚点都不存在时仍消费,但不保证位置稳定。该操作以消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。
自动加载在读者离开底部跟随、进入距历史控件两屏以内时请求。它复用已有 500ms 阅读采样及滚动结束、内容提交、尺寸通知,不新增轮询或 IntersectionObserver。代价是发现进入预取范围可能延后至下一次已有采样。
缓存是否存在与是否需要自动续接是两个事实。自动操作在低频冲突下退回按钮,不承诺等所有状态恢复;触摸与实际内层滚动仍保留续接,避免要求手机用户每次松手后再点击。
| 数据就绪时的状态 | 自动意图 | 手动意图 |
|---|---|---|
| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 通过当前锚点保位消费 |
| 非顶部静止阅读 | 既有阅读保位,消费 | 既有阅读保位,消费 |
| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 通过当前锚点保位消费 |
| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 数据可用即通过既有保位消费 |
| 手指按住或实际内层滚动 | 优先于动画判断保留意图,结束后重查 | 数据可用即通过既有保位消费 |
| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 消费可用页;没有锚点时不保证位置稳定 |
| 自动预取后恢复底部跟随 | 保留缓存,取消自动消费 | 点击已暂停底部跟随 |
| 底部继续流式输出 | 本身不阻止消费 | 本身不阻止消费 |
退回按钮后,滚动、动画结束和内容通知都不能重新激活该缓存页;只有点击或显式导航可以采用它。请求和待消费页仍然互斥,不为缓存页重复请求,也不超时强行插入。
### 位置与状态展示
会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。自动顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;手动消费和静止保位保持原有持续保位生命周期。两种模式用相同公式恢复消费前刚采集的屏幕位置,只区别于应用后是否继续保位。一次补偿不重建采集期间的读者移动,也不重新启动惯性。即使可见 Node 顺序未变化,消费完成也会结算并清除一次补偿记录;视图关闭或历史失败时直接丢弃,不再应用。
历史控件各状态保持同高。“正在加载”和“正在处理”仍可点击,以加入当前请求或消费缓存;只有确认到头才禁用按钮。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。
### 范围与既有决策
不新增 `flushSync`,不改变 Conversation 发布节奏、折叠批次目标或 ScrollFollow 的跟随策略。消费准入只读内部状态和 `scrollTop`;DOM 几何读取留在距离确认和位置补偿处。不新增独立的持续开头锚点控制器、`batchShift` 或每帧补偿器。
[单一折叠运动](../../implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md)与[分组树交互段](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md)仍拥有折叠和分组决策,本提案不取代它们。
## Alternatives considered
**任意状态下数据到达即前插,再持续补偿。** 需要分页接管已有运动;本方案只在顶部补偿一次,冲突时等待或退回按钮。
**所有不安全状态都自动等待恢复。** 增加低频动画、导航与自动续接的协调义务;保留触摸续接和手动完成,其他自动冲突退回按钮。
**完全取消暂存或直接丢弃冲突页。** 请求途中仍可能发生冲突,而且传输历史游标可能已经前移;保留一页比回滚游标更直接。
**运行中的 Turn 禁止加载。** 长回复期间仍需阅读历史,运行状态不能代替当前界面的消费条件。
**独立 IO 预取唤醒与 React 同步提交控制。** 复用已有采样和发布路径,接受采样延迟;没有具体失败证据时不增加提交调度机制。
## Acceptance criteria
- 请求、暂存与消费期间不重复取页;尾部流式继续更新。
- 自动退回按钮后不会被普通事件恢复;触摸、内层滚动和手动点击保留约定的续接。
- 静止和顶部前插保持旧内容位置;普通自动惯性消费不新增 JS 外层滚动写入。
- 页面失败、无进展、到头、重连和显式导航均有明确结果,不循环请求或消费过期页。
- 控件各状态同高;既有折叠驱动保持行为,真实浏览器验收区分当前构建、输入模拟和未覆盖情况。
## Risks
一次补偿恢复采集的屏幕位置,不估算读者速度。采集到应用之间的输入或浏览器移动可能影响最终运动,因此需要验证实际浏览器和输入序列。共享公式不叠加可能已包含原生锚定的滚动位置增量。见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。
原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。没有可用锚点的手动消费可能移动可见内容。手动消费也可能在已有触摸手势进行中建立持续保位,约束该手势或其惯性,直到新的阅读输入释放锚点;见[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)。
审计与测量尚在进行,本记录保持 proposed。此前 Chrome/Safari 手工反馈和不同迭代的 headless 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。
+9
View File
@@ -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
+2 -2
View File
@@ -54,7 +54,7 @@ flowchart LR
cfg --> plugin_dsh_base_settings
plugin_dsh_base_authorization["authorization<br/>@deepseek-ai/dsh-authorization"]
cfg --> plugin_dsh_base_authorization
plugin_dsh_base_deepseek_account["deepseek-account<br/>@deepseek-ai/dsh-deepseek-account-platform"]
plugin_dsh_base_deepseek_account["deepseek-account<br/>@deepseek-ai/dsh-deepseek-account"]
cfg --> plugin_dsh_base_deepseek_account
plugin_dsh_base_credentials["credentials<br/>@deepseek-ai/dsh-credentials-local"]
cfg --> plugin_dsh_base_credentials
@@ -233,7 +233,7 @@ flowchart LR
| `config-editor` | `@deepseek-ai/dsh-config-editor` |
| `settings` | `@deepseek-ai/dsh-settings` |
| `authorization` | `@deepseek-ai/dsh-authorization` |
| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account-platform` |
| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` |
| `credentials` | `@deepseek-ai/dsh-credentials-local` |
| `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` |
| `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` |
@@ -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"}
+50 -1
View File
@@ -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',
@@ -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 {
+2 -2
View File
@@ -15,8 +15,8 @@
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: 1f59637852e162b4
zh: b1530a1af195cb92
en: 37d36f8d57214336
zh: ceb50c0fa866eb24
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
+1 -1
View File
@@ -49,7 +49,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend
Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account-platform/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice.
+1 -1
View File
@@ -49,7 +49,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一
Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account-platform/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。
+8 -1
View File
@@ -117,7 +117,14 @@ export function desktopAccountBackend(origin: string, invoke: AccountInvoke, coo
}
if (frame.streamId === expiryStreamId && frame.type === 'item' && frame.value === 'session-expired') { expired(); return }
if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream')
if (frame.type === 'item') listener(accountView(frame.value))
if (frame.type === 'item') {
const update = frame.value
if (typeof update !== 'object' || update === null || !('type' in update)
|| (update.type !== 'snapshot' && update.type !== 'credentials-changed') || !('state' in update)) {
throw new Error('desktop account: invalid stream update')
}
listener(accountView(update.state))
}
else socket?.close()
} catch { socket?.close() }
})
+2 -1
View File
@@ -1,7 +1,8 @@
/** Mandatory-update policy, independent of local business traffic and updater artifacts. */
import { valid } from 'semver'
import { platformClientHeaders, type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account'
import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account'
import { platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata'
/** Installed release identity; no field is supplied by a renderer. */
export interface DesktopPolicyIdentity {
+2 -1
View File
@@ -2,7 +2,8 @@
import type { EventEmitter } from 'node:events'
import { createHash, randomUUID } from 'node:crypto'
import { WebContentsView, session, shell, type Session, type View, type WebFrameMain } from 'electron'
import { mergePlatformCookies, platformClientHeaders, type PlatformSession } from '@deepseek-ai/dsh-deepseek-account'
import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account'
import { mergePlatformCookies, platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata'
import { desktopClientMetadata } from './client-metadata.ts'
import { PLATFORM_IPC, type PlatformLocale } from './platform-ipc.ts'
+11 -3
View File
@@ -45,7 +45,12 @@ it('does not replay an expiry reason from an account snapshot', () => {
expect(accountView({ ...state, signOutReason: 'expired' })).toEqual(state)
})
it('receives live expiry separately from account snapshots', async () => {
it.each([
['snapshot', 'invalid'],
['credentials-changed', 'invalid'],
['snapshot', ['snapshot']],
['credentials-changed', ['credentials-changed']],
] as const)('receives %s state updates separately from live expiry and rejects type %j', async (type, invalidType) => {
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
await once(server, 'listening')
onTestFinished(async () => {
@@ -61,8 +66,9 @@ it('receives live expiry separately from account snapshots', async () => {
links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } }
const received = Promise.withResolvers<undefined>()
const backend = desktopAccountBackend(`http://127.0.0.1:${address.port}`, () => Promise.resolve(snapshot), 'dsh-auth-fixture=signed')
const failed = vi.fn()
const stop = backend.watch(
(value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, vi.fn(), expired, onAnalyticsEnabledChanged,
(value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, failed, expired, onAnalyticsEnabledChanged,
)
onTestFinished(stop)
const [, upgrade] = await connected as [unknown, IncomingMessage]
@@ -78,7 +84,7 @@ it('receives live expiry separately from account snapshots', async () => {
if (streams.size === 3) opened.resolve(undefined)
})
await opened.promise
socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: snapshot }))
socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type, state: snapshot } }))
await received.promise
socket.send(JSON.stringify({ type: 'item', streamId: streams.get('productAnalytics/watchPolicy'), value: true }))
await vi.waitFor(() => { expect(onAnalyticsEnabledChanged).toHaveBeenLastCalledWith(true) })
@@ -91,5 +97,7 @@ it('receives live expiry separately from account snapshots', async () => {
expect(expired).not.toHaveBeenCalled()
socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watchExpiry'), value: 'session-expired' }))
await vi.waitFor(() => { expect(expired).toHaveBeenCalledOnce() })
socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type: invalidType, state: snapshot } }))
await vi.waitFor(() => { expect(failed).toHaveBeenCalledOnce() })
stop()
})
+1 -1
View File
@@ -83,7 +83,7 @@ describe.skipIf(!existsSync(builtHost))('built Desktop welcome flow', () => {
const nodeBin = join(root, 'runtime/primary-runtime/dependencies/node/bin')
mkdirSync(nodeBin, { recursive: true })
cpSync(process.execPath, join(nodeBin, process.platform === 'win32' ? 'node.exe' : 'node'))
writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`)
writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n harnessOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`)
let backend: DesktopWelcomeBackend
let hostOrigin = ''
const restart = async (): Promise<void> => {
+13 -3
View File
@@ -25,6 +25,7 @@ async function mockPlatform() {
let state: string | undefined
let redirectUri: string | undefined
let avatarRequests = 0
let notificationLists = 0
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
const reply = (payload: unknown): void => {
@@ -83,7 +84,10 @@ async function mockPlatform() {
reply({ normal_wallets: [{ currency: 'CNY', balance: '1.00' }], bonus_wallets: [] })
return
}
if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { reply([]); return }
if (url.pathname === '/api/v0/users/notifications/list') {
notificationLists++
reply({ next_poll_after: 600, notifications: [] }); return
}
res.writeHead(404).end()
})
await new Promise<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })
@@ -91,7 +95,7 @@ async function mockPlatform() {
if (address === null || typeof address === 'string') throw new Error('account login: missing mock listener')
const origin = `http://127.0.0.1:${String(address.port)}`
return {
origin, inits, pages, avatarRequests: () => avatarRequests,
origin, inits, pages, avatarRequests: () => avatarRequests, notificationLists: () => notificationLists,
close: () => new Promise<void>((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }),
}
}
@@ -144,7 +148,9 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain
await menu.locator('[data-avatar-status="failed"]').waitFor()
expect(await menu.locator('img').count()).toBe(0)
const states: string[] = []
let expectedLists = 1
const capture = async (stage: string): Promise<void> => {
await expect.poll(platform.notificationLists).toBe(expectedLists)
const sidebar = menu.locator('[data-avatar-status]')
const account = page.getByRole('region', { name: 'Account', exact: true })
const mounted = await account.count() > 0
@@ -152,10 +158,11 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain
? await account.locator('[data-avatar-status]').getAttribute('data-avatar-status') : 'unmounted'
states.push(`${stage}: sidebar=${await sidebar.getAttribute('data-avatar-status')}, settings=${settingsStatus}, `
+ `sidebarImages=${await menu.locator('img').count()}, settingsImages=${mounted ? await account.locator('img').count() : 0}, `
+ `requests=${platform.avatarRequests()}`)
+ `requests=${platform.avatarRequests()}, notificationLists=${platform.notificationLists()}`)
}
await capture('Initial load')
await menu.click()
expectedLists++
await page.getByRole('menuitem', { name: 'Settings', exact: true }).click()
const settings = page.getByRole('dialog', { name: 'Settings', exact: true })
const account = settings.getByRole('region', { name: 'Account', exact: true })
@@ -167,6 +174,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain
await settings.getByRole('button', { name: 'Close', exact: true }).click()
await settings.waitFor({ state: 'detached' })
await menu.click()
expectedLists++
await page.getByRole('menuitem', { name: 'Settings', exact: true }).click()
await expect.poll(() => menu.locator('img').count()).toBe(1)
await expect.poll(() => account.locator('img').count()).toBe(1)
@@ -179,6 +187,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain
await settings.getByRole('button', { name: 'Close', exact: true }).click()
await settings.waitFor({ state: 'detached' })
await menu.click()
expectedLists++
await page.getByRole('menuitem', { name: 'Settings', exact: true }).click()
await account.waitFor()
expect(await menu.locator('img').count()).toBe(1)
@@ -194,6 +203,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain
await settings.getByRole('button', { name: 'Close', exact: true }).click()
await settings.waitFor({ state: 'detached' })
await menu.click()
expectedLists++
await page.getByRole('menuitem', { name: 'Settings', exact: true }).click()
await expect.poll(() => menu.locator('img').count()).toBe(1)
await expect.poll(() => account.locator('img').count()).toBe(1)
+269 -62
View File
@@ -22,10 +22,10 @@ const MODE = webSnapshotMode()
const TOKEN = 'dsh_bonus_notice_test'
const ACCOUNT_ID = 'bonus-user'
const ORDER_FIRST = 'bonus-notice-first'
const ORDER_LATER = '33333333-3333-4333-8333-333333333333'
const ORDER_FIRST = 'notice-first'
const ORDER_LATER = 'notice-later'
const ORDER_EN = '44444444-4444-4444-8444-444444444444'
const ORDER_RETRY = '55555555-5555-4555-8555-555555555555'
const ORDER_FAILED_EVENT = '55555555-5555-4555-8555-555555555555'
const ORDER_REPEAT = '66666666-6666-4666-8666-666666666666'
const ORDER_TOPUP = '77777777-7777-4777-8777-777777777777'
const ORDER_WEB = '99999999-9999-4999-8999-999999999999'
@@ -65,9 +65,14 @@ interface AckRecord {
async function mockPlatform() {
const unnotified: Granted[] = []
const gets: GetRecord[] = []
const contentReads: { id: string | null; locale: string | undefined }[] = []
const contents = new Map<string, Granted>()
/** Reads already answered; a request the client is still awaiting is not evidence of a delivered response. */
const served: GetRecord[] = []
const acks: AckRecord[] = []
const dismissals: AckRecord[] = []
const clicks: AckRecord[] = []
let includeUnsupportedNotification = false
/** Wallet reads, one per balance refresh the settings panel performs. */
const summaries: GetRecord[] = []
let normalBalance = '12.34'
@@ -78,20 +83,31 @@ async function mockPlatform() {
let keepUnnotified = false
/** Refuse the wallet read, which is how a Platform outage or an unparsable payload reaches the client. */
let failSummary = false
let holdProfile = false
const pendingProfiles: (() => void)[] = []
const releaseProfiles = (): void => { holdProfile = false; for (const reply of pendingProfiles.splice(0)) reply() }
/** Reply held back while the test controls when a read can answer. */
let heldReply: (() => void) | undefined
const grant = (orderId: string, amount: string, extraCopy = ''): void => {
unnotified.unshift({
const value = {
orderId, amount,
zh_CN: `已赠送您 ${amount} 元 DSH 体验赠金。${extraCopy}`,
en_US: `You received a CNY ${amount} DSH trial credit.${extraCopy}`,
})
}
unnotified.unshift(value)
contents.set(orderId, value)
}
/** @param value - granted bonus. @param locale - request language. @returns its wire fields. */
const wire = (value: Granted, locale: string | undefined): unknown => ({
order_id: value.orderId, expires_at: value.orderId === ORDER_FIRST ? null : expiresAt(),
...(value.orderId === ORDER_FIRST ? { title: '平台通知' } : {}),
msg: locale === 'en_US' ? value.en_US : value.zh_CN,
id: value.orderId, created_at: '2026-10-21T08:00:00Z',
display_until: value.orderId === ORDER_FIRST ? null : expiresAt(),
title: value.orderId === ORDER_FIRST ? (locale === 'en_US' ? 'Platform notice' : '平台通知')
: locale === 'en_US' ? 'Bonus credited' : '赠金已到账',
body: locale === 'en_US' ? value.en_US : value.zh_CN,
actions: value.orderId === 'b1111111-1111-4111-8111-111111111111' ? [
{ label: locale === 'en_US' ? 'View balance' : '查看余额', style: 'primary', target: { type: 'app_route', name: 'account' } },
{ label: locale === 'en_US' ? 'Got it' : '知道了', style: 'secondary', target: { type: 'dismiss' } },
] : [],
})
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
@@ -103,10 +119,14 @@ async function mockPlatform() {
}
if (req.headers['x-dsh-auth-token'] !== TOKEN) { res.writeHead(401).end(); return }
if (url.pathname === '/auth-api/v0/users/current') {
// `email` is required by the provider's profile schema even when the account has none.
reply({ code: 0, data: { biz_code: 0, biz_data: {
id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null },
} } })
const answer = (): void => {
// `email` is required by the provider's profile schema even when the account has none.
reply({ code: 0, data: { biz_code: 0, biz_data: {
id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null },
} } })
}
if (holdProfile) pendingProfiles.push(answer)
else answer()
return
}
if (url.pathname === '/api/v0/users/get_user_summary') {
@@ -118,28 +138,48 @@ async function mockPlatform() {
} } })
return
}
if (url.pathname === '/api/v0/users/get_unnotified_bonuses') {
if (url.pathname === '/api/v0/users/notifications/list') {
const record = { locale, query: url.search }
gets.push(record)
const payload = { code: 0, data: { biz_code: 0, biz_data: unnotified.map(value => wire(value, locale)) } }
const payload = { code: 0, data: { biz_code: 0, biz_data: {
next_poll_after: 3600, notifications: [
...includeUnsupportedNotification ? [{
id: 'unsupported-action', created_at: '2026-10-21T00:00:00Z', display_until: null,
title: 'Unsupported action', body: 'Not supported by this client',
actions: [{ label: 'Open', style: 'primary', target: { type: 'future' } }],
}] : [],
...unnotified.map(value => wire(value, locale)),
],
} } }
const answer = (): void => { served.push(record); reply(payload) }
if (heldReply === undefined) { answer(); return }
heldReply = answer
return
}
if (url.pathname === '/api/v0/users/ack_bonus_notified' && req.method === 'POST') {
if (url.pathname === '/api/v0/users/notifications/content') {
const id = url.searchParams.get('id')
contentReads.push({ id, locale })
const value = id === null ? undefined : contents.get(id)
if (value === undefined) { res.writeHead(404).end(); return }
reply({ code: 0, data: { biz_code: 0, biz_data: wire(value, locale) } })
return
}
if (url.pathname === '/api/v0/users/notifications/events' && req.method === 'POST') {
let body = ''
req.setEncoding('utf8')
req.on('data', (chunk: string) => { body += chunk })
req.on('end', () => {
const payload: unknown = JSON.parse(body)
const orderId = typeof payload === 'object' && payload !== null && 'order_id' in payload
&& typeof payload.order_id === 'string' ? payload.order_id : null
acks.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body,
const orderId = typeof payload === 'object' && payload !== null && 'notification_id' in payload
&& typeof payload.notification_id === 'string' ? payload.notification_id : null
const event = typeof payload === 'object' && payload !== null && 'type' in payload ? payload.type : null
if (event !== 'displayed' && event !== 'cta_clicked' && event !== 'dismissed') { res.writeHead(400).end(); return }
const records = event === 'displayed' ? acks : event === 'cta_clicked' ? clicks : dismissals
records.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body,
query: url.search, contentType: req.headers['content-type'], at: performance.now() })
if (ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) {
if (event === 'displayed' && ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) {
ackFailure.remaining--
// A transient gateway failure: the client retries it after its backoff.
// The event is lost; a later notification read can offer this order again.
res.writeHead(502, { 'content-type': 'text/plain' }).end('Internal Server Error')
return
}
@@ -147,8 +187,8 @@ async function mockPlatform() {
reply({ code: 0, msg: '', data: { biz_code: 1, biz_msg: 'BONUS_ORDER_NOT_FOUND', biz_data: null } }); return
}
const index = unnotified.findIndex(value => value.orderId === orderId)
if (index >= 0 && !keepUnnotified) unnotified.splice(index, 1)
reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: null } })
if (index >= 0 && !keepUnnotified && event !== 'cta_clicked') unnotified.splice(index, 1)
reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: { acked: true } } })
})
return
}
@@ -160,7 +200,11 @@ async function mockPlatform() {
if (address === null || typeof address === 'string') throw new Error('bonus notice: missing mock listener')
return {
origin: `http://127.0.0.1:${String(address.port)}`,
grant, gets, served, acks, summaries,
grant, gets, served, acks, clicks, dismissals, summaries, contentReads,
setUnsupportedNotification: (value: boolean): void => { includeUnsupportedNotification = value },
holdProfiles: (): void => { holdProfile = true },
pendingProfileResponses: (): number => pendingProfiles.length,
releaseProfiles,
/** @param value - recharge balance the settings page reads next. */
setNormalBalance: (value: string): void => { normalBalance = value },
/** @param value - bonus balance the settings page reads next. */
@@ -176,7 +220,7 @@ async function mockPlatform() {
/** Hold the next unnotified-bonus read so the test can observe the in-flight state. */
holdNextGet: (): void => { heldReply = () => undefined },
releaseGet: (): void => { const held = heldReply; heldReply = undefined; held?.() },
close: () => new Promise<void>((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }),
close: () => new Promise<void>((resolve) => { releaseProfiles(); server.close(() => { resolve() }); server.closeAllConnections() }),
}
}
@@ -286,6 +330,8 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
// A read the renderer never received cannot become a displayed notice: while the
// response is held there is no card and no acknowledgement.
platform.holdNextGet()
platform.holdProfiles()
platform.setUnsupportedNotification(true)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await expect.poll(() => platform.gets.length, { timeout: 30_000 }).toBe(1)
observations.push(`startup.held cards=${String(await noticeCards(page).count())} acks=${String(platform.acks.length)}`)
@@ -296,21 +342,34 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
// Startup signs in and reads the notice; the card shows it and only then is it acknowledged.
observations.push(`startup.notice=${await shownNotice(page, zhFirst)}`)
observations.push(`startup.ack orders=${await acked(platform, 1)}`)
expect(await noticeCards(page).count()).toBe(1)
expect(platform.acks.some(record => record.orderId === 'unsupported-action')).toBe(false)
observations.push('startup.unsupported-action skipped=true valid-card=true displayed=false')
platform.setUnsupportedNotification(false)
await expect.poll(platform.pendingProfileResponses).toBeGreaterThan(0)
observations.push('startup.profile-pending notice=true displayed=1')
platform.releaseProfiles()
const get = platform.gets[0]!
const ack = platform.acks[0]!
observations.push(`startup.get locale=${String(get.locale)} query=${get.query}`)
observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} order_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`)
observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} notification_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`)
expect(get.locale).toBe('zh_CN')
expect(get.query).toBe('')
expect(ack).toMatchObject({
method: 'POST', path: '/api/v0/users/ack_bonus_notified', locale: 'zh_CN', orderId: ORDER_FIRST,
body: JSON.stringify({ order_id: ORDER_FIRST }), query: '', contentType: 'application/json',
method: 'POST', path: '/api/v0/users/notifications/events', locale: 'zh_CN', orderId: ORDER_FIRST,
body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'displayed' }), query: '', contentType: 'application/json',
})
// Closing the card only hides it; the acknowledgement already sent is not repeated.
// Explicit close reports dismissal without repeating the display event.
await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click()
expect(await noticeCards(page).count()).toBe(0)
expect(platform.acks).toHaveLength(1)
await expect.poll(() => platform.dismissals.length).toBe(1)
expect(platform.dismissals[0]).toMatchObject({
method: 'POST', path: '/api/v0/users/notifications/events', orderId: ORDER_FIRST,
body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'dismissed' }),
})
observations.push('startup.close event=dismissed displayed=1 dismissed=1')
// A new grant and balance arrive before settings opens; one panel entry refreshes both once.
platform.grant(ORDER_LATER, '8.00')
@@ -463,32 +522,27 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click()
expect(await noticeCards(page).count()).toBe(0)
// A transient acknowledgement failure keeps the card and retries the same order after
// the backoff; the pending retry is page state, not browser storage.
const zhRetry = '已赠送您 6.00 元 DSH 体验赠金。'
platform.grant(ORDER_RETRY, '6.00')
platform.failNextAcks(ORDER_RETRY, 1)
// A failed event leaves the card intact and is not retried in the background.
const zhFailedEvent = '已赠送您 6.00 元 DSH 体验赠金。'
platform.grant(ORDER_FAILED_EVENT, '6.00')
platform.failNextAcks(ORDER_FAILED_EVENT, 1)
await openSettings(page, 'zh')
const retryDialog = page.getByRole('dialog', { name: '设置', exact: true })
await retryDialog.waitFor()
observations.push(`retry.notice=${await shownNotice(page, zhRetry)}`)
const retryAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_RETRY)
await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(1)
// The failed attempt does not withdraw the card the user is reading.
expect(await noticeCards(page).count()).toBe(1)
await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(2)
const attempts = retryAttempts()
// The first retry follows the configured first delay rather than arriving immediately.
// Only the lower bound is asserted: load can widen the observed gap, never shorten it
// below the timer's own 1s first step.
const retryGapMs = attempts[1]!.at - attempts[0]!.at
const retryBodyKept = attempts.every(item => item.body === JSON.stringify({ order_id: ORDER_RETRY })
const failedEventDialog = page.getByRole('dialog', { name: '设置', exact: true })
await failedEventDialog.waitFor()
observations.push(`event-failed.notice=${await shownNotice(page, zhFailedEvent)}`)
const failedAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_FAILED_EVENT)
await expect.poll(() => failedAttempts().length, { timeout: 30_000 }).toBe(1)
await page.clock.install()
await page.clock.fastForward(60_000)
const attempts = failedAttempts()
const eventBodyKept = attempts.every(item => item.body === JSON.stringify({ notification_id: ORDER_FAILED_EVENT, type: 'displayed' })
&& item.query === '' && item.contentType === 'application/json')
observations.push(`retry.attempts=${String(attempts.length)} backoff=${String(retryGapMs >= 900)} body-kept=${String(retryBodyKept)} cards=${String(await noticeCards(page).count())}`)
expect(retryGapMs).toBeGreaterThanOrEqual(900)
expect(retryBodyKept).toBe(true)
observations.push(`event-failed.attempts=${String(attempts.length)} body-kept=${String(eventBodyKept)} cards=${String(await noticeCards(page).count())}`)
expect(attempts).toHaveLength(1)
expect(eventBodyKept).toBe(true)
expect(await noticeCards(page).count()).toBe(1)
await page.keyboard.press('Escape')
await retryDialog.waitFor({ state: 'detached', timeout: 30_000 })
await failedEventDialog.waitFor({ state: 'detached', timeout: 30_000 })
await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click()
// Display follows each response: the double keeps serving an acknowledged order, which
@@ -580,31 +634,72 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
observations.push(`web.notice=${webNotice} acks=1`)
await webPage.close()
platform.clearUnnotified()
platform.grant('stack-third', '23.00')
platform.grant('stack-second', '22.00', '\nMore details'.repeat(8))
platform.grant('stack-first', '21.00')
platform.grant('a3333333-3333-4333-8333-333333333333', '23.00')
platform.grant('a2222222-2222-4222-8222-222222222222', '22.00', '\nMore details'.repeat(8))
platform.grant('a1111111-1111-4111-8111-111111111111', '21.00')
const ackStart = platform.acks.length
const stackPage = await openDesktopPage('zh-CN')
await stackPage.setViewportSize({ width: 900, height: 960 })
await stackPage.emulateMedia({ colorScheme: 'light' })
await stackPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
const cards = noticeCards(stackPage)
await expect.poll(() => cards.count()).toBe(3)
expect(await cards.first().isVisible()).toBe(false)
expect(platform.acks.length).toBe(ackStart)
observations.push('stack.hidden cards=3 acks=0')
await stackPage.setViewportSize({ width: 1440, height: 960 })
await expect.poll(() => cards.first().isVisible()).toBe(true)
await expect.poll(() => platform.acks.length).toBe(ackStart + 1)
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first'])
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111'])
expect(await stackPage.getByRole('status').count()).toBe(1)
const second = cards.filter({ hasText: '22.00' })
const secondNode = await second.elementHandle()
const frontBox = await cards.first().boundingBox()
const backBox = await second.boundingBox()
expect(frontBox!.width).toBeCloseTo(280, 0)
expect(backBox!.width).toBeCloseTo(272, 0)
expect(frontBox!.x).toBeCloseTo(10, 0)
expect(frontBox!.width).toBeCloseTo(260, 0)
expect(frontBox!.x + frontBox!.width).toBeCloseTo(270, 0)
expect(backBox!.width).toBeCloseTo(252, 0)
expect(backBox!.y).toBeCloseTo(frontBox!.y - 4, 0)
const transition = await second.evaluate((element) => {
const style = getComputedStyle(element)
return `${style.transitionDuration} ${style.transitionTimingFunction}`
})
expect(transition).toBe('0.25s ease-out')
observations.push(`stack.initial cards=3 acks=stack-first widths=280,272 offset=-4 transition=${transition}`)
observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`)
for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) {
const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox()
const x = handle!.x + handle!.width / 2
const y = handle!.y + handle!.height / 2
await stackPage.mouse.move(x, y)
await stackPage.mouse.down()
await stackPage.mouse.move(x + delta, y, { steps: 5 })
await stackPage.mouse.up()
await expect.poll(async () => Math.round((await cards.first().boundingBox())!.width)).toBe(width)
const movedHandle = await stackPage.locator('[data-side="sidebar"]').boundingBox()
expect(movedHandle!.x + movedHandle!.width / 2).toBeCloseTo(edge, 0)
const resized = await cards.first().boundingBox()
expect(resized!.x).toBeCloseTo(10, 0)
expect(resized!.x + resized!.width).toBeCloseTo(10 + width, 0)
observations.push(`stack.resized sidebar=${edge} card=${width} left-inset=10`)
}
const beforeCollapseAcks = platform.acks.length
const beforeCollapseDismissals = platform.dismissals.length
await stackPage.setViewportSize({ width: 900, height: 960 })
await stackPage.locator('[data-sidebar-collapsed]:not([data-sidebar-drawer])').waitFor()
await expect.poll(() => cards.first().isVisible()).toBe(false)
expect(await cards.count()).toBe(3)
expect(platform.dismissals.length).toBe(beforeCollapseDismissals)
observations.push('stack.rail cards=3 visible=false dismissed=0')
await stackPage.setViewportSize({ width: 1440, height: 960 })
await stackPage.locator('[data-sidebar-collapsed]').waitFor({ state: 'detached' })
await expect.poll(() => cards.first().isVisible()).toBe(true)
expect(await cards.count()).toBe(3)
expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true)
expect(await cardText(cards.first())).toContain('21.00')
expect(platform.acks.length).toBe(beforeCollapseAcks)
expect(platform.dismissals.length).toBe(beforeCollapseDismissals)
observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0')
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
await mkdir(artifactDir, { recursive: true })
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') })
@@ -635,20 +730,132 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
expect(promotion.middle.y).toBeLessThan(promotion.start.y)
expect(promotion.middle.y).toBeGreaterThan(promotion.end.y)
await expect.poll(() => cards.count()).toBe(2)
await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(280)
await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(260)
expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true)
expect(await second.getAttribute('data-front')).toBe('true')
await expect.poll(() => platform.acks.length).toBe(ackStart + 2)
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second'])
observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=280 same-node=true')
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222'])
observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true')
await second.getByRole('button', { name: '关闭', exact: true }).click()
await expect.poll(() => platform.acks.length).toBe(ackStart + 3)
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second', 'stack-third'])
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333'])
await cards.filter({ hasText: '23.00' }).getByRole('button', { name: '关闭', exact: true }).click()
await expect.poll(() => cards.count()).toBe(0)
await expect.poll(() => platform.dismissals.filter(record => record.orderId?.startsWith('a')).length).toBe(3)
const stackDismissals = platform.dismissals.filter(record => record.orderId?.startsWith('a'))
expect(stackDismissals.map(record => record.body)).toEqual(stackDismissals.map(record =>
JSON.stringify({ notification_id: record.orderId, type: 'dismissed' })))
observations.push('stack.dismissed cards=0 acks=stack-first,stack-second,stack-third')
await stackPage.close()
platform.grant('b1111111-1111-4111-8111-111111111111', '31.00')
const refreshAckStart = platform.acks.length
const refreshPage = await openDesktopPage('zh-CN')
await refreshPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
const refreshCards = noticeCards(refreshPage)
await shownNotice(refreshPage, '已赠送您 31.00 元 DSH 体验赠金。')
await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 1)
const firstNode = await refreshCards.first().elementHandle()
platform.grant('b3333333-3333-4333-8333-333333333333', '33.00')
platform.grant('b2222222-2222-4222-8222-222222222222', '32.00')
await openSettings(refreshPage, 'zh')
await expect.poll(() => refreshCards.count()).toBe(3)
expect(await cardText(refreshCards.first())).toContain('31.00')
expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true)
expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111'])
observations.push('refresh.retained cards=3 acks=refresh-first same-node=true')
const localeReads = platform.gets.length
const localeContents = platform.contentReads.length
await refreshPage.getByRole('dialog', { name: '设置', exact: true }).getByRole('button', { name: '通用设置', exact: true }).click()
await refreshPage.getByRole('button', { name: '中文', exact: true }).click()
await refreshPage.getByRole('menuitem', { name: 'English', exact: true }).click()
await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor()
await expect.poll(() => cardText(refreshCards.first())).toContain('You received a CNY 31.00')
expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true)
expect(platform.gets.length).toBe(localeReads)
expect(platform.acks.length).toBe(refreshAckStart + 1)
expect(platform.contentReads.slice(localeContents).map(read => read.locale)).toEqual(['en_US', 'en_US', 'en_US'])
expect(await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).count()).toBe(1)
observations.push('refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true')
await refreshPage.keyboard.press('Escape')
await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor({ state: 'detached' })
const clicksBeforeAction = platform.clicks.length
const dismissalsBeforeClick = platform.dismissals.length
await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).click()
await expect.poll(() => platform.clicks.length).toBe(clicksBeforeAction + 1)
expect(platform.clicks.at(-1)?.body).toBe(JSON.stringify({ notification_id: 'b1111111-1111-4111-8111-111111111111', type: 'cta_clicked' }))
expect(platform.dismissals.length).toBe(dismissalsBeforeClick)
expect(await refreshCards.count()).toBe(3)
const accountSettings = refreshPage.getByRole('dialog', { name: 'Settings', exact: true })
await accountSettings.waitFor()
expect(await accountSettings.getByRole('button', { name: 'Account', exact: true }).getAttribute('aria-current')).toBe('true')
observations.push('refresh.business-action event=cta_clicked cards=3 account-open=true')
await refreshPage.keyboard.press('Escape')
await accountSettings.waitFor({ state: 'detached' })
await refreshPage.setViewportSize({ width: 390, height: 844 })
await refreshPage.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor()
await expect.poll(() => refreshCards.first().isVisible()).toBe(false)
expect(await refreshCards.count()).toBe(3)
await refreshPage.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click()
const drawer = refreshPage.locator('[data-sidebar-drawer]:not([data-sidebar-collapsed])')
await drawer.waitFor()
expect(await refreshCards.first().evaluate(element => element.closest('[role="dialog"]')?.getAttribute('aria-label'))).toBe('Navigation')
await expect.poll(() => drawer.locator('[data-sidebar-mask]').evaluate(element => getComputedStyle(element).opacity)).toBe('1')
await expect.poll(() => refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).evaluate((element) => {
const rect = element.getBoundingClientRect()
return element.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2))
})).toBe(true)
observations.push('refresh.drawer width=390 notice-above-sidebar=true')
const cardBounds = await refreshCards.first().boundingBox()
const drawerBounds = await drawer.getByRole('dialog', { name: 'Navigation', exact: true }).boundingBox()
const actionBounds = await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).boundingBox()
expect(cardBounds!.x - drawerBounds!.x).toBeCloseTo(10, 0)
expect(drawerBounds!.width - cardBounds!.width).toBeCloseTo(20, 0)
expect(cardBounds!.x).toBeGreaterThanOrEqual(0)
expect(cardBounds!.x + cardBounds!.width).toBeLessThanOrEqual(390)
expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(cardBounds!.x + cardBounds!.width)
const dismissalsBeforeAction = platform.dismissals.length
await refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).click()
expect(await drawer.count()).toBe(1)
await expect.poll(() => platform.dismissals.length).toBe(dismissalsBeforeAction + 1)
expect(platform.dismissals.at(-1)?.orderId).toBe('b1111111-1111-4111-8111-111111111111')
expect(platform.clicks.length).toBe(clicksBeforeAction + 1)
observations.push('refresh.action event=dismissed got-it=true')
await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 2)
expect(await cardText(refreshCards.first())).toContain('32.00')
observations.push('refresh.promoted cards=2 acks=refresh-first,refresh-second')
await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click()
await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 3)
expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111', 'b2222222-2222-4222-8222-222222222222', 'b3333333-3333-4333-8333-333333333333'])
await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click()
await expect.poll(() => refreshCards.count()).toBe(0)
observations.push('refresh.dismissed cards=0 acks=refresh-first,refresh-second,refresh-third')
await refreshPage.close()
const pollFirst = 'c1111111-1111-4111-8111-111111111111'
const pollSecond = 'c2222222-2222-4222-8222-222222222222'
platform.grant(pollFirst, '41.00')
const pollPage = await openDesktopPage('en-US')
await pollPage.clock.install()
await pollPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await shownNotice(pollPage, 'You received a CNY 41.00 DSH trial credit.')
await expect.poll(() => platform.acks.at(-1)?.orderId).toBe(pollFirst)
const pollCards = noticeCards(pollPage)
const retainedNode = await pollCards.first().elementHandle()
const pollReads = platform.gets.length
const pollAcks = platform.acks.length
platform.grant(pollSecond, '42.00')
await pollPage.clock.fastForward(3_600_000)
await expect.poll(() => pollCards.count()).toBe(2)
expect(platform.gets.length).toBe(pollReads + 1)
expect(platform.acks.length).toBe(pollAcks)
expect(await pollCards.first().evaluate((element, previous) => element === previous, retainedNode)).toBe(true)
await openSettings(pollPage, 'en')
await expect.poll(() => platform.gets.length).toBe(pollReads + 2)
expect(await pollCards.count()).toBe(2)
observations.push('poll.arrival cards=2 list-reads=1 duplicate-acks=0 same-node=true settings-immediate-read=true')
await pollPage.close()
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'notice-flow.expected.md'), observations.join('\n'), MODE)
for (const tripwire of tripwires) {
expect(tripwire.warnings).toEqual([])
+144 -37
View File
@@ -6,7 +6,7 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import type { Browser, Page, Route } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import type { StreamChunk } from '@deepseek-ai/dsh-llm'
@@ -367,13 +367,71 @@ async function flingTranscript(page: Page, deltaY: number): Promise<void> {
await nextPaint(page)
}
async function wheelToHistoryStart(page: Page): Promise<void> {
for (let attempt = 0; attempt < 12; attempt += 1) {
if ((await scrollGeometry(page)).scrollTop <= 1) break
await wheelTranscript(page, -2_400)
/**
* Hold paging responses so auto-prefetch cannot publish a page mid-gesture.
* @param page - Chat page under test.
* @returns an idempotent release that resumes held responses and awaits them.
*/
async function holdHistoryPages(page: Page): Promise<() => Promise<void>> {
const gate = Promise.withResolvers<undefined>()
const pending = new Set<Promise<void>>()
const hold = (route: Route): Promise<void> => {
const work = gate.promise.then(() => route.continue())
pending.add(work)
return work.finally(() => { pending.delete(work) })
}
await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 })
.toBeLessThanOrEqual(1)
await page.route('**/api/session/page', hold)
let released = false
return async () => {
if (released) return
released = true
gate.resolve(undefined)
// Resume held requests before removing the handler: unregistering with a
// hold still pending lets Playwright handle that route itself, after which
// the delayed continue() fails with "Route is already handled".
while (pending.size > 0) await Promise.all([...pending])
await page.unroute('**/api/session/page', hold)
}
}
/**
* Wait until a released page has landed and the history control stopped changing.
* @param page - Chat page under test.
* @returns the settled rendered row count.
*/
async function settleHistoryPaging(page: Page): Promise<number> {
let rows = -1
await expect.poll(async () => {
if (await page.locator('[data-chat-history]').getAttribute('data-chat-history') === 'loading') return false
const current = await loadedFlowRows(page)
const stable = current === rows
rows = current
return stable
}, { timeout: 30_000 }).toBe(true)
await nextPaint(page)
return rows
}
/**
* Wheel back to the start of the loaded window.
* @param page - Chat page under test.
* @param options - holdPaging keeps auto-prefetch from publishing a page that re-anchors the viewport mid-scroll.
*/
async function wheelToHistoryStart(page: Page, options: { holdPaging?: boolean } = {}): Promise<void> {
const release = options.holdPaging === true ? await holdHistoryPages(page) : undefined
try {
for (let attempt = 0; attempt < 12; attempt += 1) {
if ((await scrollGeometry(page)).scrollTop <= 1) break
await wheelTranscript(page, -2_400)
}
await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 })
.toBeLessThanOrEqual(1)
} finally {
await release?.()
}
// A held page is released at the history edge, where the client publishes it
// as soon as it arrives; settle that prepend before the caller measures.
if (options.holdPaging === true) await settleHistoryPaging(page)
}
async function wheelUntilMounted(page: Page, selector: string, deltaY: number): Promise<void> {
@@ -476,23 +534,32 @@ async function expectMarkerAboveComposer(page: Page, marker: string): Promise<vo
expect(geometry.rowBottom).toBeLessThanOrEqual(geometry.composerTop + GEOMETRY_TOLERANCE)
}
async function loadEarlierWithAnchor(page: Page): Promise<void> {
await wheelToHistoryStart(page)
const older = page.getByRole('button', { name: 'Load earlier', exact: true })
const loading = page.getByRole('button', { name: 'Loading…', exact: true })
await older.waitFor({ timeout: 10_000 })
const anchor = await visibleFlowAnchor(page)
const before = await loadedFlowRows(page)
await older.click()
await expect.poll(async () => (
await loadedFlowRows(page) > before && await loading.count() === 0
), { timeout: 30_000 }).toBe(true)
await nextPaint(page)
if (await page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) {
expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0)
return
async function loadEarlierWithAnchor(page: Page): Promise<boolean> {
// Auto-prefetch may start while scrolling to the button. Hold its response until the reading anchor is captured.
const release = await holdHistoryPages(page)
try {
await wheelToHistoryStart(page)
const history = page.locator('[data-chat-history]')
const older = history.getByRole('button')
await older.waitFor({ timeout: 10_000 })
if (await older.isDisabled()) return false
const anchor = await visibleFlowAnchor(page)
const before = await loadedFlowRows(page)
await older.click()
await release()
await expect.poll(async () => (
await loadedFlowRows(page) > before && await history.getAttribute('data-chat-history') === 'idle'
), { timeout: 30_000 }).toBe(true)
await nextPaint(page)
if (await older.isDisabled()) {
expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0)
return true
}
await expectSameFlowTop(page, anchor)
return true
} finally {
await release()
}
await expectSameFlowTop(page, anchor)
}
async function fileExists(path: string): Promise<boolean> {
@@ -1300,6 +1367,8 @@ describe('web e2e: long Chat scroll contract', () => {
let releaseHistory = (): void => {}
let held = false
let historyRequests = 0
const heldContinued = Promise.withResolvers<undefined>()
let releaseGate: (() => void) | undefined
const gate = new Promise<void>((resolve) => { releaseGate = resolve })
releaseHistory = () => { releaseGate?.() }
@@ -1308,12 +1377,17 @@ describe('web e2e: long Chat scroll contract', () => {
method?: string
payload?: { args?: { request?: { beforeSeq?: number } } }
}
if (!held && request.method === 'session/page'
&& request.payload?.args?.request?.beforeSeq !== undefined) {
const historyRequest = request.method === 'session/page' && request.payload?.args?.request?.beforeSeq !== undefined
if (historyRequest) historyRequests += 1
if (!held && historyRequest) {
held = true
await gate
}
await route.continue()
try {
await route.continue()
} finally {
heldContinued.resolve(undefined)
}
} else await route.continue()
})
const settled = world.scaffold.whenTurnSettled(60_000)
@@ -1325,8 +1399,12 @@ describe('web e2e: long Chat scroll contract', () => {
await world.page.getByText(LIVE_TEXT_FIRST, { exact: false }).last().waitFor({ timeout: 15_000 })
await wheelToHistoryStart(world.page)
const beforeRows = await loadedFlowRows(world.page)
await world.page.getByRole('button', { name: 'Load earlier', exact: true }).click()
await expect.poll(() => held, { timeout: 10_000 }).toBe(true)
const history = world.page.locator('[data-chat-history]')
await expect.poll(() => history.getAttribute('data-chat-history')).toBe('loading')
// The upward gesture already requested the page. A click joins that request even though its label is loading.
await history.getByRole('button').click()
expect(historyRequests).toBe(1)
await wheelTranscript(world.page, 420)
const readerAnchor = await visibleFlowAnchor(world.page)
@@ -1344,6 +1422,9 @@ describe('web e2e: long Chat scroll contract', () => {
} finally {
releaseText()
releaseHistory()
if (held) await heldContinued.promise
// Release both producers before disposing the Session even if an assertion above fails.
await settled
}
await settled
@@ -1353,10 +1434,10 @@ describe('web e2e: long Chat scroll contract', () => {
let additionalPages = 0
while (additionalPages < 8) {
await wheelToHistoryStart(world.page)
if (await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) break
await loadEarlierWithAnchor(world.page)
additionalPages += 1
const before = await loadedFlowRows(world.page)
const consumed = await loadEarlierWithAnchor(world.page)
if (consumed || await loadedFlowRows(world.page) > before) additionalPages += 1
if (await world.page.locator('[data-chat-history]').getByRole('button').isDisabled()) break
}
expect(additionalPages).toBeGreaterThan(0)
// The whole log is loaded: turn 1's unique marker renders in the
@@ -1364,7 +1445,9 @@ describe('web e2e: long Chat scroll contract', () => {
// page remains.
expect(await world.page.locator('[data-conversation-scroll]')
.getByText(HISTORY_FIXTURE.markers.user(1), { exact: false }).count()).toBe(1)
expect(await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count()).toBe(0)
const history = world.page.locator('[data-chat-history]')
expect(await history.getAttribute('data-chat-history')).toBe('idle')
expect(await history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled()).toBe(true)
assertClean(world)
})
}, 180_000)
@@ -1669,9 +1752,33 @@ describe('web e2e: long Chat scroll contract', () => {
await liveRow.click()
await expect.poll(() => liveRow.getAttribute('aria-expanded'), { timeout: 10_000 }).toBe('true')
await expectSameFlowTop(world.page, toolAnchor)
await wheelToHistoryStart(world.page)
await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
await expectBottom(world.page)
// This cycle tests disclosure retention, not pagination: keep auto-prefetch from moving its scroll-away endpoint.
const historyGate = Promise.withResolvers<undefined>()
const pendingHistory = new Set<Promise<void>>()
let historyHeld = false
const holdHistory = (route: Route): Promise<void> => {
historyHeld = true
const work = historyGate.promise.then(() => route.continue())
pendingHistory.add(work)
return work.finally(() => { pendingHistory.delete(work) })
}
await world.page.route('**/api/session/page', holdHistory, { times: 1 })
try {
const beforeRows = await loadedFlowRows(world.page)
await wheelToHistoryStart(world.page)
await expect.poll(() => historyHeld, { timeout: 10_000 }).toBe(true)
expect(await loadedFlowRows(world.page)).toBe(beforeRows)
await world.page.getByRole('button', { name: 'Back to bottom', exact: true }).click()
await expectBottom(world.page)
} finally {
historyGate.resolve(undefined)
await Promise.all([...pendingHistory])
await world.page.unroute('**/api/session/page', holdHistory)
}
await expect.poll(async () => {
const state = await world.page.locator('[data-chat-history]').getAttribute('data-chat-history')
return state === 'pendingConsumption' || state === 'idle'
}, { timeout: 10_000 }).toBe(true)
await wheelUntilMounted(world.page, liveRowSelector, -1_100)
const restoredRow = world.page.locator(liveRowSelector)
await restoredRow.waitFor({ timeout: 10_000 })
@@ -1696,7 +1803,7 @@ describe('web e2e: long Chat scroll contract', () => {
)
await loadEarlierWithAnchor(world.page)
await loadEarlierWithAnchor(world.page)
await wheelToHistoryStart(world.page)
await wheelToHistoryStart(world.page, { holdPaging: true })
await wheelTranscript(world.page, 1_300)
const sessionAnchor = await visibleFlowAnchor(world.page)
@@ -1,9 +1,14 @@
/** Web DeepSeek configuration, credential reuse, and saved model selection. */
/** Web provider credentials, environment fallback, and DeepSeek model selection. */
import { readFile } from 'node:fs/promises'
import { once } from 'node:events'
import { createServer } from 'node:http'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, webkit, type Browser, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { BlockAssembler, createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import {
captureStableAria, compareOrRefreshGolden, launchWebScaffold,
watchConsole, webSnapshotMode, type WebScaffold,
@@ -12,6 +17,157 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA
const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url))
it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'acme-gateway'])(
'clears the saved %s key and sends the next request with environment authentication', async (provider) => {
const messages = provider === 'deepseek-official'
const google = provider === 'google'
const ref = credentialRef(messages ? 'DEEPSEEK_API_KEY' : `${provider.toUpperCase().replaceAll('-', '_')}_API_KEY`)
const envRef = google ? 'GEMINI_API_KEY' : ref
const calls: { path: string; key: string | undefined }[] = []
const server = createServer((request, response) => {
request.on('end', () => {
const key = request.headers[messages ? 'x-api-key' : google ? 'x-goog-api-key' : 'authorization']
calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined })
const events = messages ? [
{ type: 'message_start', message: { id: 'clear', type: 'message', role: 'assistant', model: 'clear-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
] : google ? [{ candidates: [{ content: { role: 'model', parts: [{ text: 'connection-ok' }] }, finishReason: 'STOP' }] }]
: [{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: 'connection-ok' }, finish_reason: null }] },
{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }]
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join(''))
})
request.resume()
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
let scaffold: WebScaffold | undefined
let browser: Browser | undefined
try {
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('Missing credential test listener')
const baseURL = `http://127.0.0.1:${String(address.port)}/configured`
scaffold = await launchWebScaffold({
deepSeekMissingCredential: true,
openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { [envRef]: 'fixture-environment-key' } }]),
})
const profile = { apiKeyEnv: ref, baseURL, models: [{ id: 'clear-model' }],
...messages || google ? {} : { api: 'openai-completions' } }
await scaffold.ctx.settings.mutate(messages ? 'llm-deepseek' : 'llm-pi-ai', [{
op: 'set', path: messages ? [] : ['providers', provider], value: profile,
}])
await scaffold.ctx.credentials.set(ref, 'fixture-saved-key')
const runtime = scaffold.ctx
const generate = async (): Promise<void> => {
const assembler = new BlockAssembler()
const chunks: StreamChunk[] = []
for await (const chunk of runtime.llm.stream({ provider, model: 'clear-model',
messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply connection-ok' }], source: { kind: 'user' } })] })) {
chunks.push(chunk)
assembler.push(chunk)
}
expect(assembler.message({ provider, model: 'clear-model' }).content, JSON.stringify(chunks))
.toContainEqual({ type: 'text', text: 'connection-ok' })
}
await generate()
browser = await chromium.launch()
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await page.goto(scaffold.authenticatedUrl)
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
await key.press('Delete')
expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`)
await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor()
expect((await runtime.credentials.resolve(ref))?.source).toBe('file')
if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode())
await dialog.getByRole('button', { name: '取消', exact: true }).click()
expect((await runtime.credentials.resolve(ref))?.source).toBe('file')
await edit.click()
await key.press('Delete')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(calls).toHaveLength(2)
expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key')
expect(calls[1]).toEqual({ path: calls[0]?.path,
key: messages || google ? 'fixture-environment-key' : 'Bearer fixture-environment-key' })
expect(calls[1]?.path).toContain('/configured/')
expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).not.toContain('fixture-saved-key')
await edit.click()
await dialog.getByText(`已检测到环境变量(${envRef})`, { exact: true }).waitFor()
await dialog.getByText('自定义设置', { exact: true }).click()
expect(await dialog.getByLabel('API 地址', { exact: true }).inputValue()).toBe(baseURL)
expect(await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).count()).toBe(0)
} finally {
try { await browser?.close() } finally {
try { await scaffold?.close() } finally {
await new Promise<void>((resolve, reject) => server.close((error) => {
if (error === undefined) resolve()
else reject(error)
}))
}
}
}
},
)
it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])(
'protects saved keys and reveals only unsaved replacements in $name', async ({ engine }) => {
const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true })
let browser: Browser | undefined
try {
await scaffold.ctx.credentials.set(credentialRef('DEEPSEEK_API_KEY'), 'fixture-protected-old-key')
browser = await engine.launch()
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await page.goto(scaffold.authenticatedUrl)
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`)
expect(await key.inputValue()).toBe('')
expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0)
expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key')
await key.press('Backspace')
await dialog.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor()
expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)')
await dialog.getByRole('button', { name: '取消', exact: true }).click()
await edit.click()
expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`)
await key.fill('fixture-new-key')
await dialog.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor()
await dialog.getByRole('button', { name: '显示密钥', exact: true }).click()
expect(await key.getAttribute('type')).toBe('text')
expect(await key.inputValue()).toBe('fixture-new-key')
await key.press('ControlOrMeta+A')
await key.press('ControlOrMeta+X')
await expect.poll(() => key.inputValue()).toBe('')
await key.fill('fixture-new-key')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await edit.click()
expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length))
expect(await key.inputValue()).toBe('')
expect(await key.getAttribute('type')).toBe('password')
expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0)
expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key')
} finally {
try { await browser?.close() } finally { await scaffold.close() }
}
},
)
it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])(
'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => {
const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true })
@@ -90,6 +246,10 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1)
await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
const messages = dialog
const key = messages.getByLabel('API 密钥', { exact: true })
expect(await key.inputValue()).toBe('')
expect(await key.getAttribute('placeholder')).toBe(`sk-messa${'•'.repeat(10)}ding`)
await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor()
await messages.getByText('自定义设置', { exact: true }).click()
expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder'))
.toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)')
@@ -114,6 +274,17 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY')
expect(await page.locator('body').innerText()).not.toContain('sk-e2e-')
await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click()
expect(await key.inputValue()).toBe('')
await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor()
expect(await key.getAttribute('type')).toBe('password')
await key.fill('sk-cancelled-replacement')
await messages.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor()
expect(await messages.getByText('使用已保存的 API key。', { exact: true }).count()).toBe(0)
await key.fill('')
await messages.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor()
await messages.getByRole('button', { name: '取消', exact: true }).click()
expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials)
await page.keyboard.press('Escape')
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e')
await page.getByRole('button', { name: /^选择模型/ }).click()
+9 -9
View File
@@ -51,21 +51,21 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () =>
screenshots = undefined
root = await mkdtemp(join(tmpdir(), 'dsh-desktop-onboarding-'))
server = createServer((request, response) => {
if (request.url === '/api/v0/users/get_unnotified_bonuses') {
if (request.url === '/api/v0/users/notifications/list') {
bonusReads++
response.setHeader('content-type', 'application/json')
response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: bonusOffered ? [{
order_id: '88888888-8888-4888-8888-888888888888', campaign: 'dsh_login_bonus',
amount: '5.00', currency: 'CNY', granted_at: new Date().toISOString(),
expires_at: new Date(Date.now() + 86_400_000).toISOString(), msg: '已赠送您 5.00 元 DSH 体验赠金。',
}] : [] } }))
response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { next_poll_after: 600, notifications: bonusOffered ? [{
id: '88888888-8888-4888-8888-888888888888', type: 'account.bonus_granted',
created_at: new Date().toISOString(), title: '赠金已到账', actions: [],
display_until: new Date(Date.now() + 86_400_000).toISOString(), body: '已赠送您 5.00 元 DSH 体验赠金。',
}] : [] } } }))
return
}
if (request.url === '/api/v0/users/ack_bonus_notified') {
if (request.url === '/api/v0/users/notifications/events') {
bonusAcks++
bonusOffered = false
response.setHeader('content-type', 'application/json')
response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: null } }))
response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { acked: true } } }))
return
}
if (request.url !== '/auth-api/v0/users/current' && request.url !== '/api/v0/users/get_user_summary') {
@@ -85,7 +85,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () =>
if (address === null || typeof address === 'string') throw new Error('fixture server address unavailable')
origin = `http://127.0.0.1:${address.port}`
const overlay = join(root, 'account.patch.yml')
await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n allowLoopbackHttp: true\n`)
await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n harnessOrigin: ${origin}\n allowLoopbackHttp: true\n`)
scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, extraOverlayPath: overlay })
await scaffold.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), async () => ({
kind: 'grant', payload: { version: 1, issuer: origin, token: 'onboarding-fixture-token' },
@@ -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,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 地址":
@@ -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"
+158 -4
View File
@@ -3,13 +3,13 @@
* workspace and the real dock, across docked and floating panes and a
* phone-width viewport. The package README owns the behavior asserted here.
*/
import { mkdir, writeFile } from 'node:fs/promises'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import { createLaunchEnvironmentSnapshot, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
import { launchWebScaffold, seedSession, watchConsole } from './scaffold.ts'
import { connectFreshWorkspace, saveFailureShot } from './support.ts'
/** Press at the centre of `from`, travel in steps, and release at `to`. */
@@ -290,11 +290,12 @@ it('browses workspace files in tabs that share one pane tree', async () => {
await page.setViewportSize({ width: 1680, height: 1000 })
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 460px !important; }' })
// The workspace command shows the pane's tree, moves the keyboard into it, and keeps the file.
// The workspace command shows the pane's tree, moves the keyboard to its search field, and keeps the file.
await input.focus()
await page.keyboard.press('Control+Alt+p')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => current.evaluate(node => node === document.activeElement)).toBe(true)
await expect.poll(() => navigator.locator('[data-files-search]').evaluate(node => node === document.activeElement)).toBe(true)
await expect.poll(() => current.textContent()).toBe('a.txt')
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await tabs.count()).toBe(tabCount + 1)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
@@ -537,3 +538,156 @@ it('moves a file between the docked column and a floating panel from the file me
await expect.poll(() => floatBody.evaluate(node => node.scrollTop)).toBe(600)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
})
it('searches the whole workspace, respects .gitignore on request, saves exclusion rules, restores the default list, and shows hidden entries', async () => {
const scaffold = await launchWebScaffold()
onTestFinished(() => scaffold.close())
// The scaffold's workspace is a private temporary directory that its close removes.
const root = scaffold.workspaceCwd
await mkdir(join(root, 'vendor', 'deep', 'nested'), { recursive: true })
await writeFile(join(root, 'vendor', 'deep', 'nested', 'widget-copy.ts'), 'export const copy = 3\n')
await mkdir(join(root, 'ignored'))
await writeFile(join(root, 'ignored', 'widget-ignored.ts'), 'export const ignored = 1\n')
await mkdir(join(root, '.git'), { recursive: true })
await writeFile(join(root, '.gitignore'), 'ignored/\n')
await writeFile(join(root, '.hidden-widget.txt'), 'hidden\n')
await writeFile(join(root, 'README.md'), '# Readme\n')
const seed = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links/session.v3.jsonl', import.meta.url))
await seedSession(scaffold, await readFile(seed, 'utf8'), 'file-search')
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const page = await browser.newPage({ locale: 'en-US', viewport: { width: 1680, height: 1000 } })
onTestFailed(() => saveFailureShot(page, 'web-e2e-file-search'))
const errors = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.locator('[role="treeitem"]').first().click()
await page.locator('[role="treeitem"]').nth(1).click()
await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).waitFor()
await page.locator('[data-sidebar-right-expand]').click()
const column = page.locator('[data-rightbar-col]')
await page.addStyleTag({ content: '[data-sidebar-right-panel] { width: 960px !important; }' })
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
const navigator = column.locator('[data-files-navigator]:visible')
const field = navigator.locator('[data-files-search]')
const body = navigator.locator('[data-files-body]')
const status = navigator.locator('[data-files-search-status]')
const eye = navigator.locator('[data-files-show-hidden]')
const row = (relative: string): Locator => body.locator(`[data-files-path="${root}/${relative}"]`)
await row('README.md').waitFor()
const searchToggle = column.locator('[data-files-search-toggle]')
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('false')
await expect.poll(() => field.count()).toBe(0)
await searchToggle.click()
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => field.evaluate(node => node === document.activeElement)).toBe(true)
// The eye starts closed: the tree leaves out entries whose name starts with `.`.
expect(await eye.getAttribute('aria-pressed')).toBe('false')
expect(await row('.hidden-widget.txt').count()).toBe(0)
// The search walks the whole workspace: a file three directories deep under one the tree never opened matches by name,
// ignoring case, with the match highlighted; the hidden file and the one `.gitignore` ignores are left out.
const deep = 'vendor/deep/nested/widget-copy.ts'
await field.fill('WIDGET')
await expect.poll(() => status.textContent()).toBe('Results: 1')
expect(await body.getAttribute('data-files-view')).toBe('search')
expect(await row(deep).locator('mark').textContent()).toBe('widget')
expect(await row('vendor/deep/nested').count()).toBe(1)
expect(await row('.hidden-widget.txt').count()).toBe(0)
expect(await row('ignored/widget-ignored.ts').count()).toBe(0)
expect(await row('README.md').count()).toBe(0)
expect(await body.locator('[data-files-row="search-incomplete"]').count()).toBe(0)
expect(await body.locator('[data-files-row="search-truncated"]').count()).toBe(0)
await searchToggle.click()
await expect.poll(() => searchToggle.getAttribute('aria-expanded')).toBe('false')
await expect.poll(() => field.count()).toBe(0)
await expect.poll(() => searchToggle.evaluate(node => node === document.activeElement)).toBe(true)
expect(await status.textContent()).toBe('Results: 1')
await row(deep).waitFor()
await searchToggle.click()
await expect.poll(() => field.inputValue()).toBe('WIDGET')
await expect.poll(() => field.evaluate(node => node === document.activeElement)).toBe(true)
// A query with `/` matches workspace-relative paths.
await field.fill('nested/widget')
await expect.poll(() => status.textContent()).toBe('Results: 1')
await row(deep).waitFor()
// Clearing the `.gitignore` choice in the settings searches again at once, and the ignored file matches.
await field.fill('widget')
await expect.poll(() => status.textContent()).toBe('Results: 1')
await navigator.locator('[data-files-search-settings-toggle]').click()
const gitignore = navigator.locator('[data-files-search-settings]').getByRole('checkbox', { name: 'Respect ignore files (.gitignore, etc.)', exact: true })
expect(await gitignore.isChecked()).toBe(true)
await gitignore.uncheck()
await page.keyboard.press('Escape')
await expect.poll(() => status.textContent()).toBe('Results: 2')
await row('ignored/widget-ignored.ts').waitFor()
await navigator.locator('[data-files-search-settings-toggle]').click()
await gitignore.check()
await page.keyboard.press('Escape')
await expect.poll(() => status.textContent()).toBe('Results: 1')
// Clearing the text gives the listed tree back, never expanded below the root.
await navigator.getByRole('button', { name: 'Clear search', exact: true }).click()
await expect.poll(() => body.getAttribute('data-files-view')).toBe('tree')
expect(await row('vendor/deep').count()).toBe(0)
expect(await field.inputValue()).toBe('')
expect(await status.count()).toBe(1)
expect(await status.textContent()).toBe('')
await row('README.md').waitFor()
// The magnifier opens the settings; an added path is saved when Escape closes the panel.
const trigger = navigator.locator('[data-files-search-settings-toggle]')
const settings = navigator.locator('[data-files-search-settings]')
const restore = settings.locator('[data-files-settings-restore]')
await trigger.click()
await settings.waitFor()
expect(await settings.getByText('Excluded files and directories', { exact: true }).count()).toBe(1)
for (const name of ['.DS_Store', 'Thumbs.db', '$RECYCLE.BIN', 'System Volume Information']) {
expect(await settings.locator(`[data-files-rule="${name}"]`).count()).toBe(1)
}
// The list is the default list, so there is nothing to restore.
expect(await restore.count()).toBe(0)
const add = settings.getByRole('textbox', { name: 'Add file or directory', exact: true })
await expect.poll(() => add.evaluate(node => node === document.activeElement)).toBe(true)
await add.fill('vendor')
await add.press('Enter')
await settings.locator('[data-files-rule="vendor"]').waitFor()
await page.keyboard.press('Escape')
await expect.poll(() => settings.count()).toBe(0)
expect(await trigger.evaluate(node => node === document.activeElement)).toBe(true)
const stored = (): Promise<string | null> => page.evaluate(() => localStorage.getItem('dsh.sidebar-files.workspace-search.v1'))
expect(await stored()).toContain('"vendor"')
// Exclusion rules narrow only the search; the tree still lists the directory.
await field.fill('widget')
await expect.poll(() => status.textContent()).toBe('Results: 0')
await field.press('Escape')
await expect.poll(() => body.getAttribute('data-files-view')).toBe('tree')
expect(await row('vendor').count()).toBe(1)
// Closing with the magnifier saves an unchecked rule.
await trigger.click()
const excludeVendor = settings.getByRole('checkbox', { name: 'Exclude vendor', exact: true })
await excludeVendor.uncheck()
await trigger.click()
await expect.poll(() => settings.count()).toBe(0)
await trigger.click()
expect(await excludeVendor.isChecked()).toBe(false)
// The restore control, shown while the list differs from the default list, resets it to that list.
await restore.click()
await expect.poll(() => settings.locator('[data-files-rule="vendor"]').count()).toBe(0)
expect(await restore.count()).toBe(0)
await page.keyboard.press('Escape')
await expect.poll(() => settings.count()).toBe(0)
// Back to the defaults, the workspace's stored entry goes.
expect(await stored()).not.toContain('"vendor"')
// The open eye shows hidden entries in the tree.
await eye.click()
await expect.poll(() => eye.getAttribute('aria-pressed')).toBe('true')
await row('.hidden-widget.txt').waitFor()
await eye.click()
await expect.poll(() => row('.hidden-widget.txt').count()).toBe(0)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
}, 120_000)
@@ -4,6 +4,7 @@
- id: deepseek-account
config:
platformOrigin: "{{origin}}"
harnessOrigin: "{{origin}}"
allowLoopbackHttp: true
# The scenario signs in from the account menu after initial setup.
- id: ui-settings-account
+6 -2
View File
@@ -1,13 +1,17 @@
# The bonus notice scenario points the shipped account provider at a loopback
# Platform double. The scaffold substitutes {{origin}} after the listener binds,
# so no port is ever committed here. No notice timing is overridden: every read
# comes from the product's own startup and settings-refresh paths.
# so no port is ever committed here. A long query interval isolates other notice
# interactions; the polling scenario advances the browser clock explicitly.
- id: deepseek-account
config:
platformOrigin: "{{origin}}"
harnessOrigin: "{{origin}}"
allowLoopbackHttp: true
# This scenario exercises the account launcher after initial setup.
- id: ui-settings-account
config:
step: done
completion: completed
- id: ui-account-notifications
config:
notificationPollIntervalMs: 7200000
+325 -33
View File
@@ -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,
id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false,
updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40),
baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED',
reviewThreads: { nodes: [{ isResolved: false }] },
reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] },
commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: {
pageInfo: { hasNextPage: true, endCursor: 'checks-100' },
nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)),
} } } }] },
},
9: {
number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED',
id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED',
isDraft: !state.ready, updatedAt: '2026-10-09T00:00:00Z', closedAt: state.mergedAt, author: { login: 'octo' },
headRefName: 'feat/merge', headRefOid: state.head ?? 'b'.repeat(40), baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE',
mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', reviewThreads: { nodes: [] },
headRefName: 'feat/merge', headRefOid: heads()[9], baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE',
mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED',
reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: {
pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')],
} } } }] },
},
}
if (query.includes('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}`,
])
@@ -1604,3 +1715,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([])
})
+4 -4
View File
@@ -53,9 +53,9 @@ describe('web e2e: goal bar clear convergence', () => {
const bar = page.locator('[data-goal-bar]')
await bar.waitFor({ timeout: 10_000 })
const pause = bar.getByRole('button', { name: 'Pause goal' })
await expect.poll(() => pause.count(), {
await expect.poll(() => pause.isEnabled(), {
timeout: 10_000,
}).toBe(1)
}).toBe(true)
await pause.hover()
const pauseTooltip = page.getByRole('tooltip', { name: 'Pause goal', exact: true })
await pauseTooltip.waitFor()
@@ -120,7 +120,7 @@ describe('web e2e: goal bar clear convergence', () => {
await input.fill('/goal retry after a blocker')
await input.press('Enter')
const bar = page.locator('[data-goal-bar]')
await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 })
await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true)
const agents = scaffold.ctx.agents.list()
expect(agents).toHaveLength(1)
@@ -140,7 +140,7 @@ describe('web e2e: goal bar clear convergence', () => {
await compareOrRefreshGolden(BLOCKED_EXPECTED, blocked, MODE)
await bar.getByRole('button', { name: 'Resume goal' }).click()
await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 })
await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true)
expect(scaffold.ctx.goals.get(agent)).toMatchObject({
phase: 'active', activation: 'armed', objective: 'retry with the edited plan',
})
+1 -1
View File
@@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized'))
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 })
await dialog.getByPlaceholder('•'.repeat('sk-e2e-minimax'.length), { exact: true }).waitFor({ timeout: 10_000 })
expect(await dialog.textContent()).not.toContain('API 密钥来源:')
expect(await dialog.textContent()).not.toMatch(/oauth/i)
await dialog.getByText('自定义设置').click()
@@ -33,6 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
let page: Page
let tripwire: ReturnType<typeof watchConsole>
const browserConsole: string[] = []
const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test`
beforeAll(async () => {
scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true })
@@ -86,7 +87,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE)
const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}`
await keyInput.fill(secret)
await credentialStep.getByRole('button', { name: '保存并继续' }).click()
await credentialStep.waitFor({ state: 'detached', timeout: 15_000 })
@@ -115,7 +115,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => configuredInput.getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe(`dsh_onboa${'•'.repeat(31)}test`)
const secondReloadWarnings = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
@@ -257,7 +257,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe(`dsh_onboa${'•'.repeat(31)}test`)
const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE)
await settings.getByRole('button', { name: '保存', exact: true }).click()
+8 -1
View File
@@ -551,7 +551,14 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser
await catalog.getByRole('treeitem', { name: /Continue preview verification/ }).waitFor()
await catalog.press('Escape')
await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
// Auto-prefetch may already have published the page, and a pointer click can
// land on whatever moved under it; activate the control only while it still
// offers a page, then wait for the oldest seeded row.
const historyEdge = page.locator('[data-chat-history]')
await historyEdge.getByRole('button').evaluate((button) => {
if (!(button instanceof HTMLButtonElement)) throw new Error('history control is not a button')
if (!button.disabled) button.click()
})
await page.getByText(SHOWCASE_OLDEST, { exact: true }).waitFor({ timeout: 15_000 })
await requestLazyChunk(page, site, manifest)
+119
View File
@@ -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([])
})
+5
View File
@@ -371,6 +371,11 @@ describe('web e2e: seeded history renders through cold resume', () => {
payload: { args: { request: { maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } } } },
})
await expect.poll(() => page.getByText(PROMPT, { exact: true }).count(), { timeout: 10_000 }).toBe(1)
const history = page.locator('[data-chat-history]')
await expect.poll(() => history.getAttribute('data-chat-history'), { timeout: 10_000 }).toBe('idle')
await expect.poll(() => history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled(), {
timeout: 10_000,
}).toBe(true)
await expect.poll(() => page.getByText('compact', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
await expect.poll(() => page.getByText(/^Compacted \d+ history items \(~\d+ tokens\)$/).count(), {
timeout: 10_000,
+1 -1
View File
@@ -149,7 +149,7 @@ it('shares settings card materials and control sizes in both palettes', async ()
bonusWallets: [{ currency: 'CNY', balance: '12.00' }],
}),
vi.spyOn(account, 'watch').mockImplementation(async function* (signal) {
yield state
yield { type: 'snapshot', state }
if (signal.aborted) return
await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
}),
@@ -479,7 +479,6 @@ const EXPECTED_TOOLS = [
'edit',
'exit_plan_mode',
'get_goal',
'interrupt_agent',
'job_kill',
'job_list',
'job_output',
+3 -2
View File
@@ -120,8 +120,9 @@ it.each([
await selectDraft()
await deliverPrimary('KeyP')
expect(await files.count()).toBe(1)
expect(await panel.locator('[data-dockkit-pane]').evaluate(pane => document.activeElement === pane)).toBe(true)
expect(await page.evaluate(() => document.getSelection()?.toString())).toBe('Desktop')
// Once the files page is shown, the shortcut opens its search bar and the search field takes the keyboard.
await expect.poll(() => panel.locator('[data-files-search-toggle]').getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => panel.locator('[data-files-search]').evaluate(input => document.activeElement === input)).toBe(true)
await composer.click()
const pane = panel.locator('[data-dockkit-pane]')
await pane.click({ position: { x: 20, y: 2 } })
+2 -1
View File
@@ -183,7 +183,8 @@ describe.skipIf(process.platform === 'win32')('Web sidebar shortcuts', () => {
expect(await paneAppearance()).toEqual([plainPane])
await page.keyboard.press(`${primary}+Shift+,`)
expect(await panel.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }).count()).toBe(1)
expect(await panel.locator('[data-dockkit-pane]').evaluate(pane => document.activeElement === pane)).toBe(true)
await expect.poll(() => panel.locator('[data-files-search-toggle]').getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => panel.locator('[data-files-search]').evaluate(input => document.activeElement === input)).toBe(true)
// Once the reveal's glow has ended, the focused pane draws nothing of its own. file-browser.e2e.ts and the
// seat spec own the glow itself, so this waits for no marker rather than requiring the transient one.
await expect.poll(() => panel.locator('[data-dockkit-pane][data-sidebar-right-flash]').count()).toBe(0)
@@ -182,6 +182,10 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => {
await files.locator('[data-files-row="empty"]').waitFor()
// The directory opener sits in the files page's header, above the tree.
const opener = files.locator('[data-open-target="directory"]')
const tools = files.locator('[data-files-reload], [data-files-search-toggle], [data-open-target="directory"] button')
expect((await tools.evaluateAll(elements => elements.map(element => element.hasAttribute('data-files-reload')
? 'reload' : element.hasAttribute('data-files-search-toggle') ? 'search' : 'open'))).slice(0, 3))
.toEqual(['reload', 'search', 'open'])
await opener.getByRole('button', { name: 'Open in VS Code', exact: true }).click()
await expect.poll(() => launched).toEqual([
{ app: 'vscode', path: workspace.path }, { app: 'vscode', path: workspace.path },
+1 -1
View File
@@ -519,7 +519,7 @@ describe('web e2e: sidebar search alignment and row action targets', () => {
}),
vi.spyOn(account, 'getBalance').mockResolvedValue({ status: 'ready', value: [], bonusWallets: [] }),
vi.spyOn(account, 'watch').mockImplementation(async function* (signal) {
yield state
yield { type: 'snapshot', state }
if (signal.aborted) return
await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
}),
@@ -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
+97 -18
View File
@@ -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()
+10
View File
@@ -62,6 +62,16 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => {
expect(await row.locator('[class*="ioCard"]').count()).toBe(0)
expect(await row.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1)
}
const agentRow = page.locator('[data-tool="list_agents"]').getByRole('listitem').first()
expect(await agentRow.getByRole('button').count()).toBe(0)
expect(await agentRow.locator('svg').count()).toBe(0)
// Read both positions in one browser task so scrolling cannot move the viewport between measurements.
const agentLayout = await agentRow.evaluate((element) => {
const description = element.querySelector('[class*="heading"] > span')!.getBoundingClientRect()
const name = element.querySelector('[class*="subtitle"]')!.getBoundingClientRect()
return { descriptionBottom: description.bottom, nameTop: name.top }
})
expect(agentLayout.descriptionBottom).toBeLessThanOrEqual(agentLayout.nameTop)
const changedTodos = page.locator('[data-tool="todo_write"]').nth(1)
await changedTodos.getByText('1 added · 1 updated · 1 removed', { exact: true }).waitFor()
for (const summary of await page.locator('[data-tool] details > summary').all()) await summary.click()
+24 -1
View File
@@ -155,7 +155,30 @@ describe('web e2e: workspace recency', () => {
const blank = page.getByRole('treeitem').filter({ has: page.getByText('New Session', { exact: true }) })
await expect.poll(() => blank.getAttribute('draggable')).toBe('false')
const blankWarningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
const selectedRowKey = await blank.getAttribute('data-row-key')
expect(selectedRowKey).not.toBeNull()
const restoredRowKeys = await page.locator('[role="treeitem"]:not([aria-expanded])')
.evaluateAll(rows => rows.map(row => row.getAttribute('data-row-key')))
expect(restoredRowKeys).toHaveLength(4)
const workspaceRow = page.getByRole('treeitem').filter({ has: page.getByText(workspaceTitle, { exact: true }) })
// Document load does not restore the Workspace stream or the selected blank Session. Hold the baseline to exercise that gap.
const releaseHeldWorkspace = (): void => { releaseWorkspace?.() }
releaseWorkspace = undefined
holdWorkspace = true
try {
await page.reload({ waitUntil: 'load' })
await expect.poll(() => releaseWorkspace !== undefined, { timeout: 30_000 }).toBe(true)
expect(await workspaceRow.count()).toBe(0)
} finally {
holdWorkspace = false
releaseHeldWorkspace()
}
await workspaceRow.waitFor({ state: 'visible', timeout: 30_000 })
for (const rowKey of restoredRowKeys) {
await page.locator(`[data-row-key="${rowKey}"]`).waitFor({ state: 'visible', timeout: 30_000 })
}
await page.locator(`[data-row-key="${selectedRowKey}"][aria-selected="true"]`)
.waitFor({ state: 'visible', timeout: 30_000 })
await expect.poll(titles).toEqual(['New Session', ...TITLES])
acknowledgeReloadConnectionLoss(tripwire, blankWarningStart)
await pick('Last updated')
+1
View File
@@ -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",
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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).
+1 -1
View File
@@ -76,7 +76,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共
Subagent Activation 拥有运行时树成员关系。
AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;卸载在 teardown 期间保留所需资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。
AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭时即使队列清理失败,也会取消并等待当前工作,再释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。
[事件生产者与消费者](event-producer-consumer.zh.md)。
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: bc25cf8be90065dc
zh: ae0def4872a9cdd9
en: b76743a3ff14d2f4
zh: 82431aa3ded14a89
+1 -5
View File
@@ -142,8 +142,6 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount<br/>DeepSeek account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
pkg_api_account_controller["api-account-controller"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -360,7 +358,6 @@ flowchart LR
pkg_credentials_local --> svc_credentials
pkg_cua --> svc_cuaAccess
pkg_deepseek_account --> svc_deepseekAccount
pkg_deepseek_account_platform --> svc_deepseekAccount
pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions
pkg_experimental_api_speech_to_text --> svc_speechController
pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse
@@ -518,7 +515,6 @@ flowchart LR
svc_credentials --> pkg_llm_deepseek
svc_credentials --> pkg_llm_pi_ai
svc_cuaAccess --> pkg_cua
svc_deepseekAccount --> pkg_api_account_controller
svc_deepseekAccount --> pkg_llm_deepseek
svc_deepseekLlmApiExtensions --> pkg_llm_deepseek
svc_directoryPicker --> pkg_api_workspace_controller
@@ -704,7 +700,7 @@ flowchart LR
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | Owns the default-off settings namespace that Agent-scoped delegation tools sample when composing a new top-level Session. |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage. |
| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. |
| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The Host owns browser authorization and local credentials; UI consumers receive state without tokens. |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol. |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | Accepts selected Desktop events, enriches available login identity, and observes live compaction under the live Host collection policy. |
| `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | Product analytics and Session feedback adapters create independent reporting channels through one injected service. |
+1 -5
View File
@@ -144,8 +144,6 @@ flowchart LR
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
svc_deepseekAccount["ctx.deepseekAccount<br/>DeepSeek account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
pkg_api_account_controller["api-account-controller"]
pkg_authorization["authorization"]
svc_authorization["ctx.authorization<br/>Authorization flow registry"]
pkg_client_product_analytics["client-product-analytics"]
@@ -362,7 +360,6 @@ flowchart LR
pkg_credentials_local --> svc_credentials
pkg_cua --> svc_cuaAccess
pkg_deepseek_account --> svc_deepseekAccount
pkg_deepseek_account_platform --> svc_deepseekAccount
pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions
pkg_experimental_api_speech_to_text --> svc_speechController
pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse
@@ -520,7 +517,6 @@ flowchart LR
svc_credentials --> pkg_llm_deepseek
svc_credentials --> pkg_llm_pi_ai
svc_cuaAccess --> pkg_cua
svc_deepseekAccount --> pkg_api_account_controller
svc_deepseekAccount --> pkg_llm_deepseek
svc_deepseekLlmApiExtensions --> pkg_llm_deepseek
svc_directoryPicker --> pkg_api_workspace_controller
@@ -706,7 +702,7 @@ flowchart LR
| `ctx.settings` | `core` | [`settings`](../packages/settings/settings) | - | [`api-settings-controller`](../packages/api/settings-controller) | - | Forms project volatile Config fields from active profile entries and delegate validated edits to config-editor. Plugins consume their own Config references. |
| `ctx.subagentModelSelection` | `core` | [`tool-subagent`](../packages/subagent/tool-subagent) | - | [`tool-subagent`](../packages/subagent/tool-subagent) | - | 拥有默认关闭的设置命名空间;Agent 作用域的委派工具会在组合新顶层 Session 时读取它。 |
| `ctx.credentials` | `seam` | [`credentials`](../packages/credentials/credentials) | [`credentials-local`](../packages/credentials/credentials-local) | [`api-settings-controller`](../packages/api/settings-controller), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | 配置携带对机密信息的引用;提供方拥有实际值。消费方按操作解析,因此轮换后的凭据会在紧接着的下一次请求中生效;settings controller 提供不含实际值的视图和只写存储。 |
| `ctx.deepseekAccount` | `seam` | [`deepseek-account`](../packages/credentials/deepseek-account) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | [`api-account-controller`](../packages/api/account-controller), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 |
| `ctx.deepseekAccount` | `service` | [`deepseek-account`](../packages/credentials/deepseek-account) | - | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Host 负责浏览器授权和本地凭证;UI 使用方只接收不含 token 的状态。 |
| `ctx.authorization` | `seam` | [`authorization`](../packages/credentials/authorization) | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | - | flow 由知道如何取得某份凭据的插件注册,并以其写入的记录为键;seam 拥有这段对话与"每个键同时只跑一次尝试"的生命周期,而非协议本身。 |
| `ctx.productAnalytics` | `service` | [`client-product-analytics`](../packages/client/product-analytics) | - | - | - | 根据 Host 动态采集策略接收指定桌面事件、补充可用登录身份并监听实时压缩。 |
| `ctx.otel` | `service` | [`otel`](../packages/telemetry/otel) | - | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel), [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | - | 产品埋点和 Session 反馈适配器通过同一个注入服务创建独立上报通道。 |
+68 -19
View File
@@ -367,10 +367,10 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page or one listing. */
/** Deployment caps on one page, one listing, or one search. */
export interface Config {
/**
* Inclusive byte cap on one page's text and on one byte window.
@@ -386,6 +386,22 @@ export interface Config {
readonly maxLines: number
/** Cap on returned directory entries; the rest is dropped and reported cut. */
readonly maxEntries: number
/** Budgets on one search's matches, listed files, deadline and ripgrep process. */
readonly search: SearchLimits
}
/** Deployment budgets on one search's results, listed files and process. */
export interface SearchLimits {
/** Cap on returned matches; additional matches report truncation after the bounded scan. */
readonly maxResults: number
/** Cap on files considered from rg output; an extra file terminates rg and reports the search incomplete. */
readonly maxEntries: number
/** Search process termination grace in milliseconds. */
readonly graceMs: number
/** Search deadline in milliseconds; expiry rejects rather than returning partial results. */
readonly timeoutMs: number
/** Byte cap on retained search-process stderr diagnostics. */
readonly stderrMaxBytes: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-api-workspace-files -->
@@ -578,6 +594,22 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<a id="deepseek-aidsh-client-ui-account-notifications"></a>
## `@deepseek-ai/dsh-client-ui-account-notifications`
- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts)
```ts config-catalog
/** Initial polling interval before the server supplies its next delay. */
export interface Config {
/** Initial query delay in milliseconds, replaced by each successful server response. */
notificationPollIntervalMs: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-plugin-manager -->
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
@@ -625,16 +657,12 @@ export interface Config extends ContactConfig {
developerTools: Volatile<boolean>
}
/** Questionnaire destination and bonus notice timings shared by Host and Client. */
/** Questionnaire destination shared by Host and Client. */
export interface ContactConfig {
/** HTTPS questionnaire URL; override for a test form. */
contactFormUrl: string
/** Questionnaire source option; empty until Harness is supported by the form. */
contactSource: string
/** First delay before retrying a failed bonus acknowledgement. */
bonusAckRetryDelayMs: number
/** Ceiling for the acknowledgement retry backoff. */
bonusAckRetryMaxDelayMs: number
}
/** Persisted steps; a native top-up page leaves the durable step at credit. */
@@ -858,19 +886,21 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-credentials-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<a id="deepseek-aidsh-deepseek-account-platform"></a>
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<a id="deepseek-aidsh-deepseek-account"></a>
## `@deepseek-ai/dsh-deepseek-account-platform`
## `@deepseek-ai/dsh-deepseek-account`
- `inject`: `credentials` · `authorization`
- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts)
- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts)
```ts config-catalog
/** Deployment-specific platform and request deadlines. */
export interface Config {
/** Platform origin serving auth-api and browser pages. */
platformOrigin?: string
/** Harness API origin for account notifications. */
harnessOrigin?: string
/** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */
desktopPlatform?: 'darwin' | 'win32' | null
/** Optional frontend deployment selector for embedded Usage and Top-up pages. */
@@ -881,9 +911,11 @@ export interface Config {
allowLoopbackHttp?: boolean
/** Map authorization and completion pages to platformOrigin for private development proxies. */
rewriteBrowserOrigin?: boolean
/** Host-only headers sent exclusively to platformOrigin; account authorization cannot be overridden. */
/** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */
requestHeaders?: Record<string, string>
/** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */
/** Overrides for profile, balance, notification and embedded Platform requests;
* Cookie pairs merge by name. Logout retains requestHeaders.
*/
accountRequestHeaders?: Record<string, string>
/** Deadline for each platform HTTP request. */
requestTimeoutMs?: number
@@ -897,7 +929,7 @@ export interface Config {
attemptTimeoutMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-experimental-api-speech-to-text -->
<a id="deepseek-aidsh-experimental-api-speech-to-text"></a>
@@ -1049,7 +1081,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1077,6 +1109,18 @@ export interface Config {
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
/** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */
maxCommits?: number
/**
* Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before
* them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both.
*/
testPaths?: string[]
/**
* Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after
* `testPaths` and before the built-in rules.
*/
interfacePaths?: string[]
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1112,13 +1156,15 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1142,7 +1188,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1178,6 +1224,10 @@ export interface Config {
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
maxCommits?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -4990,7 +5040,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| --- | --- | --- |
| `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) |
| `@deepseek-ai/dsh-agent` | `sessionProjections` | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) |
| `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) |
| `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) |
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
@@ -5119,7 +5168,6 @@ Abstract service classes — a deployment loads a concrete implementation packag
| `@deepseek-ai/dsh-attachment` | `AttachmentStore` | — | [`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts) |
| `@deepseek-ai/dsh-compaction` | `CompactionEngine` | — | [`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts) |
| `@deepseek-ai/dsh-credentials` | `CredentialProvider` | — | [`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts) |
| `@deepseek-ai/dsh-deepseek-account` | `DeepSeekAccount` | — | [`packages/credentials/deepseek-account/src/index.ts`](../packages/credentials/deepseek-account/src/index.ts) |
| `@deepseek-ai/dsh-file-reference` | `FileReferenceService` | — | [`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts) |
| `@deepseek-ai/dsh-fs` | `FileSystem` | — | [`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts) |
| `@deepseek-ai/dsh-host-directory-picker` | `DirectoryPicker` | — | [`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts) |
@@ -5213,6 +5261,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them.
| `@deepseek-ai/dsh-util-code-language` | — | [`packages/util/code-language/src/index.ts`](../packages/util/code-language/src/index.ts) |
| `@deepseek-ai/dsh-util-crypto` | — | [`packages/util/crypto/src/index.ts`](../packages/util/crypto/src/index.ts) |
| `@deepseek-ai/dsh-util-file-drag` | — | [`packages/util/file-drag/src/index.ts`](../packages/util/file-drag/src/index.ts) |
| `@deepseek-ai/dsh-util-ripgrep` | — | [`packages/util/ripgrep/src/index.ts`](../packages/util/ripgrep/src/index.ts) |
| `@deepseek-ai/dsh-util-time` | — | [`packages/util/time/src/index.ts`](../packages/util/time/src/index.ts) |
| `@deepseek-ai/dsh-util-values` | — | [`packages/util/values/src/index.ts`](../packages/util/values/src/index.ts) |
| `@deepseek-ai/dsh-util-workspace-path` | — | [`packages/util/workspace-path/src/index.ts`](../packages/util/workspace-path/src/index.ts) |
+68 -19
View File
@@ -369,10 +369,10 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page or one listing. */
/** Deployment caps on one page, one listing, or one search. */
export interface Config {
/**
* Inclusive byte cap on one page's text and on one byte window.
@@ -388,6 +388,22 @@ export interface Config {
readonly maxLines: number
/** Cap on returned directory entries; the rest is dropped and reported cut. */
readonly maxEntries: number
/** Budgets on one search's matches, listed files, deadline and ripgrep process. */
readonly search: SearchLimits
}
/** Deployment budgets on one search's results, listed files and process. */
export interface SearchLimits {
/** Cap on returned matches; additional matches report truncation after the bounded scan. */
readonly maxResults: number
/** Cap on files considered from rg output; an extra file terminates rg and reports the search incomplete. */
readonly maxEntries: number
/** Search process termination grace in milliseconds. */
readonly graceMs: number
/** Search deadline in milliseconds; expiry rejects rather than returning partial results. */
readonly timeoutMs: number
/** Byte cap on retained search-process stderr diagnostics. */
readonly stderrMaxBytes: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-api-workspace-files -->
@@ -580,6 +596,22 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<a id="deepseek-aidsh-client-ui-account-notifications"></a>
## `@deepseek-ai/dsh-client-ui-account-notifications`
- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts)
```ts config-catalog
/** Initial polling interval before the server supplies its next delay. */
export interface Config {
/** Initial query delay in milliseconds, replaced by each successful server response. */
notificationPollIntervalMs: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-ui-account-notifications -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-ui-plugin-manager -->
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
@@ -627,16 +659,12 @@ export interface Config extends ContactConfig {
developerTools: Volatile<boolean>
}
/** Questionnaire destination and bonus notice timings shared by Host and Client. */
/** Questionnaire destination shared by Host and Client. */
export interface ContactConfig {
/** HTTPS questionnaire URL; override for a test form. */
contactFormUrl: string
/** Questionnaire source option; empty until Harness is supported by the form. */
contactSource: string
/** First delay before retrying a failed bonus acknowledgement. */
bonusAckRetryDelayMs: number
/** Ceiling for the acknowledgement retry backoff. */
bonusAckRetryMaxDelayMs: number
}
/** Persisted steps; a native top-up page leaves the durable step at credit. */
@@ -860,19 +888,21 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-credentials-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<a id="deepseek-aidsh-deepseek-account-platform"></a>
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<a id="deepseek-aidsh-deepseek-account"></a>
## `@deepseek-ai/dsh-deepseek-account-platform`
## `@deepseek-ai/dsh-deepseek-account`
- `inject`: `credentials` · `authorization`
- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts)
- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts)
```ts config-catalog
/** Deployment-specific platform and request deadlines. */
export interface Config {
/** Platform origin serving auth-api and browser pages. */
platformOrigin?: string
/** Harness API origin for account notifications. */
harnessOrigin?: string
/** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */
desktopPlatform?: 'darwin' | 'win32' | null
/** Optional frontend deployment selector for embedded Usage and Top-up pages. */
@@ -883,9 +913,11 @@ export interface Config {
allowLoopbackHttp?: boolean
/** Map authorization and completion pages to platformOrigin for private development proxies. */
rewriteBrowserOrigin?: boolean
/** Host-only headers sent exclusively to platformOrigin; account authorization cannot be overridden. */
/** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */
requestHeaders?: Record<string, string>
/** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */
/** Overrides for profile, balance, notification and embedded Platform requests;
* Cookie pairs merge by name. Logout retains requestHeaders.
*/
accountRequestHeaders?: Record<string, string>
/** Deadline for each platform HTTP request. */
requestTimeoutMs?: number
@@ -899,7 +931,7 @@ export interface Config {
attemptTimeoutMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account-platform -->
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-deepseek-account -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-experimental-api-speech-to-text -->
<a id="deepseek-aidsh-experimental-api-speech-to-text"></a>
@@ -1051,7 +1083,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1079,6 +1111,18 @@ export interface Config {
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
/** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */
maxCommits?: number
/**
* Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before
* them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both.
*/
testPaths?: string[]
/**
* Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after
* `testPaths` and before the built-in rules.
*/
interfacePaths?: string[]
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1114,13 +1158,15 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
/** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1144,7 +1190,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1180,6 +1226,10 @@ export interface Config {
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
maxCommits?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -4992,7 +5042,6 @@ export interface Config {
| --- | --- | --- |
| `@deepseek-ai/dsh-acp-app` | `cmdlineArgs` | [`packages/bundle/acp-app/src/index.ts`](../packages/bundle/acp-app/src/index.ts) |
| `@deepseek-ai/dsh-agent` | `sessionProjections` | [`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts) |
| `@deepseek-ai/dsh-api-account-controller` | `deepseekAccount` · `agents` | [`packages/api/account-controller/src/index.ts`](../packages/api/account-controller/src/index.ts) |
| `@deepseek-ai/dsh-api-remote-access` | — | [`packages/api/remote-access/src/index.ts`](../packages/api/remote-access/src/index.ts) |
| `@deepseek-ai/dsh-api-remotes` | `typertGateway` | [`packages/api/remotes/src/index.ts`](../packages/api/remotes/src/index.ts) |
| `@deepseek-ai/dsh-authorization` | `credentials` | [`packages/credentials/authorization/src/index.ts`](../packages/credentials/authorization/src/index.ts) |
@@ -5121,7 +5170,6 @@ export interface Config {
| `@deepseek-ai/dsh-attachment` | `AttachmentStore` | — | [`packages/attachment/attachment/src/index.ts`](../packages/attachment/attachment/src/index.ts) |
| `@deepseek-ai/dsh-compaction` | `CompactionEngine` | — | [`packages/compaction/compaction/src/index.ts`](../packages/compaction/compaction/src/index.ts) |
| `@deepseek-ai/dsh-credentials` | `CredentialProvider` | — | [`packages/credentials/credentials/src/index.ts`](../packages/credentials/credentials/src/index.ts) |
| `@deepseek-ai/dsh-deepseek-account` | `DeepSeekAccount` | — | [`packages/credentials/deepseek-account/src/index.ts`](../packages/credentials/deepseek-account/src/index.ts) |
| `@deepseek-ai/dsh-file-reference` | `FileReferenceService` | — | [`packages/context/file-reference/src/index.ts`](../packages/context/file-reference/src/index.ts) |
| `@deepseek-ai/dsh-fs` | `FileSystem` | — | [`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts) |
| `@deepseek-ai/dsh-host-directory-picker` | `DirectoryPicker` | — | [`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts) |
@@ -5215,6 +5263,7 @@ export interface Config {
| `@deepseek-ai/dsh-util-code-language` | — | [`packages/util/code-language/src/index.ts`](../packages/util/code-language/src/index.ts) |
| `@deepseek-ai/dsh-util-crypto` | — | [`packages/util/crypto/src/index.ts`](../packages/util/crypto/src/index.ts) |
| `@deepseek-ai/dsh-util-file-drag` | — | [`packages/util/file-drag/src/index.ts`](../packages/util/file-drag/src/index.ts) |
| `@deepseek-ai/dsh-util-ripgrep` | — | [`packages/util/ripgrep/src/index.ts`](../packages/util/ripgrep/src/index.ts) |
| `@deepseek-ai/dsh-util-time` | — | [`packages/util/time/src/index.ts`](../packages/util/time/src/index.ts) |
| `@deepseek-ai/dsh-util-values` | — | [`packages/util/values/src/index.ts`](../packages/util/values/src/index.ts) |
| `@deepseek-ai/dsh-util-workspace-path` | — | [`packages/util/workspace-path/src/index.ts`](../packages/util/workspace-path/src/index.ts) |
@@ -12,5 +12,5 @@
en: 86422ee69c63f339
zh: 4a5e8d6f5d9a6ae3
/remote-and-api-rules/packages-api-carries-generic-orchestration-only:
en: 12a964b9c04fccf9
zh: cf804f8044535727
en: b9991b7ffcbf9029
zh: bb7ef15064e922be
+1 -1
View File
@@ -84,7 +84,7 @@ The hand-written copy drifts from the generated type without failing a build, th
The packages under `packages/api` — the controllers, `gateway`, and `remotes` — carry transport, call shape, Session lifecycle, and other generic orchestration. A business branch never aggregates there: a decision that depends on concrete business state, handling bound to one feature, or a per-feature filter belongs in its own package or module and reaches this layer as projected data or through a registration surface. The criterion is where the logic belongs, not where the file sits, so a branch that only makes sense for one feature is a defect even when the file holding it is generic.
- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds nine packages — `account-controller`, `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3, account-controller 2).
- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds eight packages — `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3).
- Not covered: generic Session lifecycle, transport, and storage abstraction stay — `gateway` dispatch, `remotes` selection, and shared session-list and catalog reads are infrastructure, not business logic. [Business ownership](../api-gateway.md#business-ownership) states the same split from the Gateway side.
- Exception: none by default. Adding a business branch here needs an independent-package review, and that review answers why the logic cannot live in the package that owns the feature.
- Fix: move the decision into the owning package, publish its result as projected data or register it on a registry this layer already injects, and leave only the orchestration that reads it.
+1 -1
View File
@@ -84,7 +84,7 @@ type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written
`packages/api` 下的包——各 controller、`gateway`、`remotes`——承载传输、调用形态、Session 生命周期等通用编排。业务分支绝不在其中聚合:依赖具体业务状态的判断、与单个功能绑定的处理、逐功能的过滤,都归独立包或模块,并作为投影数据或经注册面接入本层。判据是逻辑的归属,而不是文件的位置,所以只对一个功能成立的业务分支即使放在通用文件里也是缺陷。
- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 9 个包——`account-controller`、`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3、account-controller 2)。
- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 8 个包——`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3)。
- 不覆盖:通用 Session 生命周期、传输与存储抽象留下——`gateway` 的分发、`remotes` 的选择、共享的会话列表与目录读取属于基础设施,不是业务逻辑。[业务所有权](../api-gateway.zh.md#business-ownership)从 Gateway 一侧给出同一个划分。
- 例外:默认无例外。在此新增业务分支须走独立包评审,评审要回答这些逻辑为什么不能住在拥有该功能的包里。
- 修法:把判断移进归属包,将其结果作为投影数据发布、或注册到本层本就注入的注册表上,这里只留下读取它的编排。
+17 -17
View File
@@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
@@ -40,11 +40,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
@@ -84,7 +84,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` |
| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
+17 -17
View File
@@ -14,17 +14,17 @@
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
@@ -42,11 +42,11 @@
| `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:100`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:88`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:110`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:106`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account), `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
@@ -86,7 +86,7 @@
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` |
| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
+10 -12
View File
@@ -27,6 +27,7 @@ flowchart TD
pkg_util_code_language["util-code-language"]
pkg_util_crypto["util-crypto"]
pkg_util_file_drag["util-file-drag"]
pkg_util_ripgrep["util-ripgrep"]
pkg_util_time["util-time"]
pkg_util_values["util-values"]
pkg_util_workspace_path["util-workspace-path"]
@@ -115,7 +116,6 @@ flowchart TD
pkg_acp["acp"]
end
subgraph group_api["packages/api"]
pkg_api_account_controller["api-account-controller"]
pkg_api_gateway["api-gateway"]
pkg_api_job_controller["api-job-controller"]
pkg_api_remote_access["api-remote-access"]
@@ -159,6 +159,7 @@ flowchart TD
pkg_client_resources["client-resources"]
pkg_client_shortcuts["client-shortcuts"]
pkg_client_store["client-store"]
pkg_client_ui_account_notifications["client-ui-account-notifications"]
pkg_client_ui_agent_preset["client-ui-agent-preset"]
pkg_client_ui_agent_team["client-ui-agent-team"]
pkg_client_ui_approval["client-ui-approval"]
@@ -245,7 +246,6 @@ flowchart TD
pkg_credentials["credentials"]
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
end
subgraph group_deliverables["packages/deliverables"]
pkg_deliverable_file_references["deliverable-file-references"]
@@ -508,6 +508,7 @@ flowchart TD
pkg_subprocess --> pkg_http_proxy
pkg_remote_mock --> pkg_typert_protocol
pkg_typert_loader --> pkg_typert_registry
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_llm
@@ -694,8 +695,12 @@ flowchart TD
pkg_tmux_context --> pkg_session_projection
pkg_tmux_context --> pkg_shell
pkg_deepseek_account --> pkg_agent
pkg_deepseek_account --> pkg_authorization
pkg_deepseek_account --> pkg_brand
pkg_deepseek_account --> pkg_credentials
pkg_deepseek_account --> pkg_host_webserver
pkg_deepseek_account --> pkg_llm
pkg_deepseek_account --> pkg_typert_protocol
pkg_deepseek_account --> pkg_util_values
pkg_commands --> pkg_agent
pkg_commands --> pkg_attachment
@@ -775,17 +780,10 @@ flowchart TD
pkg_web_search_deepseek --> pkg_llm_deepseek
pkg_web_search_deepseek --> pkg_session
pkg_web_search_deepseek --> pkg_web
pkg_api_account_controller --> pkg_agent
pkg_api_account_controller --> pkg_deepseek_account
pkg_api_account_controller --> pkg_typert_protocol
pkg_compaction --> pkg_brand
pkg_compaction --> pkg_commands
pkg_compaction --> pkg_llm
pkg_compaction --> pkg_session
pkg_deepseek_account_platform --> pkg_authorization
pkg_deepseek_account_platform --> pkg_credentials
pkg_deepseek_account_platform --> pkg_deepseek_account
pkg_deepseek_account_platform --> pkg_host_webserver
pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime
pkg_experimental_ptc_runtime_python --> pkg_sandbox
pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy
@@ -1582,6 +1580,7 @@ flowchart TD
| [`client-resources`](../packages/client/resources) | `client` | — |
| [`client-shortcuts`](../packages/client/shortcuts) | `client` | — |
| [`client-store`](../packages/client/store) | `client` | — |
| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — |
| [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — |
| [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — |
| [`client-ui-approval`](../packages/client/ui-approval) | `client` | — |
@@ -1705,6 +1704,7 @@ flowchart TD
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) |
| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) |
| [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
@@ -1772,7 +1772,7 @@ flowchart TD
| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) |
| [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) |
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) |
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) |
@@ -1789,9 +1789,7 @@ flowchart TD
| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) |
| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) |
| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) |
| [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) |
| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
+10 -12
View File
@@ -29,6 +29,7 @@ flowchart TD
pkg_util_code_language["util-code-language"]
pkg_util_crypto["util-crypto"]
pkg_util_file_drag["util-file-drag"]
pkg_util_ripgrep["util-ripgrep"]
pkg_util_time["util-time"]
pkg_util_values["util-values"]
pkg_util_workspace_path["util-workspace-path"]
@@ -117,7 +118,6 @@ flowchart TD
pkg_acp["acp"]
end
subgraph group_api["packages/api"]
pkg_api_account_controller["api-account-controller"]
pkg_api_gateway["api-gateway"]
pkg_api_job_controller["api-job-controller"]
pkg_api_remote_access["api-remote-access"]
@@ -161,6 +161,7 @@ flowchart TD
pkg_client_resources["client-resources"]
pkg_client_shortcuts["client-shortcuts"]
pkg_client_store["client-store"]
pkg_client_ui_account_notifications["client-ui-account-notifications"]
pkg_client_ui_agent_preset["client-ui-agent-preset"]
pkg_client_ui_agent_team["client-ui-agent-team"]
pkg_client_ui_approval["client-ui-approval"]
@@ -247,7 +248,6 @@ flowchart TD
pkg_credentials["credentials"]
pkg_credentials_local["credentials-local"]
pkg_deepseek_account["deepseek-account"]
pkg_deepseek_account_platform["deepseek-account-platform"]
end
subgraph group_deliverables["packages/deliverables"]
pkg_deliverable_file_references["deliverable-file-references"]
@@ -510,6 +510,7 @@ flowchart TD
pkg_subprocess --> pkg_http_proxy
pkg_remote_mock --> pkg_typert_protocol
pkg_typert_loader --> pkg_typert_registry
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_llm
@@ -696,8 +697,12 @@ flowchart TD
pkg_tmux_context --> pkg_session_projection
pkg_tmux_context --> pkg_shell
pkg_deepseek_account --> pkg_agent
pkg_deepseek_account --> pkg_authorization
pkg_deepseek_account --> pkg_brand
pkg_deepseek_account --> pkg_credentials
pkg_deepseek_account --> pkg_host_webserver
pkg_deepseek_account --> pkg_llm
pkg_deepseek_account --> pkg_typert_protocol
pkg_deepseek_account --> pkg_util_values
pkg_commands --> pkg_agent
pkg_commands --> pkg_attachment
@@ -777,17 +782,10 @@ flowchart TD
pkg_web_search_deepseek --> pkg_llm_deepseek
pkg_web_search_deepseek --> pkg_session
pkg_web_search_deepseek --> pkg_web
pkg_api_account_controller --> pkg_agent
pkg_api_account_controller --> pkg_deepseek_account
pkg_api_account_controller --> pkg_typert_protocol
pkg_compaction --> pkg_brand
pkg_compaction --> pkg_commands
pkg_compaction --> pkg_llm
pkg_compaction --> pkg_session
pkg_deepseek_account_platform --> pkg_authorization
pkg_deepseek_account_platform --> pkg_credentials
pkg_deepseek_account_platform --> pkg_deepseek_account
pkg_deepseek_account_platform --> pkg_host_webserver
pkg_experimental_ptc_runtime_python --> pkg_ptc_runtime
pkg_experimental_ptc_runtime_python --> pkg_sandbox
pkg_experimental_ptc_runtime_python --> pkg_sandbox_policy
@@ -1584,6 +1582,7 @@ flowchart TD
| [`client-resources`](../packages/client/resources) | `client` | — |
| [`client-shortcuts`](../packages/client/shortcuts) | `client` | — |
| [`client-store`](../packages/client/store) | `client` | — |
| [`client-ui-account-notifications`](../packages/client/ui-account-notifications) | `client` | — |
| [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — |
| [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — |
| [`client-ui-approval`](../packages/client/ui-approval) | `client` | — |
@@ -1707,6 +1706,7 @@ flowchart TD
| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) |
| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) |
| [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
@@ -1774,7 +1774,7 @@ flowchart TD
| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`util-time`](../packages/util/time) |
| [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) |
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`util-values`](../packages/util/values) |
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`authorization`](../packages/credentials/authorization), [`brand`](../packages/util/brand), [`credentials`](../packages/credentials/credentials), [`host-webserver`](../packages/host/webserver), [`llm`](../packages/llm/llm), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
| [`commands`](../packages/interaction/commands) | `interaction` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
| [`user-approval`](../packages/interaction/user-approval) | `interaction` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) |
| [`user-questions`](../packages/interaction/user-questions) | `interaction` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) |
@@ -1791,9 +1791,7 @@ flowchart TD
| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) |
| [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) |
| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
| [`compaction`](../packages/compaction/compaction) | `compaction` | [`brand`](../packages/util/brand), [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) |
| [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) |
| [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
| [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
+1
View File
@@ -78,6 +78,7 @@ interface Agent {
* Clear queued and steering work — unless `keepInbox` — and abort the active
* turn or between-turn task. The first cause wins for that activity. With no
* active activity, cancellation is a no-op and does not arm later work.
* Queue-write failures still abort the activity and propagate to the caller.
* @param cause - the stable caller intent carried by the active operation signal.
* @param options - cancellation options; `keepInbox` preserves pending work.
*/
+1
View File
@@ -82,6 +82,7 @@ interface Agent {
* Clear queued and steering work — unless `keepInbox` — and abort the active
* turn or between-turn task. The first cause wins for that activity. With no
* active activity, cancellation is a no-op and does not arm later work.
* Queue-write failures still abort the activity and propagate to the caller.
* @param cause - the stable caller intent carried by the active operation signal.
* @param options - cancellation options; `keepInbox` preserves pending work.
*/
+6 -6
View File
@@ -12,14 +12,14 @@
en: baaab4bca76bea6b
zh: 54ccdc03ffd44f63
/user-credentials/description:
en: f7b09588c0f34952
zh: 1b93d673c5bf6a80
en: 60ce885c8cac3082
zh: 9f1cf7d25119cdda
/user-credentials/change-commits:
en: 464315a953330eb2
zh: d9815591f3abc2cb
/user-credentials/embedded-platform-credentials:
en: 78240c18fc9a085d
zh: dabf5fae10b54663
en: 6f80d44cdec8e05a
zh: 658e5e4958f9baa6
/user-credentials/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit:
en: 314e5b36f51b2c64
zh: 0e1cb3fe5adf5ecd
en: 664f0f89d89ac686
zh: 178263324ad76307
+84 -55
View File
@@ -32,13 +32,12 @@ interface ResolvedCredential {
## Description
`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again.
`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The optional `masked` field carries a provider-generated preview without the full credential. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again.
```ts type-equiv
/**
* Source and writability facts for one reference, safe for configuration UIs —
* never the value. The view has no slot a value could ride in, which is what
* lets the whole read half cross the Remote wire.
* Configuration facts and an optional provider-masked preview for one
* reference. The full credential is never part of this view.
*/
interface CredentialInfo {
/** Whether resolving the reference would currently return a value. */
@@ -47,6 +46,8 @@ interface CredentialInfo {
source?: string
/** Whether the active provider can write this reference. */
writable: boolean
/** Provider-generated masked preview of a stored value; never the full value. */
masked?: string
}
```
@@ -56,7 +57,7 @@ interface CredentialInfo {
## Embedded Platform credentials
PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account-controller RPC, AccountView, and AccountDetails.
PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails.
AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays.
@@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
/**
* Describe one reference for configuration surfaces without exposing the
* value.
* full value.
* @param ref - the reference to describe.
* @returns configured state, supplying source, and writability.
* @returns configured state, supplying source, writability, and optional masked preview.
*/
abstract describe(ref: CredentialRef): Promise<CredentialInfo>
@@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent
### `ctx.credentialsController` — `CredentialsController`
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one.
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one.
```ts cordis-catalog
/**
@@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie
Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts)
<a id="ctxdeepseekaccount--deepseekaccount-abstract-seam"></a>
<a id="ctxdeepseekaccount--deepseekaccount"></a>
### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam)
### `ctx.deepseekAccount` — `DeepSeekAccount`
Account operations; only Host consumers can obtain a request credential.
Account login, credentials, and client-safe Remote operations.
```ts cordis-catalog
/**
* Read stored-account presence and the latest login attempt.
* @returns a snapshot without credentials or PKCE secrets.
*/
abstract getState(): Promise<AccountView>
@Remote async getState(): Promise<AccountView>
/**
* Query Platform profile independently of wallet balances.
@@ -281,30 +282,65 @@ abstract getState(): Promise<AccountView>
* @param client - identity of the requesting UI for this call.
* @returns profile outcome, or null if signed out or the grant changed during the query.
*/
abstract getProfile(client: AccountClientMetadata): Promise<AccountDetails['profile'] | null>
@Remote async getProfile(client: AccountClientMetadata): Promise<AccountDetails['profile'] | null>
/**
* Query Platform recharge and bonus wallet balances independently of profile data.
* @param client - identity of the requesting UI for this call.
* @returns balance outcome, or null if signed out or the grant changed during the query.
*/
abstract getBalance(client: AccountClientMetadata): Promise<AccountDetails['balance'] | null>
@Remote getBalance(client: AccountClientMetadata): Promise<AccountDetails['balance'] | null>
/**
* Query the granted bonuses Platform has not yet recorded as displayed.
* Query unconsumed account notifications in server order without reading profile data.
* @param client - identity of the requesting UI for this call; its language selects the server-authored message.
* @returns bonuses with their account, or null if signed out or the grant changed during the query.
* @returns notifications with their next query delay, or null if signed out or the grant changed during the query.
*/
abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise<AccountBonusBatch | null>
@Remote async getNotifications(client: AccountClientMetadata): Promise<AccountNotificationBatch | null>
/**
* Record one displayed bonus as notified for the account it belongs to.
* @param accountId - account the notification was read for; a different current account is never acknowledged.
* @param orderId - granted bonus order the user saw.
* @param client - identity of the requesting UI for this call.
* @returns true once Platform records the acknowledgement; false if signed out or the account changed.
* Query localized content of a notification, including one already consumed.
* @param id - notification whose content is requested.
* @param client - identity of the requesting UI; its language selects the localized content.
* @returns content without changing consumption, or null if signed out or the grant changed.
*/
abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise<boolean>
@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise<AccountNotification | null>
/**
* Report a notification interaction; the backend decides consumption.
* @param id - notification the user interacted with.
* @param event - displayed frame, non-dismiss action click, or explicit dismissal.
* @param client - identity of the requesting UI for this call.
* @returns true once the server accepts the event; false if signed out or credentials changed during the call.
*/
@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise<boolean>
/**
* Remove an inference-rejected token only while it still matches the stored login.
* @param token - token captured by the rejected inference request.
* @returns after matching credentials are removed and the expiry notification is emitted.
*/
async rejectToken(token: string): Promise<void>
/**
* Read existing login identity without creating a device or returning credentials.
* @returns optional device/account identifiers and the provider's OS version string.
*/
async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>
/**
* Read credentials for the configured embedded-page origin, bound to their account environment, and
* pair them with the account ID from the last successful profile read; no profile request is made.
* @returns a Host-only snapshot, or null while signed out or when the credential changed during the read.
*/
async getPlatformSession(): Promise<PlatformSession | null>
/**
* Resolve a credential only for the inference origin allowed by the provider.
* @param url - actual request destination or API base URL.
* @returns stored token, or undefined for other origins or a signed-out account.
*/
async resolveToken(url: string): Promise<string | undefined>
/**
* Join an active attempt or start browser authorization.
@@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId
* @param loginSource - initiating UI, used to return from a failed exchange.
* @returns the initial snapshot without waiting for browser approval.
*/
abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise<AccountView>
@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise<AccountView>
/**
* Cancel only the named attempt; committing attempts settle before returning.
* @param id - attempt identity from this Host.
* @param attemptId - attempt identity from this Host.
* @returns state after cancellation or an already-started commit.
*/
abstract cancelSignIn(id: SignInAttemptId): Promise<AccountView>
@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise<AccountView>
/**
* Remove the local grant while retaining API keys; the provider revokes it in the background.
* @param client - identity of the requesting UI, captured for the background revocation retries.
* @returns the signed-out state after local removal; remote failures never restore the grant.
*/
abstract signOut(client: AccountClientMetadata): Promise<AccountView>
@Remote signOut(client: AccountClientMetadata): Promise<AccountView>
/**
* Subscribe to snapshots including a complete initial state.
* Inspect running work before sign-out.
* @returns whether a running task's latest request uses the account route; false when the optional agents service is absent.
*/
@Remote hasRunningAccountTasks(): boolean
/**
* Subscribe to live credential expiry without replay.
* @param signal - subscription lifetime; provider disposal also ends it.
* @returns expiry notifications emitted during the subscription.
*/
@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'>
/**
* Subscribe to ordered updates including a complete initial snapshot.
* @param signal - subscription lifetime; ending it never cancels login.
* @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false.
* @returns complete snapshots as account state changes.
* @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce.
*/
abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable<AccountView>
watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable<AccountUpdate>
/**
* Resolve a credential only for the inference origin allowed by the provider.
* @param url - actual request destination or API base URL.
* @returns stored token, or undefined for other origins or a signed-out account.
* Stream account state without the Host-only identity subscription option.
* @param signal - subscription lifetime.
* @returns initial state, login progress, and credential-change updates.
*/
abstract resolveToken(url: string): Promise<string | undefined>
/**
* Remove an inference-rejected token only while it still matches the stored login.
* @param token - token captured by the rejected inference request.
* @returns after matching credentials are removed and the expiry notification is emitted.
*/
abstract rejectToken(token: string): Promise<void>
/**
* Read credentials for the configured Platform origin, bound to their issuing environment, and
* pair them with the account ID from the last successful profile read; no profile request is made.
* @returns a Host-only snapshot, or null while signed out or when the credential changed during the read.
*/
abstract getPlatformSession(): Promise<PlatformSession | null>
/**
* Read existing login identity without creating a device or returning credentials.
* @returns optional device/account identifiers and the provider's OS version string.
*/
abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>
@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable<AccountUpdate>
```
Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts)
@@ -488,6 +517,6 @@ Local grant removal has completed.
Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts)
<!-- END GENERATED cordis-surface -->
The account Service Definition exposes getState, getProfile, getBalance, getUnnotifiedBonuses, ackBonusNotified, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. See [the account package](../../packages/credentials/deepseek-account/README.md).
The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/credentials/deepseek-account/README.md).
`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries.
+84 -55
View File
@@ -32,13 +32,12 @@ interface ResolvedCredential {
## 描述
`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。
`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。可选的 `masked` 字段携带提供方生成的脱敏预览,不包含完整凭据。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。
```ts type-equiv
/**
* Source and writability facts for one reference, safe for configuration UIs —
* never the value. The view has no slot a value could ride in, which is what
* lets the whole read half cross the Remote wire.
* Configuration facts and an optional provider-masked preview for one
* reference. The full credential is never part of this view.
*/
interface CredentialInfo {
/** Whether resolving the reference would currently return a value. */
@@ -47,6 +46,8 @@ interface CredentialInfo {
source?: string
/** Whether the active provider can write this reference. */
writable: boolean
/** Provider-generated masked preview of a stored value; never the full value. */
masked?: string
}
```
@@ -56,7 +57,7 @@ interface CredentialInfo {
## 内嵌 Platform 凭证
PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号控制器 RPC、AccountView 和 AccountDetails 均不包含此快照。
PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。
AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。
@@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
/**
* Describe one reference for configuration surfaces without exposing the
* value.
* full value.
* @param ref - the reference to describe.
* @returns configured state, supplying source, and writability.
* @returns configured state, supplying source, writability, and optional masked preview.
*/
abstract describe(ref: CredentialRef): Promise<CredentialInfo>
@@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent
### `ctx.credentialsController` — `CredentialsController`
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one.
Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one.
```ts cordis-catalog
/**
@@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie
Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts)
<a id="ctxdeepseekaccount--deepseekaccount-abstract-seam"></a>
<a id="ctxdeepseekaccount--deepseekaccount"></a>
### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam)
### `ctx.deepseekAccount` — `DeepSeekAccount`
Account operations; only Host consumers can obtain a request credential.
Account login, credentials, and client-safe Remote operations.
```ts cordis-catalog
/**
* Read stored-account presence and the latest login attempt.
* @returns a snapshot without credentials or PKCE secrets.
*/
abstract getState(): Promise<AccountView>
@Remote async getState(): Promise<AccountView>
/**
* Query Platform profile independently of wallet balances.
@@ -281,30 +282,65 @@ abstract getState(): Promise<AccountView>
* @param client - identity of the requesting UI for this call.
* @returns profile outcome, or null if signed out or the grant changed during the query.
*/
abstract getProfile(client: AccountClientMetadata): Promise<AccountDetails['profile'] | null>
@Remote async getProfile(client: AccountClientMetadata): Promise<AccountDetails['profile'] | null>
/**
* Query Platform recharge and bonus wallet balances independently of profile data.
* @param client - identity of the requesting UI for this call.
* @returns balance outcome, or null if signed out or the grant changed during the query.
*/
abstract getBalance(client: AccountClientMetadata): Promise<AccountDetails['balance'] | null>
@Remote getBalance(client: AccountClientMetadata): Promise<AccountDetails['balance'] | null>
/**
* Query the granted bonuses Platform has not yet recorded as displayed.
* Query unconsumed account notifications in server order without reading profile data.
* @param client - identity of the requesting UI for this call; its language selects the server-authored message.
* @returns bonuses with their account, or null if signed out or the grant changed during the query.
* @returns notifications with their next query delay, or null if signed out or the grant changed during the query.
*/
abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise<AccountBonusBatch | null>
@Remote async getNotifications(client: AccountClientMetadata): Promise<AccountNotificationBatch | null>
/**
* Record one displayed bonus as notified for the account it belongs to.
* @param accountId - account the notification was read for; a different current account is never acknowledged.
* @param orderId - granted bonus order the user saw.
* @param client - identity of the requesting UI for this call.
* @returns true once Platform records the acknowledgement; false if signed out or the account changed.
* Query localized content of a notification, including one already consumed.
* @param id - notification whose content is requested.
* @param client - identity of the requesting UI; its language selects the localized content.
* @returns content without changing consumption, or null if signed out or the grant changed.
*/
abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise<boolean>
@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise<AccountNotification | null>
/**
* Report a notification interaction; the backend decides consumption.
* @param id - notification the user interacted with.
* @param event - displayed frame, non-dismiss action click, or explicit dismissal.
* @param client - identity of the requesting UI for this call.
* @returns true once the server accepts the event; false if signed out or credentials changed during the call.
*/
@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise<boolean>
/**
* Remove an inference-rejected token only while it still matches the stored login.
* @param token - token captured by the rejected inference request.
* @returns after matching credentials are removed and the expiry notification is emitted.
*/
async rejectToken(token: string): Promise<void>
/**
* Read existing login identity without creating a device or returning credentials.
* @returns optional device/account identifiers and the provider's OS version string.
*/
async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>
/**
* Read credentials for the configured embedded-page origin, bound to their account environment, and
* pair them with the account ID from the last successful profile read; no profile request is made.
* @returns a Host-only snapshot, or null while signed out or when the credential changed during the read.
*/
async getPlatformSession(): Promise<PlatformSession | null>
/**
* Resolve a credential only for the inference origin allowed by the provider.
* @param url - actual request destination or API base URL.
* @returns stored token, or undefined for other origins or a signed-out account.
*/
async resolveToken(url: string): Promise<string | undefined>
/**
* Join an active attempt or start browser authorization.
@@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId
* @param loginSource - initiating UI, used to return from a failed exchange.
* @returns the initial snapshot without waiting for browser approval.
*/
abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise<AccountView>
@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise<AccountView>
/**
* Cancel only the named attempt; committing attempts settle before returning.
* @param id - attempt identity from this Host.
* @param attemptId - attempt identity from this Host.
* @returns state after cancellation or an already-started commit.
*/
abstract cancelSignIn(id: SignInAttemptId): Promise<AccountView>
@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise<AccountView>
/**
* Remove the local grant while retaining API keys; the provider revokes it in the background.
* @param client - identity of the requesting UI, captured for the background revocation retries.
* @returns the signed-out state after local removal; remote failures never restore the grant.
*/
abstract signOut(client: AccountClientMetadata): Promise<AccountView>
@Remote signOut(client: AccountClientMetadata): Promise<AccountView>
/**
* Subscribe to snapshots including a complete initial state.
* Inspect running work before sign-out.
* @returns whether a running task's latest request uses the account route; false when the optional agents service is absent.
*/
@Remote hasRunningAccountTasks(): boolean
/**
* Subscribe to live credential expiry without replay.
* @param signal - subscription lifetime; provider disposal also ends it.
* @returns expiry notifications emitted during the subscription.
*/
@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'>
/**
* Subscribe to ordered updates including a complete initial snapshot.
* @param signal - subscription lifetime; ending it never cancels login.
* @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false.
* @returns complete snapshots as account state changes.
* @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce.
*/
abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable<AccountView>
watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable<AccountUpdate>
/**
* Resolve a credential only for the inference origin allowed by the provider.
* @param url - actual request destination or API base URL.
* @returns stored token, or undefined for other origins or a signed-out account.
* Stream account state without the Host-only identity subscription option.
* @param signal - subscription lifetime.
* @returns initial state, login progress, and credential-change updates.
*/
abstract resolveToken(url: string): Promise<string | undefined>
/**
* Remove an inference-rejected token only while it still matches the stored login.
* @param token - token captured by the rejected inference request.
* @returns after matching credentials are removed and the expiry notification is emitted.
*/
abstract rejectToken(token: string): Promise<void>
/**
* Read credentials for the configured Platform origin, bound to their issuing environment, and
* pair them with the account ID from the last successful profile read; no profile request is made.
* @returns a Host-only snapshot, or null while signed out or when the credential changed during the read.
*/
abstract getPlatformSession(): Promise<PlatformSession | null>
/**
* Read existing login identity without creating a device or returning credentials.
* @returns optional device/account identifiers and the provider's OS version string.
*/
abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>
@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable<AccountUpdate>
```
Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts)
@@ -488,6 +517,6 @@ Local grant removal has completed.
Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts)
<!-- END GENERATED cordis-surface -->
账号服务定义提供 getState、getProfile、getBalance、getUnnotifiedBonuses、ackBonusNotified、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。
账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。
`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。
+4 -4
View File
@@ -6,8 +6,8 @@
en: 3990a17e12c66a23
zh: 4170c33e49248f8f
/forges/providers-and-change-requests:
en: 4ec7d1892b4067db
zh: 6bb70d21ae3d7a89
en: e5d807b29f553751
zh: e0b25d9e964f988e
/forges/status-polling:
en: 26ccfa2e342e3e67
zh: fe6cc2a622757c48
@@ -18,5 +18,5 @@
en: 13dfd36f2166bba0
zh: a369434f52f04d57
/forges/panel:
en: dbc28e731f357edf
zh: a1977fafc0651427
en: e52a5c57abc4d30e
zh: 509a40f421cc3d33
+177 -26
View File
@@ -68,15 +68,59 @@ interface ForgeProvider {
markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
/** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */
merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
/** Read the changes of a change request as the host computes them, as one unified patch with `a/` and `b/` path prefixes. */
diff(ref: ChangeRequestRef, signal: AbortSignal): Promise<string | ForgeFailure>
/**
* Read the changes of a change request at head commit `headSha` as the host computes them, as one unified
* patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the
* head is another commit, the read resolves to a `stale` failure.
*/
diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure>
/** Read the text of `path` at `commit` in the change request's repository. */
fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise<string | ForgeFailure>
/** Build the web page of `path` at `commit` in the change request's repository. */
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string
/**
* List the commits of a change request at its current head. A provider implements `commits` and `compare`
* together; omitting either declares that the change request can be read only as a whole.
*/
commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure>
/**
* Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch
* with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`.
*/
compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
}
```
```ts type-equiv
/** One commit of a change request. */
interface ForgeCommit {
/** Full commit object name. */
readonly sha: string
/** Full object name of the first parent, or null for a root commit. */
readonly parent: string | null
/** First line of the commit message. */
readonly title: string
/** Author name or login as the host reports it, or null when it reports none. */
readonly author: string | null
/** ISO 8601 time the commit was authored. */
readonly authoredAt: string
}
```
```ts type-equiv
/** The commits of a change request at one head commit. */
interface ForgeCommitList {
/** Head commit the list was read at. */
readonly headSha: string
/** Commits oldest first, ending with the head commit unless `truncated`. */
readonly commits: readonly ForgeCommit[]
/** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */
readonly truncated: boolean
}
```
`ctx.forge.commits` and `ctx.forge.compare` delegate to a provider that implements both; otherwise `commits` resolves to undefined and `compare` to an `unavailable` failure, so the forge panel offers its commit picker only where the provider reads commits.
```ts type-equiv
/** Whether a provider can reach one host with the current credentials. */
interface ForgeReadiness {
@@ -176,8 +220,10 @@ interface ChangeRequestSnapshot {
readonly checksRollup: ChecksRollup
/** Whether the host reported more checks than `checks` contains. */
readonly checksTruncated: boolean
/** Number of review threads that are not resolved. */
/** Number of counted review threads that are not resolved. */
readonly unresolvedThreads: number
/** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */
readonly threadsTruncated: boolean
/** ISO 8601 time of the host's last update to the change request. */
readonly updatedAt: string
/** ISO 8601 time the change request was merged or closed, or null while it is open. */
@@ -191,9 +237,10 @@ interface ForgeFailure {
/**
* `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected;
* `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails
* the same way; `unavailable`: any other failure.
* the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of
* a later status can succeed; `unavailable`: any other failure.
*/
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'unavailable'
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable'
/** Human-readable cause. */
readonly message: string
}
@@ -568,7 +615,20 @@ type ForgeChangeRequestStatesFrame =
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
```
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point.
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
```ts type-equiv
/**
* Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order
* the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last.
*/
interface ForgeCommitRange {
/** First, oldest commit shown. */
readonly from: string
/** Last, newest commit shown; equal to `from` for one commit. */
readonly to: string
}
```
```ts type-equiv
/** Which local changes a diff covers; each reads the Session's checkout through Git. */
@@ -576,9 +636,10 @@ type ForgeLocalScope =
/**
* The working tree and untracked files against a fork point: the merge base of HEAD with the
* `base` ref, or while `base` is null, the base commit of the worktree the Session created,
* else the merge base of HEAD with the default branch of the code host remote.
* else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
* of those commits between the fork point and HEAD, without uncommitted or untracked files.
*/
| { readonly kind: 'branch'; readonly base: string | null }
| { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null }
/** The working tree and untracked files against HEAD. */
| { readonly kind: 'uncommitted' }
/** The working tree and untracked files against the index. */
@@ -640,6 +701,15 @@ interface ForgeDiffHunk {
type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed'
```
```ts type-equiv
/**
* Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else
* `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in
* test and interface rules that the path matches, else `implementation`.
*/
type ForgeFileLayer = 'interface' | 'implementation' | 'test'
```
```ts type-equiv
/** One changed file of a diff. */
interface ForgeDiffFile {
@@ -661,6 +731,13 @@ interface ForgeDiffFile {
readonly deletions: number
/** Hunks in file order; none for a binary file or a change of mode or name only. */
readonly hunks: readonly ForgeDiffHunk[]
/** Review layer the path falls in. */
readonly layer: ForgeFileLayer
/**
* Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content
* of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it.
*/
readonly digest: string
}
```
@@ -677,22 +754,34 @@ interface ForgeLocalDiff {
```
```ts type-equiv
/** Changes of a change request as its code host computes them. */
/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */
interface ForgeChangeRequestDiff {
/** Head commit the diff describes. */
/** Commit whose new side the diff describes: the head, or the last chosen commit. */
readonly headSha: string
/** Changed files in the host's order. */
readonly files: readonly ForgeDiffFile[]
/**
* Commits the checkout's branch has beyond the head when that branch is the change request's head
* branch and the head commit is present locally; null otherwise.
* branch and the head commit is present locally; null otherwise and for chosen commits.
*/
readonly localAhead: number | null
/** Web page of each changed file at the head commit, by path. */
/** Web page of each changed file at `headSha`, by path. */
readonly fileUrls: Readonly<Record<string, string>>
}
```
```ts type-equiv
/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */
interface ForgeLocalCommits {
/** HEAD commit the list was read at. */
readonly headSha: string
/** Commits oldest first, ending with HEAD's commit. */
readonly commits: readonly ForgeCommit[]
/** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */
readonly truncated: boolean
}
```
```ts type-equiv
/** One file the `branch` scope changes, without its hunks. */
interface ForgeChangedFile {
@@ -814,13 +903,39 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal):
async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeRequestSnapshot | ForgeFailure>
/**
* Read the changes of a change request as its host computes them.
* Read the changes of a change request at one head commit as its host
* computes them. The first `stale` failure at a head commit polls a watched
* change request again at once, so its next status names the current head;
* later stale reads at the same commit wait for the regular poll, which
* bounds the reads while the host's answers disagree.
* @param ref - change request served by a registered provider.
* @param headSha - head commit the patch must describe, usually the head of the latest status.
* @param signal - cancellation of the read.
* @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it.
* @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise<string | ForgeFailure>
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure>
/**
* List the commits of a change request at its current head.
* @param ref - change request served by a registered provider.
* @param signal - cancellation of the read.
* @returns the commits, why the host did not provide them, or undefined when the provider does not read commits.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise<ForgeCommitList | ForgeFailure | undefined>
/**
* Read the changes between two commits of a change request's repository.
* @param ref - change request served by a registered provider.
* @param base - full object name of the commit compared from.
* @param head - full object name of a commit that descends from `base`.
* @param signal - cancellation of the read.
* @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that
* does not read commits returns `unavailable`.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise<string | ForgeFailure>
/**
* Publish one comment or a completed review, then refresh the watched status.
@@ -975,21 +1090,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current
* @returns the files, the base of the `branch` scope, and the untracked files left out.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
* a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
* a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
* `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
* `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
* any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.
*/
@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise<ForgeLocalDiff>
/**
* List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
* several of instead of the whole scope.
* @param session - Session whose checkout is read.
* @param base - the base ref of the `branch` scope, or null for its automatic fork point.
* @param signal - request cancellation.
* @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
* exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
*/
@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise<ForgeLocalCommits>
/**
* Read the new side of one changed file in a scope, which supplies the
* unchanged lines between its hunks: the index for `staged`, else the working tree.
* unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
* the `branch` scope, else the working tree.
* @param session - Session whose checkout is read.
* @param scope - the scope the diff was read in.
* @param path - path relative to the checkout's top-level directory, as the diff names it.
* @param signal - request cancellation.
* @returns the text.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
* an error for a path outside the checkout, binary content, or a failed read.
* `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
* the checkout, binary content, or a failed read.
*/
@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise<string>
@@ -1006,19 +1137,39 @@ Serves the forge panel. Following a Session inspects the checkout of its current
@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise<ChangeRequestSnapshot>
/**
* Read the changes of a change request of a Session as its code host
* computes them, at the head commit of its latest status. A patch already
* read at the same head commit and base branch is reused from memory, for
* any Session, until `maxCachedDiffBytes` evicts it.
* List the commits of a change request of a Session at its current head, which the changes view can show one or
* several of instead of the whole change request.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param signal - request cancellation.
* @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head.
* @returns the commits oldest first with the head they were read at, or null when the provider does not read commits.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
* `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
* `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise.
* `forgePanel/diff-failed` when the host does not list them.
*/
@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise<ForgeChangeRequestDiff>
@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise<ForgeCommitList | null>
/**
* Read the changes of a change request of a Session as its code host
* computes them, with each file's layer following the root `.gitattributes`
* of the commit the diff ends at. Without `commits` the diff covers the change
* request at the head commit of its latest status; a patch already read at the
* same head commit and base branch is reused from memory with its attributes, for
* any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those
* commits, from the first one's first parent to the last, and is read every time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param commits - consecutive commits of the change request, or null for all of it.
* @param signal - request cancellation.
* @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
* `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order;
* `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
* `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again;
* `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
* `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host
* does not provide the commits, the diff, or an existing `.gitattributes` otherwise.
*/
@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise<ForgeChangeRequestDiff>
/**
* Read one file of a change request's repository at a commit, which
Loaded 100 of 723 files, more files were not shown because too many files have changed in this diff. Show more