diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml index ddd6d80912..5a918c8cc1 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md index 84b30b6cb4..c452ae85ae 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md index 31925f7a9f..e68747a9b6 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md @@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho `stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。 -在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。 +在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。 create/adopt、全文搜索和普通历史打开允许自动迁移。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml index dba92660c8..04a78f70d3 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml @@ -9,8 +9,8 @@ en: cdc04139c8d69415 zh: a3fe3e78ada08d95 /agent-note-continuous-cua-hover-without-cross-call-ownership/decision: - en: d1ea8fdc05927896 - zh: d3039bbb82bc949c + en: 125c860c1c568960 + zh: 8a2ece1101358200 /agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered: en: 18d917ee2e909b93 zh: 5b5ad0530f138cda diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md index 1cc8db5f81..2cce428cff 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md @@ -10,7 +10,7 @@ Hover interactions span movement, delayed content, observation and input inside ## Decision -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. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md index 2f5ef0ce36..cc2457a70a 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -显式窗口提供 `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 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml index 8259c024fb..9775baf3a4 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml @@ -9,8 +9,8 @@ en: f96bf1ebc0719fb0 zh: e9a1144f0e76572d /agent-note-background-hover-and-screenshot-coordinates/decision: - en: 6ac0b77bea25fcf7 - zh: e50fec9049926fdc + en: bdf4d3386521ce00 + zh: 96db93177ad96a76 /agent-note-background-hover-and-screenshot-coordinates/alternatives-considered: en: 5fc4beaf79761c50 zh: 4948333b0020be28 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md index 1091fcaf5e..c385525731 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md index 2344d61c95..0d3db32400 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md @@ -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。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index f3a0d8f1d3..3e32b6eb92 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 609e5bf901..cce266e52b 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 081f02986e..5135dc9be8 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.i18n.yaml new file mode 100644 index 0000000000..e1e734251c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-07-forge-changes-view-responsiveness.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.md +/agent-note-forge-changes-view-responsiveness: + en: e809ffea0d880a4b + zh: 6725e6a9bd1c3bd1 +/agent-note-forge-changes-view-responsiveness/problem: + en: 77fab27f3d4a4a59 + zh: 46e0fa8b9ef978a7 +/agent-note-forge-changes-view-responsiveness/decision: + en: 40550cf129ab4c0c + zh: 2e9a3597d03ce185 +/agent-note-forge-changes-view-responsiveness/alternatives-considered: + en: c9833999164e8b67 + zh: 9459a95f307db854 +/agent-note-forge-changes-view-responsiveness/consequences: + en: 2d74147e306ed174 + zh: f1369020f27f92c0 diff --git a/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.md b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.md new file mode 100644 index 0000000000..9ceef3f98f --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.md @@ -0,0 +1,41 @@ +# Agent Note: Forge changes view responsiveness + +Status: implemented + +English | [中文](2026-11-07-forge-changes-view-responsiveness.zh.md) + +## Problem + +The forge changes view of a large change request froze the browser. Opening #7985 (366 files, 37,563 drawn lines) kept the main thread busy for about five seconds, "expand all" for fifteen, and every later state change, such as a poll result, a tool result, a file jump, or a keystroke in the file filter, re-rendered every file section. While the view was visible, the whole app slowed down: two subject-less `:has()` rules in `ui-sidebar-files` made each DOM change restyle the entire document, and the view's hundred thousand nodes made each restyle cost 170–260 ms, so a streaming Agent turn kept the main thread saturated. + +## Decision + +**Scoped `:has()` rules.** The navigator's covering rules name their row through `data-files-navigator-row`, which both hosts of `sidebar.files.navigator` set, so a DOM change outside such a row schedules no document-wide invalidation. + +**Sections draw what changed and what the reader reaches.** `ChangesTab` passes each memoized `DiffFile` values whose identity survives its renders: one handler object, one comment-actions object, and per-file strings and booleans. Tab visibility is a prop of every section, so a visibility change redraws them all; leaving the view measured +57 ms against reading it from a React context, which the client packages forbid business components to do. The scrollport's reach tracker travels in the handler object. An expanded file holds a 22 px row per drawn line until its section first comes within 1200 px of the scrollport, then draws its lines and keeps them. After a jump, the browser's scroll anchoring keeps the target in place while the sections above it draw. + +**Highlighting in the drawing render.** A section highlights its lines in the same render that draws them, as before, so the drawn text is always the file's current text and a native selection keeps its text nodes. + +**Fewer serial reads.** A panel state equal to the published one reaches no follower. `changeRequestDiff` reads the patch and `.gitattributes` together. Snapshots carry the base commit as `baseSha`; `ForgeService.diff` passes it to the provider, and forge-github starts the compare read while its GraphQL read confirms the head. + +**Pixel measurement.** Whether a section is near the scrollport decides whether React renders its lines at all, which CSS cannot express: `content-visibility` only skips layout and paint of nodes that already exist. The client packages offer no injected measurement hook, so one `IntersectionObserver` on the scrollport measures it off the main thread. + +## Alternatives considered + +**`content-visibility: auto` alone** cut style work as much as scoping the rules did, but kept the React render and Shiki tokenization of every expanded file at open, about 3 s of script, and its placeholder sizes would need estimates for every collapsed and expanded section. + +**Full virtualization that also unmounts far sections** would bound the DOM after long scrolls, but a section holds a comment draft and a text selection, which unmounting loses. + +**Deferred idle-time highlighting** drew plain text and applied tokens once the page was idle and the scrollport still. It kept fast scrolling smooth, but tokens carry their own text, so a file whose content changed at the same path showed its previous text until the next pass, and replacing the plain text nodes collapsed a selection made in the meantime. Against it, highlighting while drawing raised the blocking time of scrolling all of #7985 from 22 ms to 1,634 ms and its longest frame gap from 34 ms to 817 ms; other operations stayed within 0.1 s. + +**The CSS Custom Highlight API** would paint token colors over unchanged text nodes and keep deferral without either defect, but it cannot apply the themes' bold and italic, and its cost over tens of thousands of ranges is unmeasured. + +**Re-aligning a jumped-to section every frame for a second** kept the last file flush with the end of the list, but it also pulled back any scroll it did not start, such as one from find in page; scroll anchoring already holds every other target at the top. + +**Highlighting in a Web Worker** removes tokenization from the main thread entirely, including a heavy grammar's first use, but the shared highlighter in `ui-primitives` owns Shiki; moving it is a separate change for every consumer. + +**A provider-private cache of base commits** would avoid the optional `baseSha` field, but it adds retained state without an owner that knows when a change request stops being watched. + +## Consequences + +Opening #7985 now takes 0.5 s of main-thread work instead of 5.2 s, and file jumps, filtering, polling, and Agent turns no longer produce long tasks. In exchange, the browser's find in page does not see lines of files the reader has not approached, and scrolling onto files in a slow grammar's language, such as C++, highlights them during the scroll, up to about 0.8 s of main-thread work when that grammar is first used. A diff read costs a second compare request when the base commit changed after the latest status. diff --git a/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.zh.md b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.zh.md new file mode 100644 index 0000000000..fda2dc4b11 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-07-forge-changes-view-responsiveness.zh.md @@ -0,0 +1,41 @@ +# Agent Note: Forge 变更视图的响应速度 + +Status: implemented + +[English](2026-11-07-forge-changes-view-responsiveness.md) | 中文 + +## Problem + +大型变更请求的 forge 变更视图会让浏览器卡住。打开 #7985(366 个文件、37,563 个绘制行)时主线程忙约 5 秒,“全部展开”约 15 秒;之后的每次状态变化,例如轮询结果、工具结果、跳转文件或在文件筛选框中按键,都会重渲染所有文件段。视图可见时整个应用都变慢:`ui-sidebar-files` 中两条没有主体的 `:has()` 规则让每次 DOM 变化都重算整个文档的样式,而视图的十万个节点让每次重算耗时 170–260 ms,所以 Agent 流式输出的回合会让主线程一直饱和。 + +## Decision + +**限定 `:has()` 规则。** 导航器的遮盖规则通过 `data-files-navigator-row` 指定所在行,`sidebar.files.navigator` 的两个宿主都会设置它,因此这类行之外的 DOM 变化不再触发全文档失效。 + +**文件段只绘制变化的部分和读者接近的部分。** `ChangesTab` 传给每个 memo 化的 `DiffFile` 的值在多次渲染之间保持同一标识:一个处理函数对象、一个评论操作对象,以及每个文件的字符串和布尔值。标签页可见性作为每个文件段的参数传入,可见性变化时全部文件段都会重绘;离开视图实测比从 React context 读取多 57 ms,而客户端包禁止业务组件读取 context。滚动区域的接近跟踪对象放在处理函数对象中传递。展开的文件在它的段第一次进入滚动区域 1200 px 范围之前,按每个绘制行 22 px 占位,之后绘制各行并一直保留。跳转后,上方文件段绘制时,浏览器的滚动锚定让目标保持原位。 + +**在绘制的渲染中高亮。** 文件段与修复前一样,在绘制各行的同一次渲染中完成高亮,所以画出的始终是文件当前的文本,原生选区所在的文本节点也不会被替换。 + +**减少串行读取。** 与已发布状态相同的面板状态不会通知任何关注方。`changeRequestDiff` 同时读取补丁和 `.gitattributes`。快照把基准提交作为 `baseSha` 携带;`ForgeService.diff` 把它传给提供方,forge-github 在 GraphQL 读取确认 head 的同时就开始 compare 读取。 + +**像素测量。** 文件段是否接近滚动区域,决定 React 是否渲染它的各行,这一点 CSS 无法表达:`content-visibility` 只能跳过已有节点的布局与绘制。客户端包没有可注入的测量 hook,所以在滚动区域上用一个 `IntersectionObserver`,在主线程之外测量。 + +## Alternatives considered + +**只用 `content-visibility: auto`** 减少的样式工作与限定规则相当,但打开时仍要对每个展开文件做 React 渲染和 Shiki 分词,约 3 秒脚本时间,而且每个折叠和展开的段都需要估计占位尺寸。 + +**同时卸载远处文件段的完整虚拟化** 可以在长距离滚动后限制 DOM 规模,但文件段持有评论草稿和文本选区,卸载会丢失它们。 + +**空闲时延迟高亮** 先画纯文本,等页面空闲且滚动区域静止后再应用 token。它让快速滚动保持流畅,但 token 自带文本,同一路径内容变化后会显示旧文本直到下一轮高亮完成;替换纯文本节点还会清掉期间做出的选区。与它相比,绘制时高亮让滚动整个 #7985 的阻塞时间从 22 ms 增到 1,634 ms,最长帧间隔从 34 ms 增到 817 ms;其他操作的差异在 0.1 秒以内。 + +**CSS Custom Highlight API** 可以在不变的文本节点上绘制 token 颜色,保留延迟高亮又没有上述两个问题,但它无法应用主题中的粗体和斜体,几万个范围的绘制成本也没有测过。 + +**跳转后一秒内每帧重新对齐** 能让最后一个文件贴紧列表末端,但它也会把不是它发起的滚动拉回去,例如页内查找引起的滚动;而对其他目标,滚动锚定已经能让它们保持在顶部。 + +**在 Web Worker 中高亮** 能把分词完全移出主线程,包括重型语法的首次使用,但 Shiki 由 `ui-primitives` 中的共享高亮器持有;迁移它是影响所有使用方的另一项改动。 + +**由提供方私有缓存基准提交** 可以省去可选的 `baseSha` 字段,但会引入保留状态,而且没有一个知道变更请求何时不再被 watch 的所有者。 + +## Consequences + +打开 #7985 的主线程工作从 5.2 秒降到 0.5 秒,跳转文件、筛选、轮询和 Agent 回合不再产生长任务。代价是:浏览器的页内查找看不到读者尚未接近的文件中的行;滚动到慢语法(例如 C++)的文件时会在滚动中完成高亮,该语法首次使用时最多约 0.8 秒的主线程工作。最新状态之后基准提交有变化时,一次 diff 读取会多一次 compare 请求。 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml index ca48f70356..5736f23e73 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml @@ -18,11 +18,11 @@ en: 16c4ee08b65ead23 zh: df80d6e49982615b /agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations: - en: e112957ed8a48039 - zh: 37d63f9ea4968fb2 + en: 082e5a02b092b656 + zh: ca674a08323d8cc1 /agent-note-parallel-tool-call-execution-by-per-call-safety/verification: - en: 224b6838130c113f - zh: f3d7eb68ab5932fb + en: 20d0e1724ebc1247 + zh: baa89694cea135c8 /agent-note-parallel-tool-call-execution-by-per-call-safety/alternatives-considered: en: 17becc038bb7df7c zh: 673d9a9bdfa39edf diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md index 4eb497b1ff..03e35dba6b 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md @@ -60,13 +60,13 @@ Any shared state touched during execution must be concurrency-safe. This include `maxParallelToolCalls` is a positive AgentLoop deployment cap shared by every agent the factory creates. It defaults to `10`; `1` preserves serial execution. Exact fields and defaults live in the generated [configuration catalog](../../../../docs/config-catalog.md). -The shipped declarations are conservative. Web search, web fetch, filesystem read, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Filesystem writes and edits, bash tools, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. +The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md). -Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. +Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session. ## Verification -Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration. +Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration, and the working-directory service tests pin per-Session serialization of concurrent directory changes. Snapshot coverage pins the visible multi-call transcript: pending calls may overlap while completed results remain model-ordered. PTC mode coverage pins its serial boundary. No provider-backed e2e is required because scheduling is deterministic loop behavior. diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md index dbfa7cd684..38db00b5ff 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md @@ -60,13 +60,13 @@ Status: implemented `maxParallelToolCalls` 是 AgentLoop 的正整数部署上限,由工厂创建的所有 agent(智能体)共享。默认值为 `10`;`1` 保持串行执行。字段和默认值的精确定义见生成的[配置目录](../../../../docs/config-catalog.zh.md)。 -当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。文件系统写入与编辑、bash 工具、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。 +当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。 -文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。 +文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。 ## 验证 -单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。 +单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明,工作目录服务测试固定了按会话串行化并发目录变更。 快照测试固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。PTC mode 测试固定了其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。 diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml index b5373db47c..201593ebbe 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml @@ -9,8 +9,8 @@ en: 12ab239ab0c58e31 zh: c32874442ce66041 /agent-note-explicit-worktree-creation/decision: - en: 92782d5964d1a021 - zh: 37b385836e9ae2b9 + en: 571a2d4c5352170b + zh: aeb12b849c5f8d31 /agent-note-explicit-worktree-creation/alternatives-considered: en: 72d42e892a37b94c zh: 92a14a51c6a89c53 diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md index 33cabb9b8e..9facc68061 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md @@ -18,7 +18,7 @@ Git and directory creation use the mounted subprocess and sandbox providers with Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a branch merge policy or a task association database. -The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees. +The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Inspection trusts `git status` alone, as peer agent products do: edits to skip-worktree or assume-unchanged files are discarded with the checkout, because sparse checkout sets skip-worktree on every file outside its cone and inspecting those bits would retain every sparse checkout. A checkout whose administrative directory holds submodule repositories is retained; a committed embedded repository is not inspected, and Git's refusal of that removal settles the attempt as failed. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md index a3c7313ddd..bc9fc0670c 100644 --- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md +++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md @@ -18,7 +18,7 @@ Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用 离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有分支合并策略或任务关联数据库。 -服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。 +服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。检查与同类 Agent 产品一样只依据 `git status`:skip-worktree 或 assume-unchanged 文件的改动随检出目录一起丢弃,因为 sparse checkout 会给稀疏范围之外的每个文件设置 skip-worktree,检查这些标记会保留每个稀疏检出目录。管理目录中含子模块仓库的检出目录会保留;已提交的内嵌仓库不在检查范围内,Git 拒绝这类删除,本次尝试以失败结束。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。 ## Alternatives considered diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml index 32af5fd21a..db6139954a 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.i18n.yaml @@ -21,8 +21,8 @@ en: 8a9578bbc700c0bf zh: 8ee46e5ef1cf3972 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/authorization-loses-required-observation-or-an-accepted-credential-write: - en: 33312dc2b9813ef9 - zh: ba2fb5fac770e698 + en: c6b0d746185d0d3b + zh: a228633ecdf42800 /agent-note-keep-cleanup-dependencies-usable-until-consumers-finish/p0-findings/ssh-disables-cleanup-requests-before-dependent-process-cleanup-finishes: en: 85fb2b564bc40230 zh: 97c3e794124f8044 diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md index 22c7693e9b..cb7ad564cd 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.md @@ -36,7 +36,7 @@ A focused in-memory experiment using the actual Cordis and storage-domain implem ### Authorization loses required observation or an accepted credential write -**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts). +**Owners and evidence.** Authorization's [commit observer (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) is a caller-owned `ctx.on` effect. Its [commit operation (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts) awaits credential storage, while [success requires the observed update (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts). The account service [leaves committing attempts un-aborted and awaits their completion (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts). **Successful write, false failure.** Pause a credential write, dispose the account consumer, then complete the write and emit its update. The observer can auto-unsubscribe alongside the account's drain; Authorization then rejects with `NOT_COMMITTED` despite successful storage. Keep observation owned by the operation until its result settles, or acknowledge successful `session.commit` directly while giving legacy direct-write observation an explicit lifetime. A focused experiment using actual Cordis and Authorization with a deferred in-memory credential provider reproduced `NOT_COMMITTED` after the provider write succeeded; the complete browser sign-in path is source-traced. diff --git a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md index 17580f8578..fd5a6c3f45 100644 --- a/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md +++ b/.agents/notes/proposed/architecture/2026-10-09-cordis-cleanup-dependency-lifetimes.zh.md @@ -36,7 +36,7 @@ Status: proposed ### Authorization 丢失必需的提交观察或已接受的凭据写入 -**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`PlatformAccount`)](../../../../packages/credentials/deepseek-account-platform/src/index.ts)。 +**所有者与证据。** Authorization 的[提交观察器 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)是调用方拥有的 `ctx.on` effect。[提交操作 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)等待凭据存储,而[成功要求观察到更新 (`AuthorizationService.attempt`)](../../../../packages/credentials/authorization/src/index.ts)。账号服务[不会中止正在提交的尝试,并等待其完成 (`DeepSeekAccount`)](../../../../packages/credentials/deepseek-account/src/index.ts)。 **写入成功,却报告失败。** 暂停凭据写入,释放账号消费者,再完成写入并发出更新。观察器可以与账号的排空并发自动退订;随后 Authorization 即使存储成功也会以 `NOT_COMMITTED` 拒绝。应让操作拥有观察器直到结果确定,或直接确认成功的 `session.commit`,同时给旧式直接写入观察明确的生命周期。使用实际 Cordis 与 Authorization、配合延迟的内存凭据 provider 的实验,复现了 provider 写入成功后返回 `NOT_COMMITTED`;完整浏览器登录路径由源码追踪确认。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml new file mode 100644 index 0000000000..e921fbaeaf --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml @@ -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 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md new file mode 100644 index 0000000000..b01a462712 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md @@ -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. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md new file mode 100644 index 0000000000..ce9490648d --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md @@ -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 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml new file mode 100644 index 0000000000..d0ee532e45 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml @@ -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 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md new file mode 100644 index 0000000000..0e511c63a0 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md @@ -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. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md new file mode 100644 index 0000000000..1279f75c51 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md @@ -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 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。 diff --git a/.gitattributes b/.gitattributes index 2bead994d2..f6b77ce2c7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -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 diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 96b711a333..1fa22d5a13 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -54,7 +54,7 @@ flowchart LR cfg --> plugin_dsh_base_settings plugin_dsh_base_authorization["authorization
@deepseek-ai/dsh-authorization"] cfg --> plugin_dsh_base_authorization - plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account-platform"] + plugin_dsh_base_deepseek_account["deepseek-account
@deepseek-ai/dsh-deepseek-account"] cfg --> plugin_dsh_base_deepseek_account plugin_dsh_base_credentials["credentials
@deepseek-ai/dsh-credentials-local"] cfg --> plugin_dsh_base_credentials @@ -233,7 +233,7 @@ flowchart LR | `config-editor` | `@deepseek-ai/dsh-config-editor` | | `settings` | `@deepseek-ai/dsh-settings` | | `authorization` | `@deepseek-ai/dsh-authorization` | -| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account-platform` | +| `deepseek-account` | `@deepseek-ai/dsh-deepseek-account` | | `credentials` | `@deepseek-ai/dsh-credentials-local` | | `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` | | `session-persistence-jsonl` | `@deepseek-ai/dsh-session-persistence-jsonl` | diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index 311240e645..a7352b5dd7 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.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":"\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: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"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: \"\", 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"} diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index a3e4b09a4d..ac293e8017 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -289,6 +289,55 @@ describe('the shipped Web composition', () => { expect(ctx.agentPresets.defaultId).toBe('standard') }) + it.each(['standard', 'cordis', 'ptc'] as const)('keeps interruption disabled in %s with Team mode off or on', async (preset) => { + const handle = await ctx.agents.create({ + sessionId: SessionId(`preset-interrupt-${preset}`), + setup: agentCtx => ctx.agentPresets.mount(agentCtx, preset).then(() => undefined), + }) + try { + for (const enabled of [false, true]) { + await ctx.agentTeams.setEnabled(handle.agent, enabled) + const names = toolNames(ctx, handle.agent) + expect(names).not.toContain('interrupt_agent') + expect(names).toEqual(expect.arrayContaining(['send_message', 'list_agents', 'wait_agent'])) + } + } finally { + await handle.dispose() + } + }) + + it.each(['standard', 'cordis', 'ptc'] as const)('restores interruption through a complete %s declaration override', async (preset) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-preset-interrupt-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const declaration = composeEntries([webPatches('interrupt migration')]) + .find(row => row.id === `preset-${preset}`)!.config as { + id: string + order: number + plugins: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[] + } + const configured = await bootWeb(root, [{ + id: `preset-${preset}`, + config: { + ...declaration, + plugins: composeEntries([[{ insert: declaration.plugins }, { + id: 'tool-subagent-control', config: { interrupt: true }, + }]]), + }, + }]) + try { + const handle = await configured.agents.create({ + sessionId: SessionId(`preset-interrupt-enabled-${preset}`), + setup: agentCtx => configured.agentPresets.mount(agentCtx, preset).then(() => undefined), + }) + try { + expect(toolNames(configured)).not.toContain('interrupt_agent') + expect(toolNames(configured, handle.agent)).toEqual(expect.arrayContaining([ + 'interrupt_agent', 'send_message', 'list_agents', 'wait_agent', + ])) + } finally { await handle.dispose() } + } finally { await configured.fiber.dispose() } + }) + it('composes the full agent from `standard`', async () => { const handle = await ctx.agents.create({ sessionId: SessionId('preset-standard'), @@ -302,7 +351,7 @@ describe('the shipped Web composition', () => { // depend on ripgrep being present on the machine. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([ 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', - 'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', + 'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'skill', 'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search', @@ -599,9 +648,7 @@ describe('the shipped Web composition', () => { expect(codePointLength(text) - codePointLength(path) + 256, file).toBeLessThan(8192) } - // The persona is `standard`'s, pinned verbatim so the two declarations - // cannot drift apart: tool descriptions and the skill catalog carry - // every creation-mode instruction. + // Creator adds its DSH customization intent to the shared coding persona. const standard = await ctx.agents.create({ sessionId: SessionId('preset-cordis-standard-persona'), setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), @@ -611,7 +658,30 @@ describe('the shipped Web composition', () => { .filter(section => section.name.startsWith('deployment:persona-')) const cordisPersona = await persona(handle.agent) expect(cordisPersona.map(section => section.name)).toEqual(['deployment:persona-prefix', 'deployment:persona-suffix']) - expect(cordisPersona).toEqual(await persona(standard.agent)) + const standardPersona = await persona(standard.agent) + const standardPrefix = standardPersona.find(section => section.name === 'deployment:persona-prefix') + expect(standardPrefix?.text).toMatch(/^You are a coding agent powered by the .+ model\.$/u) + expect(cordisPersona).toEqual(standardPersona.map(section => section.name === 'deployment:persona-prefix' + ? { ...section, text: `${section.text} You help the user customize DeepSeek Harness itself.` } + : section)) + const definition = composeEntries([webPatches('Creator persona')]) + .find(row => row.id === 'preset-cordis')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition + const unregister = await ctx.agentPresets.register({ + ...definition, id: 'cordis-coding-only', + plugins: definition.plugins.map(row => row.id === 'persona' + ? { ...row, config: { prefix: standardPrefix!.text } } + : row), + }) + try { + const codingOnly = await ctx.agents.create({ + sessionId: SessionId('preset-cordis-coding-only'), + setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis-coding-only').then(() => undefined), + }) + try { + expect(ctx.tools.schemas(handle.agent).toSorted((left, right) => left.name.localeCompare(right.name))) + .toEqual(ctx.tools.schemas(codingOnly.agent).toSorted((left, right) => left.name.localeCompare(right.name))) + } finally { await codingOnly.dispose() } + } finally { await unregister() } } finally { await standard.dispose() } @@ -865,6 +935,157 @@ describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surfac }, 120_000) }) +describe('the standard preset documentation skill', () => { + it.for([false, true])('loads the packaged skill without adding tools (badge skill: %s)', async (withBadge: boolean) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-standard-doc-')) + vi.stubEnv('DSH_HOME', join(root, 'home')) + vi.stubEnv('DSH_AGENTS_HOME', join(root, 'agents-home')) + vi.stubEnv('DSH_BUNDLED_SKILL_DIR', join(root, 'bundled-skills')) + let docCtx: Context | undefined + try { + const standard = composeEntries([webPatches('standard documentation')]) + .find(row => row.id === 'preset-standard')!.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition + docCtx = await bootWeb(root, [ + { id: 'skill-badge', disabled: !withBadge }, + { insert: [{ + id: 'preset-standard-without-doc', name: '@deepseek-ai/dsh-agent-preset', + config: { + ...standard, id: 'standard-without-doc', + plugins: standard.plugins.map(row => row.id === 'skill-filesystem' + ? { ...row, config: { customSkillDirs: [] } } + : row), + }, + }] }, + ]) + const testCtx = docCtx + const adapter = new MinimalCompactionAdapter() + testCtx.llm.registerAdapter(['standard-doc-test'], adapter) + const baseline = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-baseline'), meta: { cwd: root }, + agentOptions: { provider: 'standard-doc-test', model: 'standard-doc-test' }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard-without-doc').then(() => undefined), + }) + const standardAgent = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-current'), meta: { cwd: root }, + agentOptions: { provider: 'standard-doc-test', model: 'standard-doc-test' }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), + }) + const baselineSkills = await testCtx.skills.list({ cwd: root, scope: baseline.agent }) + const skills = await testCtx.skills.list({ cwd: root, scope: standardAgent.agent }) + expect(skills.map(skill => skill.name).sort()) + .toEqual([...baselineSkills.map(skill => skill.name), 'dsh-doc'].sort()) + const definition = await testCtx.skills.get('dsh-doc', { cwd: root, scope: standardAgent.agent }) + expect(definition?.path).toBe(await realpath(join(REPO_ROOT, 'packages/preset/agent-preset/skills/dsh-doc/SKILL.md'))) + if (definition === undefined) throw new Error('standard has no packaged dsh-doc skill') + const creator = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-creator'), meta: { cwd: root }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined), + }) + expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path) + const schemas = testCtx.tools.schemas(standardAgent.agent) + expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent)) + expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_list') + expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_query') + for (const handle of [baseline, standardAgent]) { + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply ready.' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + } + const baselineCatalogs = baseline.agent.session.snapshotEvents().flatMap(event => + event.type === 'user/message' && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + const catalogs = standardAgent.agent.session.snapshotEvents().flatMap(event => + event.type === 'user/message' && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + expect(baselineCatalogs).toHaveLength(baselineSkills.length > 0 ? 1 : 0) + expect(catalogs).toHaveLength(1) + expect(catalogs[0]?.source).toMatchObject({ + entries: skills.map(skill => ({ name: skill.name, description: skill.description })), + }) + const requests = adapter.requests.filter(request => request.purpose === undefined) + expect(requests).toHaveLength(2) + expect(requests[0]?.tools).toEqual(requests[1]?.tools) + const catalogSize = (messages: typeof catalogs) => { + const text = messages.flatMap(message => message.content.flatMap(block => block.type === 'text' ? [block.text] : [])).join('') + return { + utf8Bytes: Buffer.byteLength(text, 'utf8'), codePoints: Array.from(text).length, + heuristicTokens: messages.reduce((total, message) => total + testCtx.tokenMeter.estimateMessage(message), 0), + } + } + const beforeCatalog = catalogSize(baselineCatalogs) + const afterCatalog = catalogSize(catalogs) + expect({ + utf8Bytes: afterCatalog.utf8Bytes - beforeCatalog.utf8Bytes, + codePoints: afterCatalog.codePoints - beforeCatalog.codePoints, + heuristicTokens: afterCatalog.heuristicTokens - beforeCatalog.heuristicTokens, + }).toEqual({ utf8Bytes: 500, codePoints: 500, heuristicTokens: 125 }) + const requestTexts = requests.flatMap(request => request.messages.flatMap(message => + message.content.flatMap(block => block.type === 'text' ? [block.text] : []))) + expect(requestTexts.some(text => text.includes(definition.content))).toBe(false) + expect(standardAgent.agent.session.snapshotEvents().filter(event => event.type === 'tool/call')).toEqual([]) + const profileManifest = join(root, 'profiles/spec/package.json') + const before = await readFile(profileManifest, 'utf8') + const loaded = await executeToolFixture(testCtx, { + agent: standardAgent.agent, callId: ToolCallId('standard-doc-load'), + name: 'skill', arguments: { name: 'dsh-doc' }, signal: new AbortController().signal, + }) + expect(loaded.isError).toBe(false) + expect(loaded.content.some(block => block.type === 'text' && block.text.includes(definition.content))).toBe(true) + expect(testCtx.tools.schemas(standardAgent.agent)).toEqual(schemas) + expect(await readFile(profileManifest, 'utf8')).toBe(before) + } finally { + try { await docCtx?.fiber.dispose() } finally { + vi.unstubAllEnvs() + await rm(root, { recursive: true, force: true }) + } + } + }) + it('prefers project dsh-doc overrides while packaged guidance wins over user skills', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-standard-doc-priority-')) + const home = join(root, 'home') + const agentsHome = join(root, 'agents-home') + const workspace = join(root, 'workspace') + const projectAgents = join(root, 'project-agents') + const projectDsh = join(root, 'project-dsh') + vi.stubEnv('DSH_HOME', home) + vi.stubEnv('DSH_AGENTS_HOME', agentsHome) + vi.stubEnv('DSH_BUNDLED_SKILL_DIR', join(root, 'bundled-skills')) + let priorityCtx: Context | undefined + try { + await mkdir(workspace) + for (const project of [projectAgents, projectDsh]) await mkdir(join(project, '.git'), { recursive: true }) + for (const [directory, description] of [ + [join(home, 'skills'), 'User DSH skill'], + [join(agentsHome, 'skills'), 'User agents skill'], + [join(projectAgents, '.agents/skills'), 'Project agents skill'], + [join(projectDsh, '.agents/skills'), 'Lower priority project skill'], + [join(projectDsh, '.dsh/skills'), 'Project DSH skill'], + ] as const) { + const skill = join(directory, 'dsh-doc') + await mkdir(skill, { recursive: true }) + await writeFile(join(skill, 'SKILL.md'), `---\nname: dsh-doc\ndescription: ${description}\n---\n\n${description}\n`) + } + priorityCtx = await bootWeb(root) + const testCtx = priorityCtx + const handle = await testCtx.agents.create({ + sessionId: SessionId('standard-doc-priority'), meta: { cwd: workspace }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'standard').then(() => undefined), + }) + for (const [cwd, path] of [ + [workspace, join(REPO_ROOT, 'packages/preset/agent-preset/skills/dsh-doc/SKILL.md')], + [projectAgents, join(projectAgents, '.agents/skills/dsh-doc/SKILL.md')], + [projectDsh, join(projectDsh, '.dsh/skills/dsh-doc/SKILL.md')], + ] as const) { + const skills = await testCtx.skills.list({ cwd, scope: handle.agent }) + expect(skills.filter(skill => skill.name === 'dsh-doc')).toHaveLength(1) + expect((await testCtx.skills.get('dsh-doc', { cwd, scope: handle.agent }))?.path).toBe(await realpath(path)) + } + } finally { + try { await priorityCtx?.fiber.dispose() } finally { + vi.unstubAllEnvs() + await rm(root, { recursive: true, force: true }) + } + } + }) +}) + describe('a user preset declared from the shipped cordis rows', () => { /** The JSON text a `cordis_inspect_*` result renders. */ function resultText(result: { content: ReadonlyArray<{ type: string; text?: string }> }): string { diff --git a/apps/desktop-host/tests/platform-session.spec.ts b/apps/desktop-host/tests/platform-session.spec.ts index 73c2322621..35ea560923 100644 --- a/apps/desktop-host/tests/platform-session.spec.ts +++ b/apps/desktop-host/tests/platform-session.spec.ts @@ -1,5 +1,5 @@ -import { Context } from '@deepseek-ai/cordis' -import { DeepSeekAccount, type AccountView, type PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import { Context, Service } from '@deepseek-ai/cordis' +import type { DeepSeekAccount, AccountView, AccountUpdate, PlatformSession } from '@deepseek-ai/dsh-deepseek-account' import { expect, it } from 'vitest' import { installPlatformSessionPublisher } from '../src/platform-session.ts' @@ -8,31 +8,21 @@ const state: AccountView = { links: { usageUrl: 'https://platform.example/usage', topUpUrl: 'https://platform.example/top_up' }, } -class Account extends DeepSeekAccount { - getDeviceIdentity = async () => ({ osVersion: 'test-os' }) +class Account extends Service implements Pick { + constructor(ctx: Context) { super(ctx, 'deepseekAccount') } fail = false identityChangesRequested = false ended = Promise.withResolvers() reading = Promise.withResolvers() finished = Promise.withResolvers() read: () => Promise = async () => ({ origin: 'https://platform.example', userId: null, token: 'test' }) - override async getState() { return state } - override async getProfile() { return null } - override async getBalance() { return null } - override async getUnnotifiedBonuses() { return null } - override async ackBonusNotified() { return false } - override async startSignIn() { return state } - override async cancelSignIn() { return state } - override async signOut() { return state } - override async rejectToken() {} - override async resolveToken() { return undefined } - override async getPlatformSession() { this.reading.resolve(undefined); return this.read() } - override async *watch(signal: AbortSignal, includeIdentityChanges = false) { + async getPlatformSession() { this.reading.resolve(undefined); return this.read() } + async *watch(signal: AbortSignal, includeIdentityChanges = false): AsyncIterable { this.identityChangesRequested = includeIdentityChanges const abort = () => { this.ended.resolve(undefined) } signal.addEventListener('abort', abort, { once: true }) try { - yield state + yield { type: 'snapshot', state } await this.ended.promise if (this.fail) throw new Error('fixture subscription failure') } finally { diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index d36cd62277..7b4f37e1ad 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: 1f59637852e162b4 - zh: b1530a1af195cb92 + en: 37d36f8d57214336 + zh: ceb50c0fa866eb24 /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 @@ -57,8 +57,8 @@ en: f1302ed4a3ab58bb zh: cb53b9b349815028 /deepseek-harness-desktop/updates: - en: 67bf0a18faa7aa76 - zh: 782e14ce62bb939f + en: 8b0b9efeb83727ef + zh: 5ee95de48ceab392 /deepseek-harness-desktop/updates/local-desktop-settings: en: dbe57394894b7368 zh: a3bb788c2ce631a4 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 1e9c3a595d..ffe4f5b520 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -49,7 +49,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar. -Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account-platform/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. +Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection. A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice. @@ -278,11 +278,11 @@ Ordinary update dialogs use an isolated shell-origin WebContentsView inside the Ordinary update dialogs, the Windows first-close notice, and mandatory-update documents share the UI design tokens bundled with the shell. Before displaying a card, each document resolves Electron's application theme through `prefers-color-scheme` and updates its dark-theme attribute when the palette changes. Welcome and update documents use the same initialization script. Explicit light/dark preferences and system appearance share this path; the isolated document keeps its background transparent, and dark mode adds a 1 CSS px token-based inset outline without changing the card size; light mode has no outline. -Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. +Packaged applications check fixed Nightly asynchronously at startup. Ordinary polling uses a ten-minute base interval with independently sampled ±20% jitter. Each check failure doubles the base delay up to one hour; success resets it. The randomized delay is bounded by that cap and starts after all joined callers settle. Foreground and system-resume checks respect the same monotonic deadline; the localized Check for Updates menu item, including in the Windows caption's Application menu, runs immediately and joins an in-flight check. A newly received mandatory policy also requests an immediate feed check. Automatic checks never open dialogs or download packages. Manual checks display checking, failure, or no-update feedback with the installed version. During downloading or verification, **Check for Updates…** shows the state at the time the dialog opens; it does not refresh as the operation advances. Downloading explains that the app remains usable; verification has no download-completion instruction. Closing the status dialog leaves the update running. If any ordinary shell prompt is already open, the action focuses it without replacing its pending decision; close it before requesting update status. Failure to create the status surface uses a native dialog with the same status text and controls; presentation failures are logged without changing the update operation. Ordinary update dialogs fade in and out in place; consecutive prompts replace the card content and reset its scroll position while retaining the dark translucent backdrop without blurring the parent page. `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` configures the ordinary base interval, and `DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` configures the cap; both accept integer milliseconds from 1000 through 2147483647, with the cap at least the interval. An omitted cap defaults to the larger of one hour and the interval. `DSH_DESKTOP_UPDATE_CHECK_JITTER` sets the fractional jitter from 0 through 1, defaulting to `0.2`; the final delay is at least one second and never exceeds the cap. These settings do not change mandatory-policy polling or authorize download retries. -The lower-left account row displays localized availability, a spinner with download percentage, verification, readiness, or a persistent red retry action with an accessible tooltip. This Web-embedded copy follows the active in-application language; native dialogs use the Desktop shell locale. The collapsed sidebar shows a dot on its top expand button. Connection status takes priority. Selecting an available release starts downloading immediately. Successful preparation automatically opens a shell-owned restart confirmation; closing it retains readiness without reopening the dialog. Selecting the ready entry opens confirmation again. Running agents, queued input, and running or stopping jobs trigger an interruption warning in that confirmation. API requests alone do not trigger the warning. After approval, the Host locks new requests, drains admitted requests, and rechecks tasks, including work created by an admitted write. A drain that exceeds the control-request deadline refuses installation and unlocks admission. Unknown task status, newly started work without interruption approval, or unsuccessful graceful teardown prevents installation. The Host exits as soon as it acknowledges completed teardown, so handles left open by plugins do not count against the graceful deadline. Ordinary quit asks about interruptible work as described under Closing the window and quitting, then hides the product window before stopping the Host, ignores new focus requests during teardown, and never installs an update. The next launch reconciles the version-bound runtime through the existing startup and recovery path. +The lower-left account row displays localized availability, a spinner with download percentage, verification, readiness, or a persistent red retry action with an accessible tooltip. This Web-embedded copy follows the active in-application language; native dialogs use the Desktop shell locale. The collapsed sidebar shows a dot on its top expand button. Connection status takes priority. Selecting an available release starts downloading immediately. Selecting its download percentage opens the same status dialog as Check for Updates, explaining that downloading runs in the background and the app remains usable. Successful preparation automatically opens a shell-owned restart confirmation; closing it retains readiness without reopening the dialog. Selecting the ready entry opens confirmation again. Running agents, queued input, and running or stopping jobs trigger an interruption warning in that confirmation. API requests alone do not trigger the warning. After approval, the Host locks new requests, drains admitted requests, and rechecks tasks, including work created by an admitted write. A drain that exceeds the control-request deadline refuses installation and unlocks admission. Unknown task status, newly started work without interruption approval, or unsuccessful graceful teardown prevents installation. The Host exits as soon as it acknowledges completed teardown, so handles left open by plugins do not count against the graceful deadline. Ordinary quit asks about interruptible work as described under Closing the window and quitting, then hides the product window before stopping the Host, ignores new focus requests during teardown, and never installs an update. The next launch reconciles the version-bound runtime through the existing startup and recovery path. If task teardown fails after confirmed Host exit, installation is refused and the shell restores the current-version Host before allowing another restart confirmation. Installer launch failure after a clean Host stop uses the same recovery. After the replacement Host authenticates, the shell reloads the existing application URL so the Web page obtains its current port, cookie, and boot injections; page-load failure opens native fatal recovery. An unconfirmed process exit never permits a replacement Host. The downloaded target remains available for retry. A known mandatory policy remains blocking throughout recovery; unsuccessful Host restoration opens the native fatal-recovery dialog. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 96c44ba1e2..a6c2493fbc 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -49,7 +49,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一 Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。 -Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account-platform/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 +Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。 账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。 @@ -278,11 +278,11 @@ macOS 在安装准备阶段等待产品主窗口退出全屏,再显示重启 普通更新弹窗、Windows 首次关闭提示和强更文档共用随壳打包的 UI design token。各文档在显示卡片前通过 `prefers-color-scheme` 解析 Electron 的应用主题,配色变化时同步暗色主题属性。欢迎页与更新文档复用同一初始化脚本。明确选择浅色/暗色及跟随系统共用此路径,隔离文档保持透明背景,仅暗色模式以基于 token 的 1 CSS px 内描边区分卡片,不改变尺寸;浅色模式不描边。 -打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。 +打包应用在启动后异步检查固定 Nightly。常规轮询以十分钟为基础间隔,每次独立采样 ±20% 的随机抖动。每次检查失败将基础延迟翻倍,上限为一小时;成功后重置。随机延迟不超过该上限,并从全部复用调用结算后开始计时。本地化的“检查更新…”菜单项(Windows 可从顶栏的“应用”菜单进入)立即执行,并复用正在进行的检查。回到前台和系统恢复时遵守相同的单调时钟截止时间。新收到的强更策略也会立即请求检查更新清单。自动检查从不弹窗或下载安装包。手动检查显示正在检查、失败或包含已安装版本号的无更新反馈。下载或校验期间,“**检查更新…**”显示打开提示时的状态,不随操作进展刷新。下载提示说明可以继续使用应用;校验提示不再包含下载完成的说明。关闭状态提示不影响更新。若已有普通壳弹窗,点击会聚焦该弹窗,保留其待确认操作;关闭后可再次查看更新状态。状态界面创建失败时,使用相同状态文案和按钮的原生弹窗兜底;展示失败仅记日志,不改变更新操作。常规更新弹窗原位渐入渐出;连续弹窗替换卡片内容并重置其滚动位置,保留黑色半透明蒙层,不模糊父页面。 `DSH_DESKTOP_UPDATE_CHECK_INTERVAL_MS` 配置常规基础间隔,`DSH_DESKTOP_UPDATE_CHECK_MAX_BACKOFF_MS` 配置上限;两者均接受 1000 至 2147483647 的整数毫秒数,且上限不能小于间隔。省略上限时取一小时与间隔中的较大值。`DSH_DESKTOP_UPDATE_CHECK_JITTER` 配置 0 至 1 的抖动比例,默认 `0.2`;最终延迟至少一秒,且不超过上限。这些配置不改变强更策略轮询,也不授权下载重试。 -左下角账户行显示本地化的更新可用状态、加载图标与下载百分比、验证、就绪状态,或带可访问提示的持久红色重试操作。嵌入 Web 界面的文案跟随应用内当前语言;原生弹窗使用 Desktop 壳语言。侧栏收起时,顶部展开按钮显示圆点。连接状态优先展示。选择可用版本即开始下载。准备成功后自动打开壳拥有的重启确认;关闭后保留就绪状态,不重复弹窗。选择就绪入口可再次打开确认。运行中的 agent、排队输入,以及运行中或停止中的后台任务都会在该确认中触发中断警告。仅有 API 请求不会触发警告。用户批准后,Host 锁定新请求,等待已接收的请求结束,再检查任务,包括已接收写操作创建的工作。等待超过控制请求截止时间时,拒绝安装并解除准入锁。任务状态未知、未获中断授权的新任务,或未成功完成正常收尾,都会阻止安装。Host 确认收尾完成后立即退出,插件遗留的打开句柄不会占用正常收尾期限。常规退出先按"关闭窗口与退出"一节所述询问可中断的工作,再在停止 Host 前隐藏产品窗口,在收尾期间忽略新的聚焦请求,且从不安装更新。下次启动通过已有的启动与恢复流程校准版本绑定的运行时。 +左下角账户行显示本地化的更新可用状态、加载图标与下载百分比、验证、就绪状态,或带可访问提示的持久红色重试操作。嵌入 Web 界面的文案跟随应用内当前语言;原生弹窗使用 Desktop 壳语言。侧栏收起时,顶部展开按钮显示圆点。连接状态优先展示。选择可用版本即开始下载。点击下载百分比会打开与“检查更新”相同的状态提示,说明更新正在后台下载,可以继续使用应用。准备成功后自动打开壳拥有的重启确认;关闭后保留就绪状态,不重复弹窗。选择就绪入口可再次打开确认。运行中的 agent、排队输入,以及运行中或停止中的后台任务都会在该确认中触发中断警告。仅有 API 请求不会触发警告。用户批准后,Host 锁定新请求,等待已接收的请求结束,再检查任务,包括已接收写操作创建的工作。等待超过控制请求截止时间时,拒绝安装并解除准入锁。任务状态未知、未获中断授权的新任务,或未成功完成正常收尾,都会阻止安装。Host 确认收尾完成后立即退出,插件遗留的打开句柄不会占用正常收尾期限。常规退出先按"关闭窗口与退出"一节所述询问可中断的工作,再在停止 Host 前隐藏产品窗口,在收尾期间忽略新的聚焦请求,且从不安装更新。下次启动通过已有的启动与恢复流程校准版本绑定的运行时。 若任务收尾失败但已确认 Host 退出,安装会被拒绝,壳会在允许再次确认重启前恢复当前版本的 Host。Host 正常停止后的安装器启动失败使用同一恢复路径。替代 Host 启动并完成认证后,壳重新加载原有应用地址,让 Web 页面获取当前端口、Cookie 和启动注入数据;页面加载失败时打开原生致命故障恢复弹窗。未确认进程退出时,绝不允许启动替代 Host。已下载目标保留以供重试。已知强更策略在恢复过程中继续阻塞;Host 恢复失败打开原生致命故障恢复弹窗。 diff --git a/apps/desktop/src/account-backend.ts b/apps/desktop/src/account-backend.ts index 19ae3fe796..7150655c48 100644 --- a/apps/desktop/src/account-backend.ts +++ b/apps/desktop/src/account-backend.ts @@ -117,7 +117,14 @@ export function desktopAccountBackend(origin: string, invoke: AccountInvoke, coo } if (frame.streamId === expiryStreamId && frame.type === 'item' && frame.value === 'session-expired') { expired(); return } if (frame.streamId !== streamId) throw new Error('desktop account: unexpected stream') - if (frame.type === 'item') listener(accountView(frame.value)) + if (frame.type === 'item') { + const update = frame.value + if (typeof update !== 'object' || update === null || !('type' in update) + || (update.type !== 'snapshot' && update.type !== 'credentials-changed') || !('state' in update)) { + throw new Error('desktop account: invalid stream update') + } + listener(accountView(update.state)) + } else socket?.close() } catch { socket?.close() } }) diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index 050548e879..3e2db64e24 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -138,6 +138,8 @@ export const en = { updateClose: 'Close', updateAcknowledge: 'OK', updateLater: 'Update later', + updateDownloadInProgress: 'Downloading update', + updateDownloadDetail: 'The update is downloading in the background. You can continue using the app.', updateDownloading: 'Downloading {percent}%…', updateVerifying: 'Verifying update files…', updateInstalling: 'Preparing to restart…', @@ -331,6 +333,8 @@ export const zh = { updateClose: '关闭', updateAcknowledge: '确定', updateLater: '稍后更新', + updateDownloadInProgress: '正在下载更新', + updateDownloadDetail: '更新正在后台下载,你可以继续使用应用。', updateDownloading: '正在下载 {percent}%…', updateVerifying: '正在校验更新文件…', updateInstalling: '正在准备重启…', @@ -522,6 +526,8 @@ export const ja = { updateClose: '閉じる', updateAcknowledge: 'OK', updateLater: '後でアップデート', + updateDownloadInProgress: 'アップデートをダウンロード中', + updateDownloadDetail: 'アップデートをバックグラウンドでダウンロードしています。アプリは引き続き使用できます。', updateDownloading: 'ダウンロード中 {percent}%…', updateVerifying: 'アップデートファイルを検証中…', updateInstalling: '再起動の準備中…', @@ -713,6 +719,8 @@ export const es = { updateClose: 'Cerrar', updateAcknowledge: 'OK', updateLater: 'Actualizar más tarde', + updateDownloadInProgress: 'Descargando actualización', + updateDownloadDetail: 'La actualización se está descargando en segundo plano. Puede seguir usando la aplicación.', updateDownloading: 'Descargando {percent}%…', updateVerifying: 'Verificando archivos de actualización...', updateInstalling: 'Preparándose para reiniciar…', @@ -904,6 +912,8 @@ export const fr = { updateClose: 'Fermer', updateAcknowledge: 'OK', updateLater: 'Mettre à jour plus tard', + updateDownloadInProgress: 'Téléchargement de la mise à jour', + updateDownloadDetail: 'La mise à jour se télécharge en arrière-plan. Vous pouvez continuer à utiliser l’application.', updateDownloading: 'Téléchargement de {percent}%…', updateVerifying: 'Vérification des fichiers de mise à jour…', updateInstalling: 'Préparation du redémarrage…', @@ -1095,6 +1105,8 @@ export const de = { updateClose: 'Schließen', updateAcknowledge: 'OK', updateLater: 'Später aktualisieren', + updateDownloadInProgress: 'Update wird heruntergeladen', + updateDownloadDetail: 'Das Update wird im Hintergrund heruntergeladen. Sie können die App weiter verwenden.', updateDownloading: '{percent}% wird heruntergeladen…', updateVerifying: 'Aktualisierungsdateien werden überprüft…', updateInstalling: 'Neustart wird vorbereitet…', @@ -1286,6 +1298,8 @@ export const ru = { updateClose: 'Закрыть', updateAcknowledge: 'OK', updateLater: 'Обновить позже', + updateDownloadInProgress: 'Загрузка обновления', + updateDownloadDetail: 'Обновление загружается в фоновом режиме. Вы можете продолжать пользоваться приложением.', updateDownloading: 'Загрузка {percent}%…', updateVerifying: 'Проверка файлов обновлений…', updateInstalling: 'Подготовка к перезапуску…', @@ -1477,6 +1491,8 @@ export const pt = { updateClose: 'Fechar', updateAcknowledge: 'OK', updateLater: 'Atualizar mais tarde', + updateDownloadInProgress: 'Baixando atualização', + updateDownloadDetail: 'A atualização está sendo baixada em segundo plano. Você pode continuar usando o aplicativo.', updateDownloading: 'Baixando {percent}%…', updateVerifying: 'Verificando arquivos de atualização…', updateInstalling: 'Preparando para reiniciar…', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9a08349620..8f9cd823a5 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1012,6 +1012,21 @@ async function main(): Promise { if (authenticationOperation !== undefined) { policyAuth?.focus(); updateDialog.focus() } + if (!isMandatory() && (updates.state.phase === 'downloading' || updates.state.phase === 'verifying')) { + if (updateDialog.isOpen) { + updateDialog.focus() + return Promise.resolve() + } + const options = { type: 'info' as const, title: locale.messages.updateCheckTitle, + message: updates.state.phase === 'downloading' ? locale.messages.updateDownloadInProgress : locale.messages.updateVerifying, + detail: updates.state.phase === 'downloading' ? locale.messages.updateDownloadDetail : '', buttons: [locale.messages.updateClose], cancelId: 0, + } + return ordinaryMessageBox(options).then(() => {}).catch(async (error: unknown) => { + console.error(error) + try { await dialog.showMessageBox(options) } + catch (nativeError) { console.error(nativeError) } + }) + } let failedOperation: 'check' | 'download' | 'install' = 'check' promptOperation ??= Promise.resolve().then(async () => { if (manual) updateJournal?.action('check-requested') diff --git a/apps/desktop/src/mandatory-update-policy.ts b/apps/desktop/src/mandatory-update-policy.ts index 6c65da3a68..44777281ab 100644 --- a/apps/desktop/src/mandatory-update-policy.ts +++ b/apps/desktop/src/mandatory-update-policy.ts @@ -1,7 +1,8 @@ /** Mandatory-update policy, independent of local business traffic and updater artifacts. */ import { valid } from 'semver' -import { platformClientHeaders, type AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import { platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata' /** Installed release identity; no field is supplied by a renderer. */ export interface DesktopPolicyIdentity { diff --git a/apps/desktop/src/platform-view.ts b/apps/desktop/src/platform-view.ts index daf455ed09..7cc85e8cf6 100644 --- a/apps/desktop/src/platform-view.ts +++ b/apps/desktop/src/platform-view.ts @@ -2,7 +2,8 @@ import type { EventEmitter } from 'node:events' import { createHash, randomUUID } from 'node:crypto' import { WebContentsView, session, shell, type Session, type View, type WebFrameMain } from 'electron' -import { mergePlatformCookies, platformClientHeaders, type PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account' +import { mergePlatformCookies, platformClientHeaders } from '@deepseek-ai/dsh-deepseek-account/client-metadata' import { desktopClientMetadata } from './client-metadata.ts' import { PLATFORM_IPC, type PlatformLocale } from './platform-ipc.ts' diff --git a/apps/desktop/tests/account-backend.spec.ts b/apps/desktop/tests/account-backend.spec.ts index ffdc59d340..54d6eea798 100644 --- a/apps/desktop/tests/account-backend.spec.ts +++ b/apps/desktop/tests/account-backend.spec.ts @@ -45,7 +45,12 @@ it('does not replay an expiry reason from an account snapshot', () => { expect(accountView({ ...state, signOutReason: 'expired' })).toEqual(state) }) -it('receives live expiry separately from account snapshots', async () => { +it.each([ + ['snapshot', 'invalid'], + ['credentials-changed', 'invalid'], + ['snapshot', ['snapshot']], + ['credentials-changed', ['credentials-changed']], +] as const)('receives %s state updates separately from live expiry and rejects type %j', async (type, invalidType) => { const server = new WebSocketServer({ host: '127.0.0.1', port: 0 }) await once(server, 'listening') onTestFinished(async () => { @@ -61,8 +66,9 @@ it('receives live expiry separately from account snapshots', async () => { links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } const received = Promise.withResolvers() const backend = desktopAccountBackend(`http://127.0.0.1:${address.port}`, () => Promise.resolve(snapshot), 'dsh-auth-fixture=signed') + const failed = vi.fn() const stop = backend.watch( - (value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, vi.fn(), expired, onAnalyticsEnabledChanged, + (value) => { expect(value).toEqual(snapshot); received.resolve(undefined) }, failed, expired, onAnalyticsEnabledChanged, ) onTestFinished(stop) const [, upgrade] = await connected as [unknown, IncomingMessage] @@ -78,7 +84,7 @@ it('receives live expiry separately from account snapshots', async () => { if (streams.size === 3) opened.resolve(undefined) }) await opened.promise - socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: snapshot })) + socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type, state: snapshot } })) await received.promise socket.send(JSON.stringify({ type: 'item', streamId: streams.get('productAnalytics/watchPolicy'), value: true })) await vi.waitFor(() => { expect(onAnalyticsEnabledChanged).toHaveBeenLastCalledWith(true) }) @@ -91,5 +97,7 @@ it('receives live expiry separately from account snapshots', async () => { expect(expired).not.toHaveBeenCalled() socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watchExpiry'), value: 'session-expired' })) await vi.waitFor(() => { expect(expired).toHaveBeenCalledOnce() }) + socket.send(JSON.stringify({ type: 'item', streamId: streams.get('account/watch'), value: { type: invalidType, state: snapshot } })) + await vi.waitFor(() => { expect(failed).toHaveBeenCalledOnce() }) stop() }) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 8c58dec463..17e16cec09 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -2259,7 +2259,23 @@ describe('desktop main startup', () => { const action = invoke(DESKTOP_IPC.updatesOpen, 'app') await started.promise const repeated = invoke(DESKTOP_IPC.updatesOpen, 'app') - expect(harness.dialog.showMessageBox).not.toHaveBeenCalled() + await repeated + expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: en.updateDownloadInProgress, detail: en.updateDownloadDetail, + })) + harness.dialog.showMessageBox.mockClear() + const checks = harness.updateCheck.mock.calls.length + const check = applicationMenuItems().find(item => item.label === en.checkUpdatesMenu)!.click as () => void + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: en.updateDownloadInProgress, detail: en.updateDownloadDetail, buttons: [en.updateClose], + })) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + harness.shellDialog.isOpen = true + check() + expect(harness.shellDialog.focus).toHaveBeenCalled() + expect(harness.dialog.showMessageBox).toHaveBeenCalledOnce() + harness.shellDialog.isOpen = false expect(harness.updateDownload).toHaveBeenCalledExactlyOnceWith('1.0.1-nightly.1', 0) expect(harness.updateInstall).not.toHaveBeenCalled() downloading.resolve({ phase: 'ready', version: '1.0.1-nightly.1' }) @@ -2269,6 +2285,60 @@ describe('desktop main startup', () => { expect(harness.updateInstall).toHaveBeenCalledOnce() }) + it.each(['downloading', 'verifying'] as const)('explains %s when checking from the menu without another update operation', async (phase) => { + await readyForUpdate() + harness.updateState = { phase, version: '1.0.1-nightly.1', percent: 21 } + const checks = harness.updateCheck.mock.calls.length + const check = applicationMenuItems().find(item => item.label === en.checkUpdatesMenu)!.click as () => void + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ + message: phase === 'downloading' ? en.updateDownloadInProgress : en.updateVerifying, + detail: phase === 'downloading' ? en.updateDownloadDetail : '', buttons: [en.updateClose], cancelId: 0, + })) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + check() + await vi.waitFor(() => { expect(harness.dialog.showMessageBox).toHaveBeenCalledTimes(2) }) + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + }) + + it.each(['downloading', 'verifying'] as const)('falls back to native %s status without changing the message or restarting the update', async (phase) => { + await readyForUpdate() + harness.updateState = { phase, version: '1.0.1-nightly.1', percent: 21 } + const checks = harness.updateCheck.mock.calls.length + harness.dialog.showMessageBox.mockRejectedValueOnce(new Error('overlay unavailable')) + await invoke(DESKTOP_IPC.updatesOpen, 'app') + expect(harness.dialog.showMessageBox).toHaveBeenCalledTimes(2) + const first: unknown = harness.dialog.showMessageBox.mock.calls[0]!.at(-1) + expect(first).toEqual(expect.objectContaining(harness.dialog.showMessageBox.mock.calls[1]!.at(-1))) + expect(first).toEqual(expect.objectContaining({ + type: 'info', message: phase === 'downloading' ? en.updateDownloadInProgress : en.updateVerifying, + detail: phase === 'downloading' ? en.updateDownloadDetail : '', buttons: [en.updateClose], + })) + expect(console.error).toHaveBeenCalledWith(expect.objectContaining({ message: 'overlay unavailable' })) + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + expect(harness.updateCheck).toHaveBeenCalledTimes(checks) + expect(harness.updateDownload).not.toHaveBeenCalled() + expect(harness.updateInstall).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe(phase) + }) + + it('logs native status fallback failure without rejecting the user action', async () => { + await readyForUpdate() + harness.updateState = { phase: 'downloading', version: '1.0.1-nightly.1', percent: 21 } + harness.dialog.showMessageBox.mockRejectedValueOnce(new Error('overlay unavailable')) + .mockRejectedValueOnce(new Error('native unavailable')) + await expect(invoke(DESKTOP_IPC.updatesOpen, 'app')).resolves.toBeUndefined() + expect(console.error).toHaveBeenCalledWith(expect.objectContaining({ message: 'native unavailable' })) + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + expect(harness.updateState.phase).toBe('downloading') + }) + it('does not lock or stop tasks when restart confirmation is dismissed', async () => { const host = await readyForUpdate() harness.dialog.showMessageBox.mockResolvedValueOnce({ response: 1 }) diff --git a/apps/desktop/tests/welcome-flow.e2e.ts b/apps/desktop/tests/welcome-flow.e2e.ts index 2fc04b5590..f298fd10fb 100644 --- a/apps/desktop/tests/welcome-flow.e2e.ts +++ b/apps/desktop/tests/welcome-flow.e2e.ts @@ -83,7 +83,7 @@ describe.skipIf(!existsSync(builtHost))('built Desktop welcome flow', () => { const nodeBin = join(root, 'runtime/primary-runtime/dependencies/node/bin') mkdirSync(nodeBin, { recursive: true }) cpSync(process.execPath, join(nodeBin, process.platform === 'win32' ? 'node.exe' : 'node')) - writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`) + writeFileSync(join(paths.profile, 'cordis.patch.yml'), `- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n- id: deepseek-account\n config:\n${process.platform === 'linux' ? ' desktopPlatform: darwin\n' : ''} platformOrigin: ${platform.origin}\n harnessOrigin: ${platform.origin}\n allowLoopbackHttp: true\n requestHeaders:\n Cookie: test_gate=synthetic\n`) let backend: DesktopWelcomeBackend let hostOrigin = '' const restart = async (): Promise => { diff --git a/apps/web/tests/account-login.e2e.ts b/apps/web/tests/account-login.e2e.ts index a186f74c91..029e6a3cc1 100644 --- a/apps/web/tests/account-login.e2e.ts +++ b/apps/web/tests/account-login.e2e.ts @@ -25,6 +25,7 @@ async function mockPlatform() { let state: string | undefined let redirectUri: string | undefined let avatarRequests = 0 + let notificationLists = 0 const server: Server = createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://127.0.0.1') const reply = (payload: unknown): void => { @@ -83,7 +84,10 @@ async function mockPlatform() { reply({ normal_wallets: [{ currency: 'CNY', balance: '1.00' }], bonus_wallets: [] }) return } - if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { reply([]); return } + if (url.pathname === '/api/v0/users/notifications/list') { + notificationLists++ + reply({ next_poll_after: 600, notifications: [] }); return + } res.writeHead(404).end() }) await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) @@ -91,7 +95,7 @@ async function mockPlatform() { if (address === null || typeof address === 'string') throw new Error('account login: missing mock listener') const origin = `http://127.0.0.1:${String(address.port)}` return { - origin, inits, pages, avatarRequests: () => avatarRequests, + origin, inits, pages, avatarRequests: () => avatarRequests, notificationLists: () => notificationLists, close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), } } @@ -144,7 +148,9 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await menu.locator('[data-avatar-status="failed"]').waitFor() expect(await menu.locator('img').count()).toBe(0) const states: string[] = [] + let expectedLists = 1 const capture = async (stage: string): Promise => { + await expect.poll(platform.notificationLists).toBe(expectedLists) const sidebar = menu.locator('[data-avatar-status]') const account = page.getByRole('region', { name: 'Account', exact: true }) const mounted = await account.count() > 0 @@ -152,10 +158,11 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain ? await account.locator('[data-avatar-status]').getAttribute('data-avatar-status') : 'unmounted' states.push(`${stage}: sidebar=${await sidebar.getAttribute('data-avatar-status')}, settings=${settingsStatus}, ` + `sidebarImages=${await menu.locator('img').count()}, settingsImages=${mounted ? await account.locator('img').count() : 0}, ` - + `requests=${platform.avatarRequests()}`) + + `requests=${platform.avatarRequests()}, notificationLists=${platform.notificationLists()}`) } await capture('Initial load') await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() const settings = page.getByRole('dialog', { name: 'Settings', exact: true }) const account = settings.getByRole('region', { name: 'Account', exact: true }) @@ -167,6 +174,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await expect.poll(() => menu.locator('img').count()).toBe(1) await expect.poll(() => account.locator('img').count()).toBe(1) @@ -179,6 +187,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await account.waitFor() expect(await menu.locator('img').count()).toBe(1) @@ -194,6 +203,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek account sign-in in a plain await settings.getByRole('button', { name: 'Close', exact: true }).click() await settings.waitFor({ state: 'detached' }) await menu.click() + expectedLists++ await page.getByRole('menuitem', { name: 'Settings', exact: true }).click() await expect.poll(() => menu.locator('img').count()).toBe(1) await expect.poll(() => account.locator('img').count()).toBe(1) diff --git a/apps/web/tests/bonus-notice.e2e.ts b/apps/web/tests/bonus-notice.e2e.ts index 61124bccb1..330c3e3505 100644 --- a/apps/web/tests/bonus-notice.e2e.ts +++ b/apps/web/tests/bonus-notice.e2e.ts @@ -22,10 +22,10 @@ const MODE = webSnapshotMode() const TOKEN = 'dsh_bonus_notice_test' const ACCOUNT_ID = 'bonus-user' -const ORDER_FIRST = 'bonus-notice-first' -const ORDER_LATER = '33333333-3333-4333-8333-333333333333' +const ORDER_FIRST = 'notice-first' +const ORDER_LATER = 'notice-later' const ORDER_EN = '44444444-4444-4444-8444-444444444444' -const ORDER_RETRY = '55555555-5555-4555-8555-555555555555' +const ORDER_FAILED_EVENT = '55555555-5555-4555-8555-555555555555' const ORDER_REPEAT = '66666666-6666-4666-8666-666666666666' const ORDER_TOPUP = '77777777-7777-4777-8777-777777777777' const ORDER_WEB = '99999999-9999-4999-8999-999999999999' @@ -65,9 +65,14 @@ interface AckRecord { async function mockPlatform() { const unnotified: Granted[] = [] const gets: GetRecord[] = [] + const contentReads: { id: string | null; locale: string | undefined }[] = [] + const contents = new Map() /** Reads already answered; a request the client is still awaiting is not evidence of a delivered response. */ const served: GetRecord[] = [] const acks: AckRecord[] = [] + const dismissals: AckRecord[] = [] + const clicks: AckRecord[] = [] + let includeUnsupportedNotification = false /** Wallet reads, one per balance refresh the settings panel performs. */ const summaries: GetRecord[] = [] let normalBalance = '12.34' @@ -78,20 +83,31 @@ async function mockPlatform() { let keepUnnotified = false /** Refuse the wallet read, which is how a Platform outage or an unparsable payload reaches the client. */ let failSummary = false + let holdProfile = false + const pendingProfiles: (() => void)[] = [] + const releaseProfiles = (): void => { holdProfile = false; for (const reply of pendingProfiles.splice(0)) reply() } /** Reply held back while the test controls when a read can answer. */ let heldReply: (() => void) | undefined const grant = (orderId: string, amount: string, extraCopy = ''): void => { - unnotified.unshift({ + const value = { orderId, amount, zh_CN: `已赠送您 ${amount} 元 DSH 体验赠金。${extraCopy}`, en_US: `You received a CNY ${amount} DSH trial credit.${extraCopy}`, - }) + } + unnotified.unshift(value) + contents.set(orderId, value) } /** @param value - granted bonus. @param locale - request language. @returns its wire fields. */ const wire = (value: Granted, locale: string | undefined): unknown => ({ - order_id: value.orderId, expires_at: value.orderId === ORDER_FIRST ? null : expiresAt(), - ...(value.orderId === ORDER_FIRST ? { title: '平台通知' } : {}), - msg: locale === 'en_US' ? value.en_US : value.zh_CN, + id: value.orderId, created_at: '2026-10-21T08:00:00Z', + display_until: value.orderId === ORDER_FIRST ? null : expiresAt(), + title: value.orderId === ORDER_FIRST ? (locale === 'en_US' ? 'Platform notice' : '平台通知') + : locale === 'en_US' ? 'Bonus credited' : '赠金已到账', + body: locale === 'en_US' ? value.en_US : value.zh_CN, + actions: value.orderId === 'b1111111-1111-4111-8111-111111111111' ? [ + { label: locale === 'en_US' ? 'View balance' : '查看余额', style: 'primary', target: { type: 'app_route', name: 'account' } }, + { label: locale === 'en_US' ? 'Got it' : '知道了', style: 'secondary', target: { type: 'dismiss' } }, + ] : [], }) const server: Server = createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://127.0.0.1') @@ -103,10 +119,14 @@ async function mockPlatform() { } if (req.headers['x-dsh-auth-token'] !== TOKEN) { res.writeHead(401).end(); return } if (url.pathname === '/auth-api/v0/users/current') { - // `email` is required by the provider's profile schema even when the account has none. - reply({ code: 0, data: { biz_code: 0, biz_data: { - id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null }, - } } }) + const answer = (): void => { + // `email` is required by the provider's profile schema even when the account has none. + reply({ code: 0, data: { biz_code: 0, biz_data: { + id: ACCOUNT_ID, email: '', id_profile: { name: 'Bonus User', picture: null }, + } } }) + } + if (holdProfile) pendingProfiles.push(answer) + else answer() return } if (url.pathname === '/api/v0/users/get_user_summary') { @@ -118,28 +138,48 @@ async function mockPlatform() { } } }) return } - if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { + if (url.pathname === '/api/v0/users/notifications/list') { const record = { locale, query: url.search } gets.push(record) - const payload = { code: 0, data: { biz_code: 0, biz_data: unnotified.map(value => wire(value, locale)) } } + const payload = { code: 0, data: { biz_code: 0, biz_data: { + next_poll_after: 3600, notifications: [ + ...includeUnsupportedNotification ? [{ + id: 'unsupported-action', created_at: '2026-10-21T00:00:00Z', display_until: null, + title: 'Unsupported action', body: 'Not supported by this client', + actions: [{ label: 'Open', style: 'primary', target: { type: 'future' } }], + }] : [], + ...unnotified.map(value => wire(value, locale)), + ], + } } } const answer = (): void => { served.push(record); reply(payload) } if (heldReply === undefined) { answer(); return } heldReply = answer return } - if (url.pathname === '/api/v0/users/ack_bonus_notified' && req.method === 'POST') { + if (url.pathname === '/api/v0/users/notifications/content') { + const id = url.searchParams.get('id') + contentReads.push({ id, locale }) + const value = id === null ? undefined : contents.get(id) + if (value === undefined) { res.writeHead(404).end(); return } + reply({ code: 0, data: { biz_code: 0, biz_data: wire(value, locale) } }) + return + } + if (url.pathname === '/api/v0/users/notifications/events' && req.method === 'POST') { let body = '' req.setEncoding('utf8') req.on('data', (chunk: string) => { body += chunk }) req.on('end', () => { const payload: unknown = JSON.parse(body) - const orderId = typeof payload === 'object' && payload !== null && 'order_id' in payload - && typeof payload.order_id === 'string' ? payload.order_id : null - acks.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body, + const orderId = typeof payload === 'object' && payload !== null && 'notification_id' in payload + && typeof payload.notification_id === 'string' ? payload.notification_id : null + const event = typeof payload === 'object' && payload !== null && 'type' in payload ? payload.type : null + if (event !== 'displayed' && event !== 'cta_clicked' && event !== 'dismissed') { res.writeHead(400).end(); return } + const records = event === 'displayed' ? acks : event === 'cta_clicked' ? clicks : dismissals + records.push({ method: req.method ?? '', path: url.pathname, locale, orderId, body, query: url.search, contentType: req.headers['content-type'], at: performance.now() }) - if (ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) { + if (event === 'displayed' && ackFailure !== undefined && ackFailure.orderId === orderId && ackFailure.remaining > 0) { ackFailure.remaining-- - // A transient gateway failure: the client retries it after its backoff. + // The event is lost; a later notification read can offer this order again. res.writeHead(502, { 'content-type': 'text/plain' }).end('Internal Server Error') return } @@ -147,8 +187,8 @@ async function mockPlatform() { reply({ code: 0, msg: '', data: { biz_code: 1, biz_msg: 'BONUS_ORDER_NOT_FOUND', biz_data: null } }); return } const index = unnotified.findIndex(value => value.orderId === orderId) - if (index >= 0 && !keepUnnotified) unnotified.splice(index, 1) - reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: null } }) + if (index >= 0 && !keepUnnotified && event !== 'cta_clicked') unnotified.splice(index, 1) + reply({ code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: { acked: true } } }) }) return } @@ -160,7 +200,11 @@ async function mockPlatform() { if (address === null || typeof address === 'string') throw new Error('bonus notice: missing mock listener') return { origin: `http://127.0.0.1:${String(address.port)}`, - grant, gets, served, acks, summaries, + grant, gets, served, acks, clicks, dismissals, summaries, contentReads, + setUnsupportedNotification: (value: boolean): void => { includeUnsupportedNotification = value }, + holdProfiles: (): void => { holdProfile = true }, + pendingProfileResponses: (): number => pendingProfiles.length, + releaseProfiles, /** @param value - recharge balance the settings page reads next. */ setNormalBalance: (value: string): void => { normalBalance = value }, /** @param value - bonus balance the settings page reads next. */ @@ -176,7 +220,7 @@ async function mockPlatform() { /** Hold the next unnotified-bonus read so the test can observe the in-flight state. */ holdNextGet: (): void => { heldReply = () => undefined }, releaseGet: (): void => { const held = heldReply; heldReply = undefined; held?.() }, - close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), + close: () => new Promise((resolve) => { releaseProfiles(); server.close(() => { resolve() }); server.closeAllConnections() }), } } @@ -286,6 +330,8 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { // A read the renderer never received cannot become a displayed notice: while the // response is held there is no card and no acknowledgement. platform.holdNextGet() + platform.holdProfiles() + platform.setUnsupportedNotification(true) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await expect.poll(() => platform.gets.length, { timeout: 30_000 }).toBe(1) observations.push(`startup.held cards=${String(await noticeCards(page).count())} acks=${String(platform.acks.length)}`) @@ -296,21 +342,34 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { // Startup signs in and reads the notice; the card shows it and only then is it acknowledged. observations.push(`startup.notice=${await shownNotice(page, zhFirst)}`) observations.push(`startup.ack orders=${await acked(platform, 1)}`) + expect(await noticeCards(page).count()).toBe(1) + expect(platform.acks.some(record => record.orderId === 'unsupported-action')).toBe(false) + observations.push('startup.unsupported-action skipped=true valid-card=true displayed=false') + platform.setUnsupportedNotification(false) + await expect.poll(platform.pendingProfileResponses).toBeGreaterThan(0) + observations.push('startup.profile-pending notice=true displayed=1') + platform.releaseProfiles() const get = platform.gets[0]! const ack = platform.acks[0]! observations.push(`startup.get locale=${String(get.locale)} query=${get.query}`) - observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} order_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`) + observations.push(`startup.ack method=${ack.method} path=${ack.path} locale=${String(ack.locale)} notification_id=${String(ack.orderId)} body=${JSON.stringify(ack.body)}`) expect(get.locale).toBe('zh_CN') expect(get.query).toBe('') expect(ack).toMatchObject({ - method: 'POST', path: '/api/v0/users/ack_bonus_notified', locale: 'zh_CN', orderId: ORDER_FIRST, - body: JSON.stringify({ order_id: ORDER_FIRST }), query: '', contentType: 'application/json', + method: 'POST', path: '/api/v0/users/notifications/events', locale: 'zh_CN', orderId: ORDER_FIRST, + body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'displayed' }), query: '', contentType: 'application/json', }) - // Closing the card only hides it; the acknowledgement already sent is not repeated. + // Explicit close reports dismissal without repeating the display event. await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() expect(await noticeCards(page).count()).toBe(0) expect(platform.acks).toHaveLength(1) + await expect.poll(() => platform.dismissals.length).toBe(1) + expect(platform.dismissals[0]).toMatchObject({ + method: 'POST', path: '/api/v0/users/notifications/events', orderId: ORDER_FIRST, + body: JSON.stringify({ notification_id: ORDER_FIRST, type: 'dismissed' }), + }) + observations.push('startup.close event=dismissed displayed=1 dismissed=1') // A new grant and balance arrive before settings opens; one panel entry refreshes both once. platform.grant(ORDER_LATER, '8.00') @@ -463,32 +522,27 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() expect(await noticeCards(page).count()).toBe(0) - // A transient acknowledgement failure keeps the card and retries the same order after - // the backoff; the pending retry is page state, not browser storage. - const zhRetry = '已赠送您 6.00 元 DSH 体验赠金。' - platform.grant(ORDER_RETRY, '6.00') - platform.failNextAcks(ORDER_RETRY, 1) + // A failed event leaves the card intact and is not retried in the background. + const zhFailedEvent = '已赠送您 6.00 元 DSH 体验赠金。' + platform.grant(ORDER_FAILED_EVENT, '6.00') + platform.failNextAcks(ORDER_FAILED_EVENT, 1) await openSettings(page, 'zh') - const retryDialog = page.getByRole('dialog', { name: '设置', exact: true }) - await retryDialog.waitFor() - observations.push(`retry.notice=${await shownNotice(page, zhRetry)}`) - const retryAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_RETRY) - await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(1) - // The failed attempt does not withdraw the card the user is reading. - expect(await noticeCards(page).count()).toBe(1) - await expect.poll(() => retryAttempts().length, { timeout: 30_000 }).toBe(2) - const attempts = retryAttempts() - // The first retry follows the configured first delay rather than arriving immediately. - // Only the lower bound is asserted: load can widen the observed gap, never shorten it - // below the timer's own 1s first step. - const retryGapMs = attempts[1]!.at - attempts[0]!.at - const retryBodyKept = attempts.every(item => item.body === JSON.stringify({ order_id: ORDER_RETRY }) + const failedEventDialog = page.getByRole('dialog', { name: '设置', exact: true }) + await failedEventDialog.waitFor() + observations.push(`event-failed.notice=${await shownNotice(page, zhFailedEvent)}`) + const failedAttempts = (): AckRecord[] => platform.acks.filter(item => item.orderId === ORDER_FAILED_EVENT) + await expect.poll(() => failedAttempts().length, { timeout: 30_000 }).toBe(1) + await page.clock.install() + await page.clock.fastForward(60_000) + const attempts = failedAttempts() + const eventBodyKept = attempts.every(item => item.body === JSON.stringify({ notification_id: ORDER_FAILED_EVENT, type: 'displayed' }) && item.query === '' && item.contentType === 'application/json') - observations.push(`retry.attempts=${String(attempts.length)} backoff=${String(retryGapMs >= 900)} body-kept=${String(retryBodyKept)} cards=${String(await noticeCards(page).count())}`) - expect(retryGapMs).toBeGreaterThanOrEqual(900) - expect(retryBodyKept).toBe(true) + observations.push(`event-failed.attempts=${String(attempts.length)} body-kept=${String(eventBodyKept)} cards=${String(await noticeCards(page).count())}`) + expect(attempts).toHaveLength(1) + expect(eventBodyKept).toBe(true) + expect(await noticeCards(page).count()).toBe(1) await page.keyboard.press('Escape') - await retryDialog.waitFor({ state: 'detached', timeout: 30_000 }) + await failedEventDialog.waitFor({ state: 'detached', timeout: 30_000 }) await noticeCards(page).getByRole('button', { name: '关闭', exact: true }).click() // Display follows each response: the double keeps serving an acknowledged order, which @@ -580,31 +634,72 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { observations.push(`web.notice=${webNotice} acks=1`) await webPage.close() platform.clearUnnotified() - platform.grant('stack-third', '23.00') - platform.grant('stack-second', '22.00', '\nMore details'.repeat(8)) - platform.grant('stack-first', '21.00') + platform.grant('a3333333-3333-4333-8333-333333333333', '23.00') + platform.grant('a2222222-2222-4222-8222-222222222222', '22.00', '\nMore details'.repeat(8)) + platform.grant('a1111111-1111-4111-8111-111111111111', '21.00') const ackStart = platform.acks.length const stackPage = await openDesktopPage('zh-CN') + await stackPage.setViewportSize({ width: 900, height: 960 }) await stackPage.emulateMedia({ colorScheme: 'light' }) await stackPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) const cards = noticeCards(stackPage) await expect.poll(() => cards.count()).toBe(3) + expect(await cards.first().isVisible()).toBe(false) + expect(platform.acks.length).toBe(ackStart) + observations.push('stack.hidden cards=3 acks=0') + await stackPage.setViewportSize({ width: 1440, height: 960 }) + await expect.poll(() => cards.first().isVisible()).toBe(true) await expect.poll(() => platform.acks.length).toBe(ackStart + 1) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first']) + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111']) expect(await stackPage.getByRole('status').count()).toBe(1) const second = cards.filter({ hasText: '22.00' }) const secondNode = await second.elementHandle() const frontBox = await cards.first().boundingBox() const backBox = await second.boundingBox() - expect(frontBox!.width).toBeCloseTo(280, 0) - expect(backBox!.width).toBeCloseTo(272, 0) + expect(frontBox!.x).toBeCloseTo(10, 0) + expect(frontBox!.width).toBeCloseTo(260, 0) + expect(frontBox!.x + frontBox!.width).toBeCloseTo(270, 0) + expect(backBox!.width).toBeCloseTo(252, 0) expect(backBox!.y).toBeCloseTo(frontBox!.y - 4, 0) const transition = await second.evaluate((element) => { const style = getComputedStyle(element) return `${style.transitionDuration} ${style.transitionTimingFunction}` }) expect(transition).toBe('0.25s ease-out') - observations.push(`stack.initial cards=3 acks=stack-first widths=280,272 offset=-4 transition=${transition}`) + observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`) + for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) { + const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox() + const x = handle!.x + handle!.width / 2 + const y = handle!.y + handle!.height / 2 + await stackPage.mouse.move(x, y) + await stackPage.mouse.down() + await stackPage.mouse.move(x + delta, y, { steps: 5 }) + await stackPage.mouse.up() + await expect.poll(async () => Math.round((await cards.first().boundingBox())!.width)).toBe(width) + const movedHandle = await stackPage.locator('[data-side="sidebar"]').boundingBox() + expect(movedHandle!.x + movedHandle!.width / 2).toBeCloseTo(edge, 0) + const resized = await cards.first().boundingBox() + expect(resized!.x).toBeCloseTo(10, 0) + expect(resized!.x + resized!.width).toBeCloseTo(10 + width, 0) + observations.push(`stack.resized sidebar=${edge} card=${width} left-inset=10`) + } + const beforeCollapseAcks = platform.acks.length + const beforeCollapseDismissals = platform.dismissals.length + await stackPage.setViewportSize({ width: 900, height: 960 }) + await stackPage.locator('[data-sidebar-collapsed]:not([data-sidebar-drawer])').waitFor() + await expect.poll(() => cards.first().isVisible()).toBe(false) + expect(await cards.count()).toBe(3) + expect(platform.dismissals.length).toBe(beforeCollapseDismissals) + observations.push('stack.rail cards=3 visible=false dismissed=0') + await stackPage.setViewportSize({ width: 1440, height: 960 }) + await stackPage.locator('[data-sidebar-collapsed]').waitFor({ state: 'detached' }) + await expect.poll(() => cards.first().isVisible()).toBe(true) + expect(await cards.count()).toBe(3) + expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true) + expect(await cardText(cards.first())).toContain('21.00') + expect(platform.acks.length).toBe(beforeCollapseAcks) + expect(platform.dismissals.length).toBe(beforeCollapseDismissals) + observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0') const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url)) await mkdir(artifactDir, { recursive: true }) await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') }) @@ -635,20 +730,132 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => { expect(promotion.middle.y).toBeLessThan(promotion.start.y) expect(promotion.middle.y).toBeGreaterThan(promotion.end.y) await expect.poll(() => cards.count()).toBe(2) - await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(280) + await expect.poll(async () => Math.round((await second.boundingBox())!.width)).toBe(260) expect(await second.evaluate((element, previous) => element === previous, secondNode)).toBe(true) expect(await second.getAttribute('data-front')).toBe('true') await expect.poll(() => platform.acks.length).toBe(ackStart + 2) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second']) - observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=280 same-node=true') + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222']) + observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true') await second.getByRole('button', { name: '关闭', exact: true }).click() await expect.poll(() => platform.acks.length).toBe(ackStart + 3) - expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['stack-first', 'stack-second', 'stack-third']) + expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333']) await cards.filter({ hasText: '23.00' }).getByRole('button', { name: '关闭', exact: true }).click() await expect.poll(() => cards.count()).toBe(0) + await expect.poll(() => platform.dismissals.filter(record => record.orderId?.startsWith('a')).length).toBe(3) + const stackDismissals = platform.dismissals.filter(record => record.orderId?.startsWith('a')) + expect(stackDismissals.map(record => record.body)).toEqual(stackDismissals.map(record => + JSON.stringify({ notification_id: record.orderId, type: 'dismissed' }))) observations.push('stack.dismissed cards=0 acks=stack-first,stack-second,stack-third') await stackPage.close() + platform.grant('b1111111-1111-4111-8111-111111111111', '31.00') + const refreshAckStart = platform.acks.length + const refreshPage = await openDesktopPage('zh-CN') + await refreshPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const refreshCards = noticeCards(refreshPage) + await shownNotice(refreshPage, '已赠送您 31.00 元 DSH 体验赠金。') + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 1) + const firstNode = await refreshCards.first().elementHandle() + platform.grant('b3333333-3333-4333-8333-333333333333', '33.00') + platform.grant('b2222222-2222-4222-8222-222222222222', '32.00') + await openSettings(refreshPage, 'zh') + await expect.poll(() => refreshCards.count()).toBe(3) + expect(await cardText(refreshCards.first())).toContain('31.00') + expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true) + expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111']) + observations.push('refresh.retained cards=3 acks=refresh-first same-node=true') + const localeReads = platform.gets.length + const localeContents = platform.contentReads.length + await refreshPage.getByRole('dialog', { name: '设置', exact: true }).getByRole('button', { name: '通用设置', exact: true }).click() + await refreshPage.getByRole('button', { name: '中文', exact: true }).click() + await refreshPage.getByRole('menuitem', { name: 'English', exact: true }).click() + await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor() + await expect.poll(() => cardText(refreshCards.first())).toContain('You received a CNY 31.00') + expect(await refreshCards.first().evaluate((element, previous) => element === previous, firstNode)).toBe(true) + expect(platform.gets.length).toBe(localeReads) + expect(platform.acks.length).toBe(refreshAckStart + 1) + expect(platform.contentReads.slice(localeContents).map(read => read.locale)).toEqual(['en_US', 'en_US', 'en_US']) + expect(await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).count()).toBe(1) + observations.push('refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true') + await refreshPage.keyboard.press('Escape') + await refreshPage.getByRole('dialog', { name: 'Settings', exact: true }).waitFor({ state: 'detached' }) + const clicksBeforeAction = platform.clicks.length + const dismissalsBeforeClick = platform.dismissals.length + await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).click() + await expect.poll(() => platform.clicks.length).toBe(clicksBeforeAction + 1) + expect(platform.clicks.at(-1)?.body).toBe(JSON.stringify({ notification_id: 'b1111111-1111-4111-8111-111111111111', type: 'cta_clicked' })) + expect(platform.dismissals.length).toBe(dismissalsBeforeClick) + expect(await refreshCards.count()).toBe(3) + const accountSettings = refreshPage.getByRole('dialog', { name: 'Settings', exact: true }) + await accountSettings.waitFor() + expect(await accountSettings.getByRole('button', { name: 'Account', exact: true }).getAttribute('aria-current')).toBe('true') + observations.push('refresh.business-action event=cta_clicked cards=3 account-open=true') + await refreshPage.keyboard.press('Escape') + await accountSettings.waitFor({ state: 'detached' }) + await refreshPage.setViewportSize({ width: 390, height: 844 }) + await refreshPage.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor() + await expect.poll(() => refreshCards.first().isVisible()).toBe(false) + expect(await refreshCards.count()).toBe(3) + await refreshPage.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() + const drawer = refreshPage.locator('[data-sidebar-drawer]:not([data-sidebar-collapsed])') + await drawer.waitFor() + expect(await refreshCards.first().evaluate(element => element.closest('[role="dialog"]')?.getAttribute('aria-label'))).toBe('Navigation') + await expect.poll(() => drawer.locator('[data-sidebar-mask]').evaluate(element => getComputedStyle(element).opacity)).toBe('1') + await expect.poll(() => refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).evaluate((element) => { + const rect = element.getBoundingClientRect() + return element.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2)) + })).toBe(true) + observations.push('refresh.drawer width=390 notice-above-sidebar=true') + const cardBounds = await refreshCards.first().boundingBox() + const drawerBounds = await drawer.getByRole('dialog', { name: 'Navigation', exact: true }).boundingBox() + const actionBounds = await refreshCards.first().getByRole('button', { name: 'View balance', exact: true }).boundingBox() + expect(cardBounds!.x - drawerBounds!.x).toBeCloseTo(10, 0) + expect(drawerBounds!.width - cardBounds!.width).toBeCloseTo(20, 0) + expect(cardBounds!.x).toBeGreaterThanOrEqual(0) + expect(cardBounds!.x + cardBounds!.width).toBeLessThanOrEqual(390) + expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(cardBounds!.x + cardBounds!.width) + const dismissalsBeforeAction = platform.dismissals.length + await refreshCards.first().getByRole('button', { name: 'Got it', exact: true }).click() + expect(await drawer.count()).toBe(1) + await expect.poll(() => platform.dismissals.length).toBe(dismissalsBeforeAction + 1) + expect(platform.dismissals.at(-1)?.orderId).toBe('b1111111-1111-4111-8111-111111111111') + expect(platform.clicks.length).toBe(clicksBeforeAction + 1) + observations.push('refresh.action event=dismissed got-it=true') + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 2) + expect(await cardText(refreshCards.first())).toContain('32.00') + observations.push('refresh.promoted cards=2 acks=refresh-first,refresh-second') + await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => platform.acks.length).toBe(refreshAckStart + 3) + expect(platform.acks.slice(refreshAckStart).map(ack => ack.orderId)).toEqual(['b1111111-1111-4111-8111-111111111111', 'b2222222-2222-4222-8222-222222222222', 'b3333333-3333-4333-8333-333333333333']) + await refreshCards.first().getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => refreshCards.count()).toBe(0) + observations.push('refresh.dismissed cards=0 acks=refresh-first,refresh-second,refresh-third') + await refreshPage.close() + + const pollFirst = 'c1111111-1111-4111-8111-111111111111' + const pollSecond = 'c2222222-2222-4222-8222-222222222222' + platform.grant(pollFirst, '41.00') + const pollPage = await openDesktopPage('en-US') + await pollPage.clock.install() + await pollPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await shownNotice(pollPage, 'You received a CNY 41.00 DSH trial credit.') + await expect.poll(() => platform.acks.at(-1)?.orderId).toBe(pollFirst) + const pollCards = noticeCards(pollPage) + const retainedNode = await pollCards.first().elementHandle() + const pollReads = platform.gets.length + const pollAcks = platform.acks.length + platform.grant(pollSecond, '42.00') + await pollPage.clock.fastForward(3_600_000) + await expect.poll(() => pollCards.count()).toBe(2) + expect(platform.gets.length).toBe(pollReads + 1) + expect(platform.acks.length).toBe(pollAcks) + expect(await pollCards.first().evaluate((element, previous) => element === previous, retainedNode)).toBe(true) + await openSettings(pollPage, 'en') + await expect.poll(() => platform.gets.length).toBe(pollReads + 2) + expect(await pollCards.count()).toBe(2) + observations.push('poll.arrival cards=2 list-reads=1 duplicate-acks=0 same-node=true settings-immediate-read=true') + await pollPage.close() + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'notice-flow.expected.md'), observations.join('\n'), MODE) for (const tripwire of tripwires) { expect(tripwire.warnings).toEqual([]) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index fd5f778c1e..bccac447e1 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -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 { await nextPaint(page) } -async function wheelToHistoryStart(page: Page): Promise { - 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> { + const gate = Promise.withResolvers() + const pending = new Set>() + const hold = (route: Route): Promise => { + 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 { + 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 { + 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 { @@ -476,23 +534,32 @@ async function expectMarkerAboveComposer(page: Page, marker: string): Promise { - 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 { + // 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 { @@ -1300,6 +1367,8 @@ describe('web e2e: long Chat scroll contract', () => { let releaseHistory = (): void => {} let held = false + let historyRequests = 0 + const heldContinued = Promise.withResolvers() let releaseGate: (() => void) | undefined const gate = new Promise((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() + const pendingHistory = new Set>() + let historyHeld = false + const holdHistory = (route: Route): Promise => { + 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) diff --git a/apps/web/tests/composer-paste-routing.e2e.ts b/apps/web/tests/composer-paste-routing.e2e.ts new file mode 100644 index 0000000000..75a12217e7 --- /dev/null +++ b/apps/web/tests/composer-paste-routing.e2e.ts @@ -0,0 +1,169 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-subagent' +import { launchWebScaffold, selectedSessionFixture, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot } from './support.ts' + +const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const LABEL = 'event-sourcing researcher' +const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' + +/** Duplicate the base turn so the child owns its own replayed history. */ +function childFixture(source: string, fixtureId: string): string { + const [header, ...eventLines] = source.trimEnd().split('\n') + if (header === undefined) throw new Error('base replay fixture has no header') + const value = JSON.parse(header) as Record + value.id = fixtureId + return [JSON.stringify(value), ...eventLines, ''].join('\n') +} + +async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise { + const deadline = Date.now() + 30_000 + while (scaffold.ctx.agents.get(id) !== undefined) { + if (Date.now() >= deadline) throw new Error(`subagent ${id} did not settle`) + await new Promise(resolve => setTimeout(resolve, 10)) + } +} + +/** Put one PNG on the system clipboard, confirm the clipboard holds it, then paste it with the platform shortcut. */ +async function pasteImage(page: Page): Promise { + const types = await page.evaluate(async (base64) => { + const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0)) + await navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]) + return (await navigator.clipboard.read()).flatMap(item => item.types) + }, PNG_BASE64) + expect(types).toContain('image/png') + await page.keyboard.press('ControlOrMeta+V') +} + +/** Leave every control, as after clicking a transcript's empty space. */ +async function blurAll(page: Page): Promise { + await page.evaluate(() => { (document.activeElement as HTMLElement | null)?.blur() }) + expect(await page.evaluate(() => document.activeElement === document.body)).toBe(true) +} + +/** Editors of the main Conversation composer and the Sidebar chat composer. */ +const MAIN_INPUT = '[data-composer-input][contenteditable="true"]:not([data-sidebar-chat] *)' +const SIDEBAR_INPUT = '[data-sidebar-chat] [data-composer-input][contenteditable="true"]' + +/** Image thumbnails currently in each composer's draft rail. */ +async function railImages(page: Page): Promise<{ main: number; sidebar: number }> { + return page.evaluate(() => { + const count = (root: Element | null): number => + root?.querySelectorAll('[data-composer-card] img').length ?? 0 + const sidebar = document.querySelector('[data-sidebar-chat]') + const main = [...document.querySelectorAll('[data-conversation-content]')] + .find(element => sidebar === null || !sidebar.contains(element)) ?? null + return { main: count(main), sidebar: count(sidebar) } + }) +} + +describe('web e2e: composer paste routing', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let sidecarRoot: string + + beforeAll(async () => { + if (webSnapshotMode() === 'record') throw new Error('composer paste routing is a keyless assembled scenario') + const selectedBaseFixture = await selectedSessionFixture(BASE_FIXTURE) + const baseFixture = prepareSessionSnapshotFixtureForComparison(await readFile(selectedBaseFixture, 'utf8')) + sidecarRoot = await mkdtemp(join(tmpdir(), 'dsh-web-paste-')) + const childFixturePath = join(sidecarRoot, 'child.jsonl') + await writeFile(childFixturePath, childFixture(baseFixture, 'recorded-subagent')) + scaffold = await launchWebScaffold({ + replayFixture: selectedBaseFixture, + compareReplaySession: false, + replayChildFixtures: [childFixturePath], + paceMs: 25, + }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const parent = scaffold.ctx.agents.list().filter(agent => agent.session.header.origin !== 'subagent')[0] + if (parent === undefined) throw new Error('fresh workspace did not publish its parent Agent') + const parentSettled = scaffold.whenTurnSettled() + const parentInput = page.locator('[data-composer-input][contenteditable="true"]').first() + await parentInput.fill('Ask a research subagent to explain event sourcing.') + await parentInput.press('Enter') + expect(await parentSettled).toBe(parent.id) + const started = await scaffold.ctx.subagents.startActivation({ + delivery: 'parent', provider: 'spawn', label: LABEL, signal: new AbortController().signal, + prompt: [{ type: 'text', text: 'Explain event sourcing in one sentence.' }], + parent, + }) + await waitForAgentToSettle(scaffold, started.childId) + await page.getByRole('button', { name: '1 subagent', exact: true }).hover() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }) + .getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click() + await page.locator('[data-sidebar-chat] [data-composer-card]').waitFor({ timeout: 15_000 }) + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (sidecarRoot !== undefined) await rm(sidecarRoot, { recursive: true, force: true }) + }) + + it('pastes into the focused editor once and an unfocused paste into the last focused composer', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste')) + const before = await railImages(page) + await page.locator(SIDEBAR_INPUT).click() + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main, sidebar: before.sidebar + 1 }) + await blurAll(page) + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main, sidebar: before.sidebar + 2 }) + await page.locator(MAIN_INPUT).click() + await blurAll(page) + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar + 2 }) + }) + + it('ignores an unfocused paste while Settings is open', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste-modal')) + await page.locator(MAIN_INPUT).click() + await blurAll(page) + const before = await railImages(page) + await openSettings(page, 'en') + const settings = page.getByRole('dialog', { name: 'Settings' }) + await settings.waitFor() + await pasteImage(page) + await page.keyboard.press('Escape') + await settings.waitFor({ state: 'detached' }) + await blurAll(page) + // Exactly one image after a paste that would succeed: the paste behind Settings added none. + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar }) + }) + + it('sends an unfocused paste to the main composer once the focused Sidebar collapses', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-paste-collapsed')) + await page.locator(SIDEBAR_INPUT).click() + const before = await railImages(page) + await page.getByRole('button', { name: 'Collapse right sidebar', exact: true }).click() + await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor() + // The collapsed Sidebar keeps the chat mounted inside an inert dock section. + expect(await page.locator('[data-sidebar-chat] [data-composer-card]') + .evaluate(card => card.closest('[inert]') !== null)).toBe(true) + await blurAll(page) + try { + await pasteImage(page) + await expect.poll(() => railImages(page)).toEqual({ main: before.main + 1, sidebar: before.sidebar }) + } finally { + await page.getByRole('button', { name: 'Open right sidebar', exact: true }).click() + await page.locator(SIDEBAR_INPUT).waitFor() + } + }) +}) diff --git a/apps/web/tests/creator-persona.e2e.ts b/apps/web/tests/creator-persona.e2e.ts new file mode 100644 index 0000000000..c9382bbde5 --- /dev/null +++ b/apps/web/tests/creator-persona.e2e.ts @@ -0,0 +1,55 @@ +/** Creator mode adds its DSH customization intent to the actual model prompt. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import type {} from '@deepseek-ai/dsh-token-meter' +import { fixtureUserPrompts, launchWebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/creator-persona/session.v4.jsonl', import.meta.url)) +const CUSTOMIZATION_INTENT = 'You help the user customize DeepSeek Harness itself.' + +it('sends the Creator customization intent without taking actions for an ordinary request', async () => { + const scaffold = await launchWebScaffold({ + replayFixture: FIXTURE, compareReplaySession: true, paceMs: 10, + agentPresets: { default: 'cordis' }, + }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const prompts = fixtureUserPrompts(await readFile(FIXTURE, 'utf8')) + expect(prompts).toHaveLength(1) + const settled = scaffold.whenTurnSettled() + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + await composer.fill(prompts[0]!) + await composer.press('Enter') + const sessionId = await settled + const agent = scaffold.ctx.agents.get(sessionId) + if (agent === undefined) throw new Error('Creator persona session is missing') + expect(agent.session.header.agentPreset).toBe('cordis') + const system = agent.session.deriveMessages().find(message => message.role === 'system') + if (system === undefined) throw new Error('Creator request has no system prompt') + const prompt = system.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + expect(prompt).toMatch(/^You are a coding agent powered by the .+ model\. You help the user customize DeepSeek Harness itself\.$/mu) + expect(prompt.split(CUSTOMIZATION_INTENT)).toHaveLength(2) + const sharedPrompt = prompt.replace(` ${CUSTOMIZATION_INTENT}`, '') + console.info('Creator persona context increment', { + utf8Bytes: Buffer.byteLength(prompt) - Buffer.byteLength(sharedPrompt), + codePoints: Array.from(prompt).length - Array.from(sharedPrompt).length, + heuristicTokens: scaffold.ctx.tokenMeter.estimateMessage(system) + - scaffold.ctx.tokenMeter.estimateMessage({ ...system, content: [{ type: 'text', text: sharedPrompt }] }), + }) + expect(agent.session.snapshotEvents().filter(event => event.type === 'tool/call')).toEqual([]) + await page.getByText('READY', { exact: true }).waitFor() + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 6033c8f06f..bd4f463f3b 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -1,9 +1,14 @@ -/** Web DeepSeek configuration, credential reuse, and saved model selection. */ +/** Web provider credentials, environment fallback, and DeepSeek model selection. */ import { readFile } from 'node:fs/promises' +import { once } from 'node:events' +import { createServer } from 'node:http' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, webkit, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { BlockAssembler, createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, @@ -12,6 +17,157 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url)) +it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'acme-gateway'])( + 'clears the saved %s key and sends the next request with environment authentication', async (provider) => { + const messages = provider === 'deepseek-official' + const google = provider === 'google' + const ref = credentialRef(messages ? 'DEEPSEEK_API_KEY' : `${provider.toUpperCase().replaceAll('-', '_')}_API_KEY`) + const envRef = google ? 'GEMINI_API_KEY' : ref + const calls: { path: string; key: string | undefined }[] = [] + const server = createServer((request, response) => { + request.on('end', () => { + const key = request.headers[messages ? 'x-api-key' : google ? 'x-goog-api-key' : 'authorization'] + calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined }) + const events = messages ? [ + { type: 'message_start', message: { id: 'clear', type: 'message', role: 'assistant', model: 'clear-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } }, + { type: 'message_stop' }, + ] : google ? [{ candidates: [{ content: { role: 'model', parts: [{ text: 'connection-ok' }] }, finishReason: 'STOP' }] }] + : [{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: 'connection-ok' }, finish_reason: null }] }, + { id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }] + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('')) + }) + request.resume() + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + let scaffold: WebScaffold | undefined + let browser: Browser | undefined + try { + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Missing credential test listener') + const baseURL = `http://127.0.0.1:${String(address.port)}/configured` + scaffold = await launchWebScaffold({ + deepSeekMissingCredential: true, + openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { [envRef]: 'fixture-environment-key' } }]), + }) + const profile = { apiKeyEnv: ref, baseURL, models: [{ id: 'clear-model' }], + ...messages || google ? {} : { api: 'openai-completions' } } + await scaffold.ctx.settings.mutate(messages ? 'llm-deepseek' : 'llm-pi-ai', [{ + op: 'set', path: messages ? [] : ['providers', provider], value: profile, + }]) + await scaffold.ctx.credentials.set(ref, 'fixture-saved-key') + const runtime = scaffold.ctx + const generate = async (): Promise => { + const assembler = new BlockAssembler() + const chunks: StreamChunk[] = [] + for await (const chunk of runtime.llm.stream({ provider, model: 'clear-model', + messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply connection-ok' }], source: { kind: 'user' } })] })) { + chunks.push(chunk) + assembler.push(chunk) + } + expect(assembler.message({ provider, model: 'clear-model' }).content, JSON.stringify(chunks)) + .toContainEqual({ type: 'text', text: 'connection-ok' }) + } + await generate() + browser = await chromium.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + await key.press('Delete') + expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) + await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'), + await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) + await dialog.getByRole('button', { name: '取消', exact: true }).click() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + await edit.click() + await key.press('Delete') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await generate() + expect(calls).toHaveLength(2) + expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key') + expect(calls[1]).toEqual({ path: calls[0]?.path, + key: messages || google ? 'fixture-environment-key' : 'Bearer fixture-environment-key' }) + expect(calls[1]?.path).toContain('/configured/') + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).not.toContain('fixture-saved-key') + await edit.click() + await dialog.getByText(`已检测到环境变量(${envRef})`, { exact: true }).waitFor() + await dialog.getByText('自定义设置', { exact: true }).click() + expect(await dialog.getByLabel('API 地址', { exact: true }).inputValue()).toBe(baseURL) + expect(await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).count()).toBe(0) + } finally { + try { await browser?.close() } finally { + try { await scaffold?.close() } finally { + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + } + } + } + }, +) + +it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( + 'protects saved keys and reveals only unsaved replacements in $name', async ({ engine }) => { + const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) + let browser: Browser | undefined + try { + await scaffold.ctx.credentials.set(credentialRef('DEEPSEEK_API_KEY'), 'fixture-protected-old-key') + browser = await engine.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`) + expect(await key.inputValue()).toBe('') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') + await key.press('Backspace') + await dialog.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() + expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') + await dialog.getByRole('button', { name: '取消', exact: true }).click() + await edit.click() + expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`) + await key.fill('fixture-new-key') + await dialog.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() + await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() + expect(await key.getAttribute('type')).toBe('text') + expect(await key.inputValue()).toBe('fixture-new-key') + await key.press('ControlOrMeta+A') + await key.press('ControlOrMeta+X') + await expect.poll(() => key.inputValue()).toBe('') + await key.fill('fixture-new-key') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await edit.click() + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length)) + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('type')).toBe('password') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key') + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } + }, +) + it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( 'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => { const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) @@ -90,6 +246,10 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1) await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click() const messages = dialog + const key = messages.getByLabel('API 密钥', { exact: true }) + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('placeholder')).toBe(`sk-messa${'•'.repeat(10)}ding`) + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') @@ -114,6 +274,17 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages') expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY') expect(await page.locator('body').innerText()).not.toContain('sk-e2e-') + await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click() + expect(await key.inputValue()).toBe('') + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() + expect(await key.getAttribute('type')).toBe('password') + await key.fill('sk-cancelled-replacement') + await messages.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() + expect(await messages.getByText('使用已保存的 API key。', { exact: true }).count()).toBe(0) + await key.fill('') + await messages.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() + await messages.getByRole('button', { name: '取消', exact: true }).click() + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) await page.keyboard.press('Escape') await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e') await page.getByRole('button', { name: /^选择模型/ }).click() diff --git a/apps/web/tests/desktop-onboarding.e2e.ts b/apps/web/tests/desktop-onboarding.e2e.ts index c275135057..8283fb7125 100644 --- a/apps/web/tests/desktop-onboarding.e2e.ts +++ b/apps/web/tests/desktop-onboarding.e2e.ts @@ -51,21 +51,21 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => screenshots = undefined root = await mkdtemp(join(tmpdir(), 'dsh-desktop-onboarding-')) server = createServer((request, response) => { - if (request.url === '/api/v0/users/get_unnotified_bonuses') { + if (request.url === '/api/v0/users/notifications/list') { bonusReads++ response.setHeader('content-type', 'application/json') - response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: bonusOffered ? [{ - order_id: '88888888-8888-4888-8888-888888888888', campaign: 'dsh_login_bonus', - amount: '5.00', currency: 'CNY', granted_at: new Date().toISOString(), - expires_at: new Date(Date.now() + 86_400_000).toISOString(), msg: '已赠送您 5.00 元 DSH 体验赠金。', - }] : [] } })) + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { next_poll_after: 600, notifications: bonusOffered ? [{ + id: '88888888-8888-4888-8888-888888888888', type: 'account.bonus_granted', + created_at: new Date().toISOString(), title: '赠金已到账', actions: [], + display_until: new Date(Date.now() + 86_400_000).toISOString(), body: '已赠送您 5.00 元 DSH 体验赠金。', + }] : [] } } })) return } - if (request.url === '/api/v0/users/ack_bonus_notified') { + if (request.url === '/api/v0/users/notifications/events') { bonusAcks++ bonusOffered = false response.setHeader('content-type', 'application/json') - response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: null } })) + response.end(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { acked: true } } })) return } if (request.url !== '/auth-api/v0/users/current' && request.url !== '/api/v0/users/get_user_summary') { @@ -85,7 +85,7 @@ describe.skipIf(MODE === 'record')('web e2e: App-only desktop onboarding', () => if (address === null || typeof address === 'string') throw new Error('fixture server address unavailable') origin = `http://127.0.0.1:${address.port}` const overlay = join(root, 'account.patch.yml') - await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n allowLoopbackHttp: true\n`) + await writeFile(overlay, `- id: deepseek-account\n config:\n platformOrigin: ${origin}\n harnessOrigin: ${origin}\n allowLoopbackHttp: true\n`) scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, extraOverlayPath: overlay }) await scaffold.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), async () => ({ kind: 'grant', payload: { version: 1, issuer: origin, token: 'onboarding-fixture-token' }, diff --git a/apps/web/tests/desktop-updates.e2e.ts b/apps/web/tests/desktop-updates.e2e.ts index ac596249b3..0fb963b7ea 100644 --- a/apps/web/tests/desktop-updates.e2e.ts +++ b/apps/web/tests/desktop-updates.e2e.ts @@ -74,11 +74,10 @@ describe('web e2e: Desktop update workspace chrome', () => { await publish(progress) const downloading = page.getByRole('button', { name: '58%', exact: true }) await downloading.waitFor() - expect(await downloading.getAttribute('aria-disabled')).toBe('true') + expect(await downloading.getAttribute('aria-disabled')).toBe('false') expect(await downloading.locator('svg').count()).toBe(1) - // Force dispatch past Playwright's aria-disabled guard to verify the product's click guard. - await downloading.click({ force: true }) - expect(await opens()).toBe(1) + await downloading.click() + await expect.poll(opens).toBe(2) await page.screenshot({ path: join(evidence, 'downloading.png') }) const collapse = locale === 'zh-CN' ? '收起侧边栏' : 'Collapse sidebar' @@ -118,21 +117,21 @@ describe('web e2e: Desktop update workspace chrome', () => { await expect.poll(() => tooltip.evaluateAll(elements => elements.map(element => getComputedStyle(element).opacity))).toEqual(['1']) await page.screenshot({ path: join(evidence, 'retry.png') }) await retry.click() - await expect.poll(opens).toBe(2) + await expect.poll(opens).toBe(3) await publish(presentDesktopUpdate({ phase: 'ready', version })) const ready = page.getByRole('button', { name: readyLabel, exact: true }) await ready.waitFor() expect(await ready.getAttribute('aria-disabled')).toBe('false') - expect(await opens()).toBe(2) + expect(await opens()).toBe(3) await page.screenshot({ path: join(evidence, 'ready.png') }) await ready.click() - await expect.poll(opens).toBe(3) + await expect.poll(opens).toBe(4) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) expect(await page.evaluate(() => (window as FixtureWindow).updateFixture.listeners.size)).toBe(1) await writeFile(join(evidence, 'result.json'), JSON.stringify({ locale, geometry, updateBackground, failedBackground, - passed: true, explicitActions: 3, carrier: 'substituted', host: 'real Web composition', + passed: true, explicitActions: 4, carrier: 'substituted', host: 'real Web composition', electron: false, installerExecuted: false }, null, 2) + '\n') console.log(`Desktop workspace chrome evidence: ${evidence}`) } catch (error) { diff --git a/apps/web/tests/expected/account-login/avatar-retry.expected.md b/apps/web/tests/expected/account-login/avatar-retry.expected.md index 4106b7eb4b..e86b065689 100644 --- a/apps/web/tests/expected/account-login/avatar-retry.expected.md +++ b/apps/web/tests/expected/account-login/avatar-retry.expected.md @@ -1,6 +1,6 @@ -Initial load: sidebar=failed, settings=unmounted, sidebarImages=0, settingsImages=0, requests=1 -First Settings entry: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=2 -Second Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 -Third Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 -Rendered image failure: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=3 -Settings entry after rendered failure: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3 +Initial load: sidebar=failed, settings=unmounted, sidebarImages=0, settingsImages=0, requests=1, notificationLists=1 +First Settings entry: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=2, notificationLists=2 +Second Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=3 +Third Settings entry: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=4 +Rendered image failure: sidebar=failed, settings=failed, sidebarImages=0, settingsImages=0, requests=3, notificationLists=4 +Settings entry after rendered failure: sidebar=ready, settings=ready, sidebarImages=1, settingsImages=1, requests=3, notificationLists=5 diff --git a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md index c4ff30f121..08f4861da9 100644 --- a/apps/web/tests/expected/bonus-notice/notice-flow.expected.md +++ b/apps/web/tests/expected/bonus-notice/notice-flow.expected.md @@ -1,11 +1,14 @@ startup.held cards=0 acks=0 startup.notice=平台通知 / 已赠送您 5.00 元 DSH 体验赠金。 -startup.ack orders=bonus-notice-first +startup.ack orders=notice-first +startup.unsupported-action skipped=true valid-card=true displayed=false +startup.profile-pending notice=true displayed=1 startup.get locale=zh_CN query= -startup.ack method=POST path=/api/v0/users/ack_bonus_notified locale=zh_CN order_id=bonus-notice-first body="{\"order_id\":\"bonus-notice-first\"}" +startup.ack method=POST path=/api/v0/users/notifications/events locale=zh_CN notification_id=notice-first body="{\"notification_id\":\"notice-first\",\"type\":\"displayed\"}" +startup.close event=dismissed displayed=1 dismissed=1 open.held cards=0 acks=1 gets=1 open.shown notice=赠金已到账 / 已赠送您 8.00 元 DSH 体验赠金。 -open.shown ack orders=bonus-notice-first,33333333-3333-4333-8333-333333333333 +open.shown ack orders=notice-first,notice-later open.shown painted-under-settings=true cards=1 acks=2 open.get locale=zh_CN query= served=true gets=1 open.balance bonus-row=true amount=true dated=false @@ -21,8 +24,8 @@ topup.returned bridge=open:top-up,close cards=0 topup.notice=赠金已到账 / 已赠送您 11.00 元 DSH 体验赠金。 topup.refresh gets=2 summaries=2 acks=1 recharge=true bonus=true topup.closed cards=1 acks=1 -retry.notice=赠金已到账 / 已赠送您 6.00 元 DSH 体验赠金。 -retry.attempts=2 backoff=true body-kept=true cards=1 +event-failed.notice=赠金已到账 / 已赠送您 6.00 元 DSH 体验赠金。 +event-failed.attempts=1 body-kept=true cards=1 repeat.first=赠金已到账 / 已赠送您 7.00 元 DSH 体验赠金。 repeat.reload=赠金已到账 / 已赠送您 7.00 元 DSH 体验赠金。 repeat.shown added-storage-keys=0 reload-added=0 acks=2 cards=1 @@ -31,6 +34,19 @@ failed.reached usages=2 gets=1 summaries=1 en.notice=Bonus credited / You received a CNY 9.00 DSH trial credit. en.get locale=en_US query= web.notice=赠金已到账 / 已赠送您 4.00 元 DSH 体验赠金。 acks=1 -stack.initial cards=3 acks=stack-first widths=280,272 offset=-4 transition=0.25s ease-out -stack.promoted cards=2 acks=stack-first,stack-second width=280 same-node=true +stack.hidden cards=3 acks=0 +stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=0.25s ease-out +stack.resized sidebar=360 card=280 left-inset=10 +stack.resized sidebar=280 card=260 left-inset=10 +stack.rail cards=3 visible=false dismissed=0 +stack.expanded cards=3 duplicate-acks=0 dismissed=0 +stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true stack.dismissed cards=0 acks=stack-first,stack-second,stack-third +refresh.retained cards=3 acks=refresh-first same-node=true +refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true +refresh.business-action event=cta_clicked cards=3 account-open=true +refresh.drawer width=390 notice-above-sidebar=true +refresh.action event=dismissed got-it=true +refresh.promoted cards=2 acks=refresh-first,refresh-second +refresh.dismissed cards=0 acks=refresh-first,refresh-second,refresh-third +poll.arrival cards=2 list-reads=1 duplicate-acks=0 same-node=true settings-immediate-read=true diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 93993bbe04..5a3a367e7a 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: sk-messa••••••••••ding + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md new file mode 100644 index 0000000000..b1c8c2f328 --- /dev/null +++ b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md @@ -0,0 +1,25 @@ +- dialog "设置": + - text: 设置 + - navigation: + - button "通用设置" + - button "模型" + - button "内置插件" + - button "Agent 预设" + - button "打开配置文件" + - button "关闭" + - heading "模型" [level=2] + - paragraph: 填入各提供商的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: DeepSeek + - img "API 密钥已配置" + - button "编辑 DeepSeek (deepseek-official)": 编辑 + - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" + - textbox "API 密钥": + - /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY) + - paragraph: 保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。 + - group: 自定义设置 + - button "取消" + - button "保存" + - button "添加模型提供商" diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md index b4f0445c07..1e3111ba0c 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -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 diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md index 72d7382c18..e7f09431a2 100644 --- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -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 diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md index 114cf607bf..d5e6cce057 100644 --- a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md +++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md @@ -1,6 +1,7 @@ - text: main - button "基准分支:origin/main": origin/main - text: 包含未提交的修改 +- button "查看的提交:全部提交": 全部提交 - button "创建变更请求" - button "分支" - button "全部 0 个文件" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-layers.expected.md b/apps/web/tests/expected/forge-panel/review-layers.expected.md new file mode 100644 index 0000000000..e160dbbd40 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-layers.expected.md @@ -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 diff --git a/apps/web/tests/expected/forge-panel/review-quotes.expected.md b/apps/web/tests/expected/forge-panel/review-quotes.expected.md index 0f7262a4b1..292dd3382f 100644 --- a/apps/web/tests/expected/forge-panel/review-quotes.expected.md +++ b/apps/web/tests/expected/forge-panel/review-quotes.expected.md @@ -1,6 +1,6 @@ - textbox "发消息或创建任务, / 调用指令, @ 文件或对话": - paragraph: - button "移除引用" - - text: "## User Comment 2 File: src/extra.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const extra = 1 ``` Comment: 请检查这项修改" + - text: src/extra.ts R1 请检查这项修改 - button "移除引用" - - text: "## User Comment 1 File: src/app.ts Side: R Lines: 1 Source: Local (branch) Base: origin/main Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const app = 1 ``` Comment: 请解释这行代码" + - text: src/app.ts R1 请解释这行代码 diff --git a/apps/web/tests/expected/goal-bar/active.expected.md b/apps/web/tests/expected/goal-bar/active.expected.md index cf3227ee51..423676465d 100644 --- a/apps/web/tests/expected/goal-bar/active.expected.md +++ b/apps/web/tests/expected/goal-bar/active.expected.md @@ -1,4 +1,4 @@ - text: Ongoing Goal guard rapid clear clicks -- button "Pause goal" - button "Edit goal" - button "Clear goal" +- button "Pause goal" diff --git a/apps/web/tests/expected/goal-bar/blocked.expected.md b/apps/web/tests/expected/goal-bar/blocked.expected.md index dbfcf5563b..b61a46559d 100644 --- a/apps/web/tests/expected/goal-bar/blocked.expected.md +++ b/apps/web/tests/expected/goal-bar/blocked.expected.md @@ -1,4 +1,4 @@ - text: Blocked Goal retry with the edited plan -- button "Resume goal" - button "Edit goal" - button "Clear goal" +- button "Resume goal" diff --git a/apps/web/tests/expected/goal-bar/inactive.expected.md b/apps/web/tests/expected/goal-bar/inactive.expected.md index 729dbd1dd9..64258bf74b 100644 --- a/apps/web/tests/expected/goal-bar/inactive.expected.md +++ b/apps/web/tests/expected/goal-bar/inactive.expected.md @@ -1,4 +1,4 @@ - text: Inactive Goal guard rapid clear clicks -- button "Resume goal" - button "Edit goal" - button "Clear goal" +- button "Resume goal" diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index a7be30e8c3..3bd004257e 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index b369a619b4..5b10207801 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -17,7 +17,8 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: dsh_onboa•••••••••••••••••••••••••••••••test + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md index 5d275c2323..a7bb6c76e3 100644 --- a/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md +++ b/apps/web/tests/expected/plugin-manager/missing-bundle.expected.md @@ -3,7 +3,7 @@ - status - switch "启用 @fixture/missing-bundle" [checked] - heading "@fixture/missing-bundle" [level=3] -- text: 异常 未安装 +- text: 未运行 未安装 - paragraph: - code: "@fixture/missing-bundle" - status: "原因: dsh: cannot resolve profile bundle \"@fixture/missing-bundle\" from the dsh installation or {{home}}/profiles/scaffold; run 'dsh plugin --profile scaffold install' if its dependency is not installed" diff --git a/apps/web/tests/expected/retained-steering/trajectory.expected.md b/apps/web/tests/expected/retained-steering/trajectory.expected.md index 1cf298260c..c453914925 100644 --- a/apps/web/tests/expected/retained-steering/trajectory.expected.md +++ b/apps/web/tests/expected/retained-steering/trajectory.expected.md @@ -9,9 +9,9 @@ - 'row "CONTEXT, The following information describes your current session: Current working directory: \"{{cwd}}/workspace\". Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}/workspace\". Some platform te…"': - cell "CONTEXT" - 'cell " The following information describes your current session: Current working directory: \"{{cwd}}/workspace\". Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}/workspace\". Some platform te…"' - - 'row "CONTEXT, A skill is a reusable set of task-specific instructions. The following skills are available in this session: office: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step. office-docx: Create, read, edit, and validate Word documents (.docx). office-pptx: Create, read, edit, and validate PowerPoint presentations (.pptx). office-xlsx: Read, cr…"': + - 'row "CONTEXT, A skill is a reusable set of task-specific instructions. The following skills are available in this session: dsh-doc: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skil…"': - cell "CONTEXT" - - 'cell " A skill is a reusable set of task-specific instructions. The following skills are available in this session: office: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step. office-docx: Create, read, edit, and validate Word documents (.docx). office-pptx: Create, read, edit, and validate PowerPoint presentations (.pptx). office-xlsx: Read, cr…"' + - 'cell " A skill is a reusable set of task-specific instructions. The following skills are available in this session: dsh-doc: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skil…"' - 'row "CONTEXT, Time sampled while preparing turn 1, step 1: 2026-01-15T{{clock}}+{{clock}}[Asia/Shanghai] Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone. Elapsed since the preceding model-visible message: unavailable."': - cell "CONTEXT" - 'cell "Time sampled while preparing turn 1, step 1: 2026-01-15T{{clock}}+{{clock}}[Asia/Shanghai] Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone. Elapsed since the preceding model-visible message: unavailable."' diff --git a/apps/web/tests/expected/shortcuts-panels/page-actions.expected.md b/apps/web/tests/expected/shortcuts-panels/page-actions.expected.md index d3e05295e9..0dd762d927 100644 --- a/apps/web/tests/expected/shortcuts-panels/page-actions.expected.md +++ b/apps/web/tests/expected/shortcuts-panels/page-actions.expected.md @@ -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" diff --git a/apps/web/tests/expected/shortcuts-panels/panels.expected.md b/apps/web/tests/expected/shortcuts-panels/panels.expected.md index 5cced821c6..0fca7fdde8 100644 --- a/apps/web/tests/expected/shortcuts-panels/panels.expected.md +++ b/apps/web/tests/expected/shortcuts-panels/panels.expected.md @@ -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 diff --git a/apps/web/tests/expected/shortcuts-workspace/files-open.expected.md b/apps/web/tests/expected/shortcuts-workspace/files-open.expected.md index 8768d85619..d6ac8a0b00 100644 --- a/apps/web/tests/expected/shortcuts-workspace/files-open.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/files-open.expected.md @@ -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 diff --git a/apps/web/tests/expected/stats-paged-history/ui.expected.md b/apps/web/tests/expected/stats-paged-history/ui.expected.md index 34f3cf897d..26d522dbe9 100644 --- a/apps/web/tests/expected/stats-paged-history/ui.expected.md +++ b/apps/web/tests/expected/stats-paged-history/ui.expected.md @@ -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 diff --git a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md index b60114ef0f..b86fcda5f5 100644 --- a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md +++ b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md @@ -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" diff --git a/apps/web/tests/file-browser.e2e.ts b/apps/web/tests/file-browser.e2e.ts index b23b531ee1..ea6a887742 100644 --- a/apps/web/tests/file-browser.e2e.ts +++ b/apps/web/tests/file-browser.e2e.ts @@ -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 => 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) diff --git a/apps/web/tests/fixtures/account-login/cordis.patch.yml b/apps/web/tests/fixtures/account-login/cordis.patch.yml index a31eac8f46..c61c6bfbbf 100644 --- a/apps/web/tests/fixtures/account-login/cordis.patch.yml +++ b/apps/web/tests/fixtures/account-login/cordis.patch.yml @@ -4,6 +4,7 @@ - id: deepseek-account config: platformOrigin: "{{origin}}" + harnessOrigin: "{{origin}}" allowLoopbackHttp: true # The scenario signs in from the account menu after initial setup. - id: ui-settings-account diff --git a/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml b/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml index 11e43d1493..a3a7a9129c 100644 --- a/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml +++ b/apps/web/tests/fixtures/bonus-notice/cordis.patch.yml @@ -1,13 +1,17 @@ # The bonus notice scenario points the shipped account provider at a loopback # Platform double. The scaffold substitutes {{origin}} after the listener binds, -# so no port is ever committed here. No notice timing is overridden: every read -# comes from the product's own startup and settings-refresh paths. +# so no port is ever committed here. A long query interval isolates other notice +# interactions; the polling scenario advances the browser clock explicitly. - id: deepseek-account config: platformOrigin: "{{origin}}" + harnessOrigin: "{{origin}}" allowLoopbackHttp: true # This scenario exercises the account launcher after initial setup. - id: ui-settings-account config: step: done completion: completed +- id: ui-account-notifications + config: + notificationPollIntervalMs: 7200000 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 44f24a6a58..6f6990b494 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -43,10 +43,14 @@ const run = promisify(execFile) * 7 with one failed and one passed check run, one unresolved thread, and a * required review, and pull request 9, an approved draft whose checks passed. * `gh pr ready 9` and the REST merge of pull request 9 change what later - * queries report, through `state.json`. `gh pr diff N` prints `pr-N.diff`, or - * fails with `pr-N.refused` on standard error when that file exists, and the raw - * contents API serves `contents.json`, keyed by `path@commit`. Every invocation - * is appended to `calls.jsonl`. + * queries report, through `state.json`, which can also move the head of pull + * request 9. The compare API serves `compare.json`, keyed by `base...head`, and + * otherwise, between a pull request's recorded base and its head, prints + * `pr-N.diff`, or, when `pr-N.refused` exists, fails with that JSON error body + * and the matching diagnostic as GitHub's HTTP 406 refusal. The raw contents API + * serves `contents.json`, keyed by `path@commit`, and the commit listing of pull + * request 7 serves `commits.json`, oldest first. Every invocation is appended to + * `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -87,13 +91,29 @@ if (args[0] === 'api' && args[4] === 'POST' && ['repos/octo/demo/pulls/7/comment process.stdout.write(JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#pullrequestreview-1' })) process.exit(0) } -if (args[0] === 'pr' && args[1] === 'diff') { - const refused = join(here, 'pr-' + args[2] + '.refused') - if (existsSync(refused)) { - process.stderr.write(readFileSync(refused, 'utf8')) +const BASE = 'e'.repeat(40) +const heads = () => ({ 7: 'a'.repeat(40), 9: state.head ?? 'b'.repeat(40) }) +if (args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')) { + const [, range] = args.at(-1).split('/compare/') + const chosen = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined + if (chosen !== undefined) { + process.stdout.write(chosen) + process.exit(0) + } + const [base, head] = range.split('...') + const number = Object.entries(heads()).find(([, oid]) => oid === head)?.[0] + if (base !== BASE || number === undefined) { + process.stderr.write('gh: Not Found (HTTP 404)\\n') process.exit(1) } - await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve)) + const refused = join(here, 'pr-' + number + '.refused') + if (existsSync(refused)) { + const message = readFileSync(refused, 'utf8') + process.stdout.write(JSON.stringify({ message, errors: [{ resource: 'PullRequest', field: 'diff', code: 'too_large' }], status: '406' })) + process.stderr.write('gh: ' + message + ' (HTTP 406)\\n') + process.exit(1) + } + await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + number + '.diff'), 'utf8'), resolve)) process.exit(0) } if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.raw+json') { @@ -120,25 +140,42 @@ if (args[0] === 'api' && args[1] === 'graphql') { }) const pulls = { 7: { - number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, - updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), + id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, + updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), baseRefOid: BASE, baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', - reviewThreads: { nodes: [{ isResolved: false }] }, + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: { pageInfo: { hasNextPage: true, endCursor: 'checks-100' }, nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)), } } } }] }, }, 9: { - number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', + id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', isDraft: !state.ready, updatedAt: '2026-10-09T00:00:00Z', closedAt: state.mergedAt, author: { login: 'octo' }, - headRefName: 'feat/merge', headRefOid: state.head ?? 'b'.repeat(40), baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE', - mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', reviewThreads: { nodes: [] }, + headRefName: 'feat/merge', headRefOid: heads()[9], baseRefName: 'main', baseRefOid: BASE, additions: 30, deletions: 2, mergeable: 'MERGEABLE', + mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], } } } }] }, }, } + if (query.includes('commits(first: $first')) { + const commits = existsSync(join(here, 'commits.json')) ? JSON.parse(readFileSync(join(here, 'commits.json'), 'utf8')) : [] + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40), commits: { + totalCount: commits.length, pageInfo: { hasNextPage: false, endCursor: null }, + nodes: commits.map(commit => ({ commit: { + oid: commit.sha, messageHeadline: commit.title, authoredDate: '2026-10-08T00:00:00Z', + author: { name: 'Octo', user: { login: 'octo' } }, parents: { nodes: [{ oid: commit.parent }] }, + } })), + } } } } })) + process.exit(0) + } + if (query.includes('pullRequest(number: $number)')) { + const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, baseRefOid: BASE } } } })) + process.exit(0) + } if (query.includes('node(id: $id)')) { process.stdout.write(JSON.stringify({ data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, @@ -165,13 +202,14 @@ process.exit(1) /** Head commit of pull request 7 in the GitHub CLI double. */ const HEAD7 = 'a'.repeat(40) -/** What gh 2.100 prints for the diff of pull request 9 when GitHub refuses it for having over 300 files. */ -const PR9_REFUSAL = [ - 'could not find pull request diff: HTTP 406: Sorry, the diff exceeded the maximum number of files (300). Consider using \'List pull ' - + 'requests files\' API or locally cloning the repository instead. (https://api.github.com/repos/octo/demo/pulls/9)', - 'PullRequest.diff too_large', - '', -].join('\n') +/** Patch of pull request 9: one line added to each of 301 files, more than the pull request diff endpoint accepts. */ +const PR9_DIFF = Array.from({ length: 301 }, (_, index) => [ + `diff --git a/merge/m${index}.ts b/merge/m${index}.ts`, 'index 1111111..2222222 100644', `--- a/merge/m${index}.ts`, `+++ b/merge/m${index}.ts`, + '@@ -1 +1,2 @@', ' export {}', `+export const m${index} = ${index}`, '', +].join('\n')).join('') + +/** Message of the double's HTTP 406 refusal, which it sends in the error body format GitHub uses for a diff over its size limit. */ +const PR9_REFUSAL = 'Sorry, the diff exceeded the size limit.' /** Line `n` of `src/panel.ts` before (`old`) or after (`new`) pull request 7, which changes lines 2 and 15 of its 20. */ function panelLine(n: number, side: 'old' | 'new'): string { @@ -204,6 +242,53 @@ const PR7_DIFF = [ '', ].join('\n') +/** A patch section that adds `lines` as the new file `path`. */ +function addedSection(path: string, lines: readonly string[]): string[] { + return [`diff --git a/${path} b/${path}`, 'new file mode 100644', 'index 0000000..4444444', '--- /dev/null', `+++ b/${path}`, + `@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)] +} + +/** Commits of pull request 7 in the review fixture, oldest first; the last is its head. */ +const REVIEW_COMMITS = [ + { sha: '1'.repeat(40), parent: 'f'.repeat(40), title: 'Add the pull request panel' }, + { sha: '2'.repeat(40), parent: '1'.repeat(40), title: 'Test the panel and translate it' }, + { sha: HEAD7, parent: '2'.repeat(40), title: 'Publish the panel schema' }, +] as const + +/** New files of each review fixture commit after the first, which changes `src/panel.ts` and adds `docs/panel.md`. */ +const REVIEW_SECTIONS = { + test: [ + ...addedSection('src/panel.spec.ts', ['it(\'shows the panel\', () => {})']), + ...addedSection('locale/zh.json', ['{ "title": "面板" }']), + ], + schema: [ + ...addedSection('package.json', ['{ "name": "demo" }']), + ...addedSection('docs/schema.json', ['{ "type": "object" }']), + ], +} + +/** + * Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is + * interface, and the spec, the locale dictionary, which `.gitattributes` places in the test layer, and + * `docs/schema.json`, which it marks generated, are tests. + */ +const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n') + +/** Write the review fixture of pull request 7: its patch, commits, commit ranges, and root `.gitattributes`. */ +async function writeReviewFixture(root: string): Promise { + 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 + 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 { const { stdout } = await run('git', args, { cwd, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } }) return stdout.trim() @@ -243,7 +328,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' await writeFile(gh, GH) await chmod(gh, 0o755) await writeFile(join(root, 'pr-7.diff'), PR7_DIFF) - await writeFile(join(root, 'pr-9.refused'), PR9_REFUSAL) + await writeFile(join(root, 'pr-9.diff'), PR9_DIFF) const panelText = `${Array.from({ length: 20 }, (_, index) => panelLine(index + 1, 'new')).join('\n')}\n` await writeFile(join(root, 'contents.json'), JSON.stringify({ [`src/panel.ts@${HEAD7}`]: panelText })) const overlay = join(root, 'forge.patch.yml') @@ -462,10 +547,14 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'), await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE) - expect(events.flatMap((event) => { - const record = pluginRecordOf(event) - return record?.type === 'plugin:forge-session/binding' ? [record.data] : [] - })).toEqual([{ action: 'reference', url: PULL }]) + await expect.poll(async () => { + await scaffold.ctx.sessionPersistence.flush() + const boundEvents = await readPersistedEvents(scaffold, sessionId) + return boundEvents.flatMap((event) => { + const record = pluginRecordOf(event) + return record?.type === 'plugin:forge-session/binding' ? [record.data] : [] + }) + }).toEqual([{ action: 'reference', url: PULL }]) const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url']) expect(tripwire.pageErrors).toEqual([]) @@ -1005,21 +1094,43 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an expect(await reviewDialog.getByRole('radio', { name: '评论', exact: true }).isChecked()).toBe(true) await page.keyboard.press('Escape') - // GitHub refuses the diff of pull request 9 as too large, so its view offers the web page instead of a retry. + // Pull request 9 changes 301 files, more than the pull request diff endpoint accepts; the compare read shows every file. scaffold.ctx.forgeSession.track(session, DRAFT) await expect.poll(() => header.getAttribute('aria-pressed'), { timeout: 20_000 }).toBe('false') await header.click() const draft = page.locator(`[data-forge-change="${DRAFT}"]`) await draft.getByRole('button', { name: '展开 #9', exact: true }).click() await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 }) - const refused = page.locator('[data-forge-changes="change"]').filter({ hasText: 'Add the merge button' }) - await refused.getByRole('status').filter({ hasText: '变更太大,无法在这里显示' }).waitFor({ timeout: 20_000 }) - await refused.getByRole('button', { name: '在浏览器中查看', exact: true }).waitFor() - expect(await refused.getByRole('button', { name: '重试', exact: true }).count()).toBe(0) + const wide = page.locator('[data-forge-changes="change"]').filter({ hasText: 'Add the merge button' }) + await wide.getByRole('region', { name: '全部 301 个文件', exact: true }).waitFor({ timeout: 20_000 }) + expect(await wide.locator('[data-forge-diff-file]').count()).toBe(301) + + // A push moves the head to a commit whose diff GitHub refuses over its size limit, so a newly opened view offers the web page + // instead of a retry. + await page.locator('[data-dockkit-tab]').filter({ hasText: '#9 的变更' }).locator('[data-dockkit-tab-close]').click() + await expect.poll(() => wide.count()).toBe(0) + await writeFile(join(root, 'state.json'), JSON.stringify({ ready: false, mergedAt: null, head: 'd'.repeat(40) })) + await writeFile(join(root, 'pr-9.refused'), PR9_REFUSAL) + scaffold.ctx.forge.refresh({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 }) + await expect.poll(() => scaffold.ctx.forge.latest({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 }), + { timeout: 20_000 }).toMatchObject({ snapshot: { headSha: 'd'.repeat(40) } }) + if (await header.getAttribute('aria-pressed') !== 'true') await header.click() + const expand = draft.getByRole('button', { name: '展开 #9', exact: true }) + if (await expand.count() > 0) await expand.click() + await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 }) + await wide.getByRole('status').filter({ hasText: '变更太大,无法在这里显示' }).waitFor({ timeout: 20_000 }) + await wide.getByRole('button', { name: '在浏览器中查看', exact: true }).waitFor() + expect(await wide.getByRole('button', { name: '重试', exact: true }).count()).toBe(0) const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) - expect(calls).toContainEqual(['pr', 'diff', '7', '--repo', 'github.com/octo/demo', '--color', 'never']) - expect(calls).toContainEqual(['pr', 'diff', '9', '--repo', 'github.com/octo/demo', '--color', 'never']) + const compared = (head: string) => [ + 'api', '--hostname', 'github.com', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', + `repos/octo/demo/compare/${'e'.repeat(40)}...${head}`, + ] + expect(calls).toContainEqual(compared(HEAD7)) + expect(calls).toContainEqual(compared('b'.repeat(40))) + expect(calls).toContainEqual(compared('d'.repeat(40))) + expect(calls.some(call => call[0] === 'pr' && call[1] === 'diff')).toBe(false) expect(calls).toContainEqual([ 'api', '--hostname', 'github.com', '-H', 'Accept: application/vnd.github.raw+json', `repos/octo/demo/contents/src/panel.ts?ref=${HEAD7}`, ]) @@ -1064,6 +1175,8 @@ it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across return { path: element.getAttribute('data-forge-diff-file'), line: line.dataset.newLine, offset: line.getBoundingClientRect().top - top, scrollTop: viewport.scrollTop } }) + // An expanded file draws its lines once the reader scrolls near it. + await file.scrollIntoViewIfNeeded() await code.waitFor() for (const width of [240, 320]) { if (width === 320) { @@ -1141,6 +1254,11 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre expect(await scroll.evaluate(element => document.activeElement === element)).toBe(true) await page.keyboard.press('ArrowRight') await expect.poll(() => tree.getByRole('button', { name: 'README.md', exact: true }).getAttribute('aria-current')).toBe('true') + // The last file draws its lines after the jump, and scroll anchoring adjusts the position at the next layout. + await c.locator('[data-review-code]').first().waitFor() + await scroll.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + })) const lastPosition = await scroll.evaluate(element => element.scrollTop) const lastBox = await c.boundingBox(), viewport = await scroll.boundingBox() if (lastBox === null || viewport === null) throw new Error('The last file and scroll viewport must be rendered') @@ -1604,3 +1722,184 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor() expect(tripwire.pageErrors).toEqual([]) }) + +/** Open the change request view of pull request 7 in full screen, its tree on the left. */ +async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly view: ReturnType; 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): 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([]) +}) diff --git a/apps/web/tests/goal-bar.e2e.ts b/apps/web/tests/goal-bar.e2e.ts index 132d44569b..348a7520a6 100644 --- a/apps/web/tests/goal-bar.e2e.ts +++ b/apps/web/tests/goal-bar.e2e.ts @@ -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', }) diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 950076a427..d467ccc230 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() - await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByPlaceholder('•'.repeat('sk-e2e-minimax'.length), { exact: true }).waitFor({ timeout: 10_000 }) expect(await dialog.textContent()).not.toContain('API 密钥来源:') expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8706a7a4de..d8d5b9356f 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -33,6 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup let page: Page let tripwire: ReturnType const browserConsole: string[] = [] + const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test` beforeAll(async () => { scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true }) @@ -86,7 +87,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE) - const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}` await keyInput.fill(secret) await credentialStep.getByRole('button', { name: '保存并继续' }).click() await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) @@ -115,7 +115,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe(`dsh_onboa${'•'.repeat(31)}test`) const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -257,7 +257,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe(`dsh_onboa${'•'.repeat(31)}test`) const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f1ea40b25c..72ce0e6872 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -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) diff --git a/apps/web/tests/reasoning-spacing.e2e.ts b/apps/web/tests/reasoning-spacing.e2e.ts new file mode 100644 index 0000000000..aa3b3935a4 --- /dev/null +++ b/apps/web/tests/reasoning-spacing.e2e.ts @@ -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 { + switch (kind) { + case 'reasoning': return { type: 'reasoning', text: `Thinking ${label}\n\nDetails for ${label}.` } + case 'signature': return { type: 'reasoning', text: `${label}` } + 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[] = [] + 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([]) +}) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 82f436c837..adfea25d10 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -124,14 +124,24 @@ describe('web e2e: fresh round trip through the real assembly', () => { let accepted = false try { await input.fill(PROMPT) + // Hold the prompt POST at the browser boundary so the Host cannot accept + // the message before the pre-accept snapshot is read. + const promptSent = Promise.withResolvers() + const releasePrompt = Promise.withResolvers() + const holdPrompt = async (route: Route): Promise => { + promptSent.resolve(undefined) + await releasePrompt.promise + await route.continue() + } + await page.route('**/api/session/prompt', holdPrompt, { times: 1 }) const admitted = page.waitForResponse('**/api/session/prompt') - const [echoSnapshot, response] = await Promise.all([ - input.evaluate(async (element, prompt) => { + try { + const echoCapture = input.evaluate(async (element, prompt) => { element.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true, })) - // sendSession registered its paint yield first. This frame observes the - // composer holding the message while the Host has not accepted it yet. + // sendSession registered its paint yield first; this frame observes the + // composer holding the message while the POST is still held. await new Promise((resolve) => { requestAnimationFrame(() => { resolve() }) }) const echo = document.querySelector('[data-submission-echo]') return [ @@ -139,12 +149,15 @@ describe('web e2e: fresh round trip through the real assembly', () => { `composer: ${JSON.stringify(element.textContent ?? '')}`, `contenteditable: ${element.getAttribute('contenteditable')}`, ].join('\n') - }, PROMPT), - admitted, - ]) + }, PROMPT) + await promptSent.promise + await compareOrRefreshGolden(ECHO_EXPECTED, await echoCapture, MODE) + } finally { + releasePrompt.resolve(undefined) + } + const response = await admitted expect(await response.json()).toMatchObject({ result: { ok: true, value: { accepted: true } } }) accepted = true - await compareOrRefreshGolden(ECHO_EXPECTED, echoSnapshot, MODE) // Acceptance publishes the echo and clears the composer; maintenance keeps the Turn from starting. await page.locator('[data-submission-echo]', { hasText: PROMPT }).waitFor() await expect.poll(() => input.textContent()).toBe('') diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 9119cd3235..71a1f38975 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -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, diff --git a/apps/web/tests/settings-appearance.e2e.ts b/apps/web/tests/settings-appearance.e2e.ts index fa55a444df..26be4bdedc 100644 --- a/apps/web/tests/settings-appearance.e2e.ts +++ b/apps/web/tests/settings-appearance.e2e.ts @@ -149,7 +149,7 @@ it('shares settings card materials and control sizes in both palettes', async () bonusWallets: [{ currency: 'CNY', balance: '12.00' }], }), vi.spyOn(account, 'watch').mockImplementation(async function* (signal) { - yield state + yield { type: 'snapshot', state } if (signal.aborted) return await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) }), diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index 36b74d0e88..35a08e5fb2 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -479,7 +479,6 @@ const EXPECTED_TOOLS = [ 'edit', 'exit_plan_mode', 'get_goal', - 'interrupt_agent', 'job_kill', 'job_list', 'job_output', diff --git a/apps/web/tests/shortcuts-desktop.e2e.ts b/apps/web/tests/shortcuts-desktop.e2e.ts index 7560831694..2c42e082da 100644 --- a/apps/web/tests/shortcuts-desktop.e2e.ts +++ b/apps/web/tests/shortcuts-desktop.e2e.ts @@ -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 } }) diff --git a/apps/web/tests/shortcuts-panels.e2e.ts b/apps/web/tests/shortcuts-panels.e2e.ts index bdfe036343..9cf2ab6ab5 100644 --- a/apps/web/tests/shortcuts-panels.e2e.ts +++ b/apps/web/tests/shortcuts-panels.e2e.ts @@ -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) diff --git a/apps/web/tests/shortcuts-workspace.e2e.ts b/apps/web/tests/shortcuts-workspace.e2e.ts index d7c81823c2..7ddaf59227 100644 --- a/apps/web/tests/shortcuts-workspace.e2e.ts +++ b/apps/web/tests/shortcuts-workspace.e2e.ts @@ -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 }, diff --git a/apps/web/tests/sidebar-alignment.e2e.ts b/apps/web/tests/sidebar-alignment.e2e.ts index ed5fced520..7f5ecdeabe 100644 --- a/apps/web/tests/sidebar-alignment.e2e.ts +++ b/apps/web/tests/sidebar-alignment.e2e.ts @@ -519,7 +519,7 @@ describe('web e2e: sidebar search alignment and row action targets', () => { }), vi.spyOn(account, 'getBalance').mockResolvedValue({ status: 'ready', value: [], bonusWallets: [] }), vi.spyOn(account, 'watch').mockImplementation(async function* (signal) { - yield state + yield { type: 'snapshot', state } if (signal.aborted) return await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) }), diff --git a/apps/web/tests/standard-dsh-doc.e2e.ts b/apps/web/tests/standard-dsh-doc.e2e.ts new file mode 100644 index 0000000000..26d920ac98 --- /dev/null +++ b/apps/web/tests/standard-dsh-doc.e2e.ts @@ -0,0 +1,51 @@ +/** Standard mode offers the installed documentation skill without loading it for an unrelated task. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { dirname } from 'node:path' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { assertFixtureInventory, fixtureUserPrompts, launchWebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/standard-dsh-doc/session.v4.jsonl', import.meta.url)) + +it('lists dsh-doc once without loading instructions or calling tools for an ordinary task', async () => { + const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, compareReplaySession: true, paceMs: 10 }) + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const prompts = fixtureUserPrompts(await readFile(FIXTURE, 'utf8')) + expect(prompts).toHaveLength(1) + const settled = scaffold.whenTurnSettled() + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + await composer.fill(prompts[0]!) + await composer.press('Enter') + const sessionId = await settled + const agent = scaffold.ctx.agents.get(sessionId) + if (agent === undefined) throw new Error('standard documentation session is missing') + const events = agent.session.snapshotEvents() + expect(events.filter(event => event.type === 'tool/call')).toEqual([]) + const catalogs = events.flatMap(event => event.type === 'user/message' + && event.data.source.kind === 'skill-catalog' ? [event.data] : []) + expect(catalogs).toHaveLength(1) + const skills = await scaffold.ctx.skills.list({ cwd: agent.session.header.cwd, scope: agent }) + expect(skills.filter(skill => skill.name === 'dsh-doc')).toHaveLength(1) + expect(catalogs[0]?.source).toMatchObject({ entries: skills.map(skill => ({ name: skill.name })) }) + expect(events.filter(event => event.type === 'user/message' + && event.data.source.kind === 'skill-invocation')).toEqual([]) + const names = scaffold.ctx.tools.schemas(agent).map(tool => tool.name) + expect(names).not.toContain('cordis_inspect_list') + expect(names).not.toContain('cordis_inspect_query') + await page.getByText('READY', { exact: true }).waitFor() + await assertFixtureInventory(dirname(FIXTURE), ['session.v4.jsonl']) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/stats-paged-history.e2e.ts b/apps/web/tests/stats-paged-history.e2e.ts index 5531a4dbda..27c494e4aa 100644 --- a/apps/web/tests/stats-paged-history.e2e.ts +++ b/apps/web/tests/stats-paged-history.e2e.ts @@ -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 diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 9690154afe..a3345c93bf 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -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() diff --git a/apps/web/tests/tool-details.e2e.ts b/apps/web/tests/tool-details.e2e.ts index 8a51e66d44..93963c070e 100644 --- a/apps/web/tests/tool-details.e2e.ts +++ b/apps/web/tests/tool-details.e2e.ts @@ -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() diff --git a/apps/web/tests/workspace-recency.e2e.ts b/apps/web/tests/workspace-recency.e2e.ts index 18c454bc88..507b95fca7 100644 --- a/apps/web/tests/workspace-recency.e2e.ts +++ b/apps/web/tests/workspace-recency.e2e.ts @@ -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') diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 7294b2fd47..a70870d5ec 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -89,6 +89,7 @@ "tests/trajectory-virtualization.e2e.ts", "tests/lifecycle-chrome.e2e.ts", "tests/reasoning-preview.e2e.ts", + "tests/reasoning-spacing.e2e.ts", "tests/details-session-lifecycle.e2e.ts", "tests/sessionless-header.e2e.ts", "tests/document-preview.e2e.ts", @@ -210,6 +211,8 @@ "tests/queue-image.e2e.ts", "tests/skill-invocation-policy.e2e.ts", "tests/skill-user-invoke.e2e.ts", + "tests/standard-dsh-doc.e2e.ts", + "tests/creator-persona.e2e.ts", "tests/skill-menu-plugin-change.e2e.ts", "tests/permission-policy-context.e2e.ts", "tests/access-confirmation.e2e.ts", @@ -230,6 +233,7 @@ "tests/goal-bar.e2e.ts", "tests/goal-command-presentation.e2e.ts", "tests/subagent-conversation.e2e.ts", + "tests/composer-paste-routing.e2e.ts", "tests/subagent-interrupt.e2e.ts", "tests/subagent-interrupt-ui.e2e.ts", "tests/sidebar-subagent-activity.e2e.ts", diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 573a7492dc..d897229806 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -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 diff --git a/docs/architecture.md b/docs/architecture.md index 05ecbdcf3b..c7c036016b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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). diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index e7e5ebf8d0..2eae113769 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -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)。 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 5cf559474b..77f025f1e9 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: bc25cf8be90065dc - zh: ae0def4872a9cdd9 + en: b76743a3ff14d2f4 + zh: 82431aa3ded14a89 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index f46656e06d..145a4f5317 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -142,8 +142,6 @@ flowchart LR pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] - pkg_deepseek_account_platform["deepseek-account-platform"] - pkg_api_account_controller["api-account-controller"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -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. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 3deee7e895..5effa1f8c4 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -144,8 +144,6 @@ flowchart LR pkg_credentials_local["credentials-local"] pkg_deepseek_account["deepseek-account"] svc_deepseekAccount["ctx.deepseekAccount
DeepSeek account"] - pkg_deepseek_account_platform["deepseek-account-platform"] - pkg_api_account_controller["api-account-controller"] pkg_authorization["authorization"] svc_authorization["ctx.authorization
Authorization flow registry"] pkg_client_product_analytics["client-product-analytics"] @@ -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 反馈适配器通过同一个注入服务创建独立上报通道。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..e6c96fafbc 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -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 } ``` @@ -578,6 +594,22 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-client-ui-account-notifications` + +- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts) + +```ts config-catalog +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +``` + + @@ -625,16 +657,12 @@ export interface Config extends ContactConfig { developerTools: Volatile } -/** Questionnaire destination and bonus notice timings shared by Host and Client. */ +/** Questionnaire destination shared by Host and Client. */ export interface ContactConfig { /** HTTPS questionnaire URL; override for a test form. */ contactFormUrl: string /** Questionnaire source option; empty until Harness is supported by the form. */ contactSource: string - /** First delay before retrying a failed bonus acknowledgement. */ - bonusAckRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - bonusAckRetryMaxDelayMs: number } /** Persisted steps; a native top-up page leaves the durable step at credit. */ @@ -858,19 +886,21 @@ export interface Config { ``` - - + + -## `@deepseek-ai/dsh-deepseek-account-platform` +## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string + /** Harness API origin for account notifications. */ + harnessOrigin?: string /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ @@ -881,9 +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 - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ accountRequestHeaders?: Record /** Deadline for each platform HTTP request. */ requestTimeoutMs?: number @@ -897,7 +929,7 @@ export interface Config { attemptTimeoutMs?: number } ``` - + @@ -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[] } ``` @@ -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:279`](../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 } ``` @@ -1511,7 +1561,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:35`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1530,7 +1580,11 @@ export interface Config { timeoutMs?: number /** Subprocess termination grace in milliseconds. */ graceMs?: number - /** Maximum captured bytes per subprocess output stream. */ + /** + * Maximum captured bytes per subprocess output stream; archive inspection + * streams `git status`, and inspection and restoration stream the worktree + * listing, so it bounds only their stderr. + */ maxOutputBytes?: number } ``` @@ -4990,7 +5044,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 +5172,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 +5265,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) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..c6b8e1f2c8 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -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 } ``` @@ -580,6 +596,22 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-client-ui-account-notifications` + +- `source`: [`packages/client/ui-account-notifications/src/config.ts:5`](../packages/client/ui-account-notifications/src/config.ts) + +```ts config-catalog +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +``` + + @@ -627,16 +659,12 @@ export interface Config extends ContactConfig { developerTools: Volatile } -/** Questionnaire destination and bonus notice timings shared by Host and Client. */ +/** Questionnaire destination shared by Host and Client. */ export interface ContactConfig { /** HTTPS questionnaire URL; override for a test form. */ contactFormUrl: string /** Questionnaire source option; empty until Harness is supported by the form. */ contactSource: string - /** First delay before retrying a failed bonus acknowledgement. */ - bonusAckRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - bonusAckRetryMaxDelayMs: number } /** Persisted steps; a native top-up page leaves the durable step at credit. */ @@ -860,19 +888,21 @@ export interface Config { ``` - - + + -## `@deepseek-ai/dsh-deepseek-account-platform` +## `@deepseek-ai/dsh-deepseek-account` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account/src/index.ts:40`](../packages/credentials/deepseek-account/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string + /** Harness API origin for account notifications. */ + harnessOrigin?: string /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ @@ -883,9 +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 - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ accountRequestHeaders?: Record /** Deadline for each platform HTTP request. */ requestTimeoutMs?: number @@ -899,7 +931,7 @@ export interface Config { attemptTimeoutMs?: number } ``` - + @@ -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[] } ``` @@ -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:279`](../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 } ``` @@ -1513,7 +1563,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official' - `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/worktree/src/index.ts:35`](../packages/experimental/worktree/src/index.ts) +- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts) ```ts config-catalog /** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */ @@ -1532,7 +1582,11 @@ export interface Config { timeoutMs?: number /** Subprocess termination grace in milliseconds. */ graceMs?: number - /** Maximum captured bytes per subprocess output stream. */ + /** + * Maximum captured bytes per subprocess output stream; archive inspection + * streams `git status`, and inspection and restoration stream the worktree + * listing, so it bounds only their stderr. + */ maxOutputBytes?: number } ``` @@ -4992,7 +5046,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 +5174,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 +5267,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) | diff --git a/docs/defensive-patterns/remote-and-api.i18n.yaml b/docs/defensive-patterns/remote-and-api.i18n.yaml index c16a005c98..0e705303e6 100644 --- a/docs/defensive-patterns/remote-and-api.i18n.yaml +++ b/docs/defensive-patterns/remote-and-api.i18n.yaml @@ -12,5 +12,5 @@ en: 86422ee69c63f339 zh: 4a5e8d6f5d9a6ae3 /remote-and-api-rules/packages-api-carries-generic-orchestration-only: - en: 12a964b9c04fccf9 - zh: cf804f8044535727 + en: b9991b7ffcbf9029 + zh: bb7ef15064e922be diff --git a/docs/defensive-patterns/remote-and-api.md b/docs/defensive-patterns/remote-and-api.md index 5bfda3bd19..d79fa0309d 100644 --- a/docs/defensive-patterns/remote-and-api.md +++ b/docs/defensive-patterns/remote-and-api.md @@ -84,7 +84,7 @@ The hand-written copy drifts from the generated type without failing a build, th The packages under `packages/api` — the controllers, `gateway`, and `remotes` — carry transport, call shape, Session lifecycle, and other generic orchestration. A business branch never aggregates there: a decision that depends on concrete business state, handling bound to one feature, or a per-feature filter belongs in its own package or module and reaches this layer as projected data or through a registration surface. The criterion is where the logic belongs, not where the file sits, so a branch that only makes sense for one feature is a defect even when the file holding it is generic. -- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds nine packages — `account-controller`, `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3, account-controller 2). +- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds eight packages — `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3). - Not covered: generic Session lifecycle, transport, and storage abstraction stay — `gateway` dispatch, `remotes` selection, and shared session-list and catalog reads are infrastructure, not business logic. [Business ownership](../api-gateway.md#business-ownership) states the same split from the Gateway side. - Exception: none by default. Adding a business branch here needs an independent-package review, and that review answers why the logic cannot live in the package that owns the feature. - Fix: move the decision into the owning package, publish its result as projected data or register it on a registry this layer already injects, and leave only the orchestration that reads it. diff --git a/docs/defensive-patterns/remote-and-api.zh.md b/docs/defensive-patterns/remote-and-api.zh.md index 46e1925ef9..5ff8385c96 100644 --- a/docs/defensive-patterns/remote-and-api.zh.md +++ b/docs/defensive-patterns/remote-and-api.zh.md @@ -84,7 +84,7 @@ type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written `packages/api` 下的包——各 controller、`gateway`、`remotes`——承载传输、调用形态、Session 生命周期等通用编排。业务分支绝不在其中聚合:依赖具体业务状态的判断、与单个功能绑定的处理、逐功能的过滤,都归独立包或模块,并作为投影数据或经注册面接入本层。判据是逻辑的归属,而不是文件的位置,所以只对一个功能成立的业务分支即使放在通用文件里也是缺陷。 -- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 9 个包——`account-controller`、`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3、account-controller 2)。 +- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 8 个包——`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3)。 - 不覆盖:通用 Session 生命周期、传输与存储抽象留下——`gateway` 的分发、`remotes` 的选择、共享的会话列表与目录读取属于基础设施,不是业务逻辑。[业务所有权](../api-gateway.zh.md#business-ownership)从 Gateway 一侧给出同一个划分。 - 例外:默认无例外。在此新增业务分支须走独立包评审,评审要回答这些逻辑为什么不能住在拥有该功能的包里。 - 修法:把判断移进归属包,将其结果作为投影数据发布、或注册到本层本就注入的注册表上,这里只留下读取它的编排。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d6514e9585..eb32364097 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -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` | @@ -62,19 +62,19 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:458`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:465`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:444`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:472`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:461`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | | `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | @@ -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) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 38d90599f9..ae28c03fc4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -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` | @@ -64,19 +64,19 @@ | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:458`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:465`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:444`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:472`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:455`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:461`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | | `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | @@ -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) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..a3a28f92fc 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -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) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..9e337229b4 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -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) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index a5fb682b48..baef62d6d9 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -12,8 +12,8 @@ en: 35ffb6107a5fbae2 zh: 06ce2128075e157b /session-persistence-event-catalog/event-envelope: - en: 56414ffd00cdc32a - zh: 6dc11eb013e95e41 + en: 189352d7a3bba620 + zh: 5361f42035034672 /session-persistence-event-catalog/events: en: f4776ba3d0fd53ce zh: e86769f50a69055a diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6b80fbbc99..3f70236194 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -161,7 +161,7 @@ export type SessionEvent = { }[T] ``` -Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts) +Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:506`](../packages/core/session/src/types.ts) ## Events diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c73b594c28..adfc4971e9 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -163,7 +163,7 @@ export type SessionEvent = { }[T] ``` -来源:[`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts) +来源:[`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:506`](../packages/core/session/src/types.ts) ## 事件 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 40264ec898..a00dc512ef 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -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. */ diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index ff1d3b579e..5cb66a1692 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -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. */ diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index bad9827407..174bd14fc4 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -12,14 +12,14 @@ en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: f7b09588c0f34952 - zh: 1b93d673c5bf6a80 + en: 60ce885c8cac3082 + zh: 9f1cf7d25119cdda /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb /user-credentials/embedded-platform-credentials: - en: 78240c18fc9a085d - zh: dabf5fae10b54663 + en: 6f80d44cdec8e05a + zh: 658e5e4958f9baa6 /user-credentials/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit: - en: 314e5b36f51b2c64 - zh: 0e1cb3fe5adf5ecd + en: 664f0f89d89ac686 + zh: 178263324ad76307 diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..444b2b8a52 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -32,13 +32,12 @@ interface ResolvedCredential { ## Description -`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. +`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The optional `masked` field carries a provider-generated preview without the full credential. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** - * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * Configuration facts and an optional provider-masked preview for one + * reference. The full credential is never part of this view. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ @@ -47,6 +46,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Provider-generated masked preview of a stored value; never the full value. */ + masked?: string } ``` @@ -56,7 +57,7 @@ interface CredentialInfo { ## Embedded Platform credentials -PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account-controller RPC, AccountView, and AccountDetails. +PlatformSession is a Host-only snapshot from getPlatformSession: origin names the configured Platform issuer and token contains its stored account credential. userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID. The snapshot reuses that ID without issuing a profile request of its own, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser storage by origin and userId and fall back to temporary storage for null. Signed-out accounts and credentials changed during the credential read return no snapshot; a mismatched issuer fails. Native consumers own document invalidation when credentials change. This snapshot is excluded from account Remote API, AccountView, and AccountDetails. AccountDetails.balance projects recharge wallets in value and promotional wallets in bonusWallets, with independent currency and decimal balance strings. Failed queries contain no wallet arrays. @@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise /** * Describe one reference for configuration surfaces without exposing the - * value. + * full value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional masked preview. */ abstract describe(ref: CredentialRef): Promise @@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent ### `ctx.credentialsController` — `CredentialsController` -Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one. +Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one. ```ts cordis-catalog /** @@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - + -### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam) +### `ctx.deepseekAccount` — `DeepSeekAccount` -Account operations; only Host consumers can obtain a request credential. +Account login, credentials, and client-safe Remote operations. ```ts cordis-catalog /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ -abstract getState(): Promise +@Remote async getState(): Promise /** * Query Platform profile independently of wallet balances. @@ -281,30 +282,65 @@ abstract getState(): Promise * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ -abstract getProfile(client: AccountClientMetadata): Promise +@Remote async getProfile(client: AccountClientMetadata): Promise /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ -abstract getBalance(client: AccountClientMetadata): Promise +@Remote getBalance(client: AccountClientMetadata): Promise /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ -abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise +@Remote async getNotifications(client: AccountClientMetadata): Promise /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ -abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise /** * Join an active attempt or start browser authorization. @@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ -abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ -abstract cancelSignIn(id: SignInAttemptId): Promise +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ -abstract signOut(client: AccountClientMetadata): Promise +@Remote signOut(client: AccountClientMetadata): Promise /** - * Subscribe to snapshots including a complete initial state. + * Inspect running work before sign-out. + * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ -abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ -abstract resolveToken(url: string): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -abstract rejectToken(token: string): Promise - -/** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -abstract getPlatformSession(): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable ``` Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) @@ -488,6 +517,6 @@ Local grant removal has completed. Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) -The account Service Definition exposes getState, getProfile, getBalance, getUnnotifiedBonuses, ackBonusNotified, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. See [the account package](../../packages/credentials/deepseek-account/README.md). +The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/credentials/deepseek-account/README.md). `AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..ce9fbdadd5 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -32,13 +32,12 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 +`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。可选的 `masked` 字段携带提供方生成的脱敏预览,不包含完整凭据。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** - * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * Configuration facts and an optional provider-masked preview for one + * reference. The full credential is never part of this view. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ @@ -47,6 +46,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Provider-generated masked preview of a stored value; never the full value. */ + masked?: string } ``` @@ -56,7 +57,7 @@ interface CredentialInfo { ## 内嵌 Platform 凭证 -PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号控制器 RPC、AccountView 和 AccountDetails 均不包含此快照。 +PlatformSession 是 getPlatformSession 返回的仅限 Host 快照:origin 指定所配置的 Platform 签发来源,token 包含其已存账号凭证。userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器存储的键,为 null 时退回临时存储。账号已退登或读取凭证期间凭证变化时不返回快照;签发来源不匹配时失败。原生使用方负责在凭证变化时使文档失效。账号 Remote API、AccountView 和 AccountDetails 均不包含此快照。 AccountDetails.balance 将充值钱包投影为 value、赠送钱包投影为 bonusWallets,分别保留币种和十进制余额字符串。查询失败不包含钱包数组。 @@ -154,9 +155,9 @@ abstract resolve(ref: CredentialRef): Promise /** * Describe one reference for configuration surfaces without exposing the - * value. + * full value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional masked preview. */ abstract describe(ref: CredentialRef): Promise @@ -228,7 +229,7 @@ Source: [`packages/credentials/credentials/src/index.ts`](../../packages/credent ### `ctx.credentialsController` — `CredentialsController` -Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Secret values cross in one direction only — no method here returns one. +Host service backing the generated `ctx.remote.credentials` namespace. It carries every wire obligation the credential seam itself does not: the batch fan-out bound, the field-by-field view projection, the reference-grammar guard, and the refusal mapping. Full secret values cross in one direction only — no method here returns one. ```ts cordis-catalog /** @@ -261,18 +262,18 @@ Host service backing the generated `ctx.remote.credentials` namespace. It carrie Source: [`packages/api/settings-controller/src/credentials.ts`](../../packages/api/settings-controller/src/credentials.ts) - + -### `ctx.deepseekAccount` — `DeepSeekAccount` (abstract seam) +### `ctx.deepseekAccount` — `DeepSeekAccount` -Account operations; only Host consumers can obtain a request credential. +Account login, credentials, and client-safe Remote operations. ```ts cordis-catalog /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ -abstract getState(): Promise +@Remote async getState(): Promise /** * Query Platform profile independently of wallet balances. @@ -281,30 +282,65 @@ abstract getState(): Promise * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ -abstract getProfile(client: AccountClientMetadata): Promise +@Remote async getProfile(client: AccountClientMetadata): Promise /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ -abstract getBalance(client: AccountClientMetadata): Promise +@Remote getBalance(client: AccountClientMetadata): Promise /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ -abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise +@Remote async getNotifications(client: AccountClientMetadata): Promise /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ -abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise +@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise + +/** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ +@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise + +/** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ +async rejectToken(token: string): Promise + +/** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ +async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + +/** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ +async getPlatformSession(): Promise + +/** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ +async resolveToken(url: string): Promise /** * Join an active attempt or start browser authorization. @@ -313,56 +349,49 @@ abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ -abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise +@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ -abstract cancelSignIn(id: SignInAttemptId): Promise +@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ -abstract signOut(client: AccountClientMetadata): Promise +@Remote signOut(client: AccountClientMetadata): Promise /** - * Subscribe to snapshots including a complete initial state. + * Inspect running work before sign-out. + * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + */ +@Remote hasRunningAccountTasks(): boolean + +/** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ +@Remote({ mode: 'stream' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> + +/** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ -abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable +watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ -abstract resolveToken(url: string): Promise - -/** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ -abstract rejectToken(token: string): Promise - -/** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ -abstract getPlatformSession(): Promise - -/** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ -abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> +@Remote({ name: 'watch', mode: 'stream' }) watchState(signal: AbortSignal): AsyncIterable ``` Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) @@ -488,6 +517,6 @@ Local grant removal has completed. Source: [`packages/credentials/deepseek-account/src/index.ts`](../../packages/credentials/deepseek-account/src/index.ts) -账号服务定义提供 getState、getProfile、getBalance、getUnnotifiedBonuses、ackBonusNotified、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 +账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/credentials/deepseek-account/README.zh.md)。 `AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。 diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 3f4994aa39..97ebf7bece 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -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 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f36141ea1b..208c6a5d9f 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -68,15 +68,60 @@ interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** 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 + /** + * 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. `base`, when given, is the `baseSha` the + * latest status recorded with `headSha`; a provider may start reading from it before it confirms the head. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** 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 + /** + * 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 } ``` +```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 { @@ -155,6 +200,11 @@ interface ChangeRequestSnapshot { readonly headSha: string /** Branch the change request merges into. */ readonly baseBranch: string + /** + * Base commit the host recorded with `headSha`, whose merge base with the head starts the change request's diff; + * omitted when the provider does not report it. + */ + readonly baseSha?: string /** Lines the change request adds. */ readonly additions: number /** Lines the change request deletes. */ @@ -176,8 +226,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 +243,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 +621,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 +642,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 +707,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 +737,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 +760,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> } ``` +```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 +909,40 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * 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. When the latest status of a watched change request names + * `headSha`, its `baseSha` goes to the provider, which may then read the patch while it confirms the head. * @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 +async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * 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 + +/** + * 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 /** * Publish one comment or a completed review, then refresh the watched status. @@ -975,21 +1097,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 +/** + * 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 + /** * 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 @@ -1006,19 +1144,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 /** - * 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 +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * 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 /** * Read one file of a change request's repository at a commit, which diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 61c53fbd6c..0d6fba5c35 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -68,15 +68,60 @@ interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** 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 + /** + * 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. `base`, when given, is the `baseSha` the + * latest status recorded with `headSha`; a provider may start reading from it before it confirms the head. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** 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 + /** + * 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 } ``` +```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` 与 `ctx.forge.compare` 委托给同时实现两者的提供方;否则 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此 forge 面板只在提供方能读取提交时提供提交选择器。 + ```ts type-equiv /** Whether a provider can reach one host with the current credentials. */ interface ForgeReadiness { @@ -155,6 +200,11 @@ interface ChangeRequestSnapshot { readonly headSha: string /** Branch the change request merges into. */ readonly baseBranch: string + /** + * Base commit the host recorded with `headSha`, whose merge base with the head starts the change request's diff; + * omitted when the provider does not report it. + */ + readonly baseSha?: string /** Lines the change request adds. */ readonly additions: number /** Lines the change request deletes. */ @@ -176,8 +226,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 +243,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 +621,20 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 +变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。 + +```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 +642,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 +707,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 +737,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 +760,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> } ``` +```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 +909,40 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * 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. When the latest status of a watched change request names + * `headSha`, its `baseSha` goes to the provider, which may then read the patch while it confirms the head. * @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 +async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * 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 + +/** + * 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 /** * Publish one comment or a completed review, then refresh the watched status. @@ -975,21 +1097,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 +/** + * 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 + /** * 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 @@ -1006,19 +1144,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 /** - * 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 +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * 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 /** * Read one file of a change request's repository at a commit, which diff --git a/docs/subsystems/mcp.md b/docs/subsystems/mcp.md index a07100c4e7..da3c4539a3 100644 --- a/docs/subsystems/mcp.md +++ b/docs/subsystems/mcp.md @@ -86,7 +86,9 @@ type McpResourceRequest = /** One configured server's resource access, owned by its MCP connection plugin. */ interface McpResourceProvider { /** - * Run an operation against one live connection generation. + * Run an operation against one live connection generation. The resource tools + * dispatch in parallel, so one provider may receive several concurrent requests; + * each must settle independently. * @param request - MCP resource method and parameters. * @param exec - caller identity and cancellation for this invocation. * @returns the protocol result as lossless JSON. diff --git a/docs/subsystems/mcp.zh.md b/docs/subsystems/mcp.zh.md index 216db4413a..a2eecf3f11 100644 --- a/docs/subsystems/mcp.zh.md +++ b/docs/subsystems/mcp.zh.md @@ -86,7 +86,9 @@ type McpResourceRequest = /** One configured server's resource access, owned by its MCP connection plugin. */ interface McpResourceProvider { /** - * Run an operation against one live connection generation. + * Run an operation against one live connection generation. The resource tools + * dispatch in parallel, so one provider may receive several concurrent requests; + * each must settle independently. * @param request - MCP resource method and parameters. * @param exec - caller identity and cancellation for this invocation. * @returns the protocol result as lossless JSON. diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml index b4cd4bba34..2c56dc6e76 100644 --- a/docs/subsystems/session.i18n.yaml +++ b/docs/subsystems/session.i18n.yaml @@ -39,8 +39,11 @@ en: 13820e0611b2e141 zh: 2aafb1e5e3dc42f6 /sessions/session-public-api: - en: 04e9982948d9560d - zh: 221961cadebc6fb1 + en: 2dbf1890d8c38701 + zh: 9948971a092b3243 +/sessions/session-public-api/sessioneventinput-one-proposed-event: + en: 90c3989856a301dc + zh: 839a494d5b2b1fa4 /sessions/derived-history-derivemessages-and-deriveeventmessage: en: 45d1a9ee6d610ac5 zh: 79c061252fde4ceb diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index 7a0ad908d9..c1651bf32e 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -447,6 +447,17 @@ interface SurfaceFoldResult { ## `Session` public API +### `SessionEventInput` — one proposed event + +```ts type-equiv +/** One positional event call proposed for append, without assigned sequence or time. */ +type SessionEventInput = { + [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []] +}[SessionEventType] +``` + +Each array member keeps its event type paired with its payload and requires surface intent only for message-producing events. + The body-stripped declaration keeps the plain class's detached factory, state accessors, append method, and history projections synchronized with source. Store operations remain in the generated [`ctx.sessions` section](#ctxsessions--sessionstore). ```ts public-api @@ -573,6 +584,18 @@ declare class Session { isOwnSeq(seq: SessionSeq): boolean; /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */ get seq(): SessionLogOffset; + /** Current event while synchronously notifying a batch's observers. */ + get currentBatchPublication(): SessionEvent | undefined; + /** + * Append consecutive events together after validating every candidate and dispatch. + * Observers read the complete committed log and final message surface. + * Listener registration changes during publication take effect on the next append. + * Persistence listeners retain their own durability rules. + * @param inputs - event payloads and surface intents in commit order. An empty array records no events. + * @returns immutable committed events in the same order. + * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails. + */ + append(inputs: readonly SessionEventInput[]): readonly SessionEvent[]; /** * Append one typed event to the log and synchronously notify observers via * the store-owned, module-private publication hooks. The hot path never blocks @@ -1384,13 +1407,16 @@ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/i #### `session/event` — emit -Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context. +Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context. ```ts cordis-catalog /** * Post-commit, fire-and-forget append feed. The listener snapshot resolves * before the log push, but callbacks run after it; observer failures are * logged and contained without making the committed append fail. + * Array append commits every member before publishing them in order; + * `session.seq` and `session.surface` already include the complete batch. + * `session.currentBatchPublication` identifies the member being delivered. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners * receive only events from sessions entered through that agent's context. * @param session - the session whose log grew. diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index ec9fab642f..e359382e86 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -449,6 +449,17 @@ interface SurfaceFoldResult { ## `Session` 公共 API +### `SessionEventInput`:一个候选事件 + +```ts type-equiv +/** One positional event call proposed for append, without assigned sequence or time. */ +type SessionEventInput = { + [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []] +}[SessionEventType] +``` + +数组中的每个成员将事件类型与对应载荷配对,且仅对产生消息的事件要求surface意图。 + 去除方法体的声明与源码中的普通类保持同步,覆盖其脱离态工厂、状态访问器、append 方法和历史投影。存储操作仍由生成的 [`ctx.sessions` 小节](#ctxsessions--sessionstore)记录。 ```ts public-api @@ -575,6 +586,18 @@ declare class Session { isOwnSeq(seq: SessionSeq): boolean; /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */ get seq(): SessionLogOffset; + /** Current event while synchronously notifying a batch's observers. */ + get currentBatchPublication(): SessionEvent | undefined; + /** + * Append consecutive events together after validating every candidate and dispatch. + * Observers read the complete committed log and final message surface. + * Listener registration changes during publication take effect on the next append. + * Persistence listeners retain their own durability rules. + * @param inputs - event payloads and surface intents in commit order. An empty array records no events. + * @returns immutable committed events in the same order. + * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails. + */ + append(inputs: readonly SessionEventInput[]): readonly SessionEvent[]; /** * Append one typed event to the log and synchronously notify observers via * the store-owned, module-private publication hooks. The hot path never blocks @@ -1388,13 +1411,16 @@ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/i #### `session/event` — emit -Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context. +Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context. ```ts cordis-catalog /** * Post-commit, fire-and-forget append feed. The listener snapshot resolves * before the log push, but callbacks run after it; observer failures are * logged and contained without making the committed append fail. + * Array append commits every member before publishing them in order; + * `session.seq` and `session.surface` already include the complete batch. + * `session.currentBatchPublication` identifies the member being delivered. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners * receive only events from sessions entered through that agent's context. * @param session - the session whose log grew. diff --git a/docs/subsystems/sidebar-right.i18n.yaml b/docs/subsystems/sidebar-right.i18n.yaml index 37bd0f9433..81b6399d55 100644 --- a/docs/subsystems/sidebar-right.i18n.yaml +++ b/docs/subsystems/sidebar-right.i18n.yaml @@ -27,8 +27,8 @@ en: 2916306e6cb9282c zh: cdec047989860202 /right-sidebar/workspace-files: - en: 2b1b49dbba9cc9ee - zh: 13d2a45224743b37 + en: 264e28c7cdf4ae5d + zh: a516ea0d8db9437c /right-sidebar/shipped-types: en: f8f0e368701f6669 zh: de364aaf3345d70c diff --git a/docs/subsystems/sidebar-right.md b/docs/subsystems/sidebar-right.md index 5cc25a74bc..2e661bfb4a 100644 --- a/docs/subsystems/sidebar-right.md +++ b/docs/subsystems/sidebar-right.md @@ -135,7 +135,7 @@ A resource stays open while it has a holder — a subscribed `useResource` or a ## Workspace Files -The Host `ctx.workspaceFiles` service and generated `workspaceFiles` Remote namespace read files allowed by the Session filesystem backend: `stat(path)` returns `{ absolutePath, version, bytes? }`; `read(path, { offset?, limit? })` returns one page of lines (`offset` 1-based, `limit` capped by the configured page size) as `{ …stat, offset, text, eof }`; `readBytes(path, { range?, baseFile? })` returns a complete file under `maxFileBytes` or a byte window under `maxBytes` as `{ …stat, offset, data, eof }` with native `Uint8Array` data. Its optional `range` uses 0-based `offset` and a byte `length`; `baseFile` resolves the relative target from another file’s directory. `list(path)` remains inside the workspace root and returns a directory's direct children (`name`, `type: 'file' | 'directory' | 'other'`, `size?`) cut to the configured cap with `truncated` set. `changes(path)` watches one target; the Host determines its type and confines directories to the workspace. It yields `{ kind: 'ready' }` once subscribed, then `{ kind: 'change', change }` frames whose payload is `{ absolutePath, version }` or `{ absolutePath, absent: true }` ([README](../../packages/api/workspace-files/README.md#use-this-package)). File reads reject final symlinks and enforce transfer caps; `read` additionally requires UTF-8 text. Failures use `workspace-file/*` codes ([failures](../../packages/api/workspace-files/README.md)). +The Host `ctx.workspaceFiles` service and generated `workspaceFiles` Remote namespace read files allowed by the Session filesystem backend: `stat(path)` returns `{ absolutePath, version, bytes? }`; `read(path, { offset?, limit? })` returns one page of lines (`offset` 1-based, `limit` capped by the configured page size) as `{ …stat, offset, text, eof }`; `readBytes(path, { range?, baseFile? })` returns a complete file under `maxFileBytes` or a byte window under `maxBytes` as `{ …stat, offset, data, eof }` with native `Uint8Array` data. Its optional `range` uses 0-based `offset` and a byte `length`; `baseFile` resolves the relative target from another file’s directory. `list(path)` remains inside the workspace root and returns a directory's direct children (`name`, `type: 'file' | 'directory' | 'other'`, `size?`) cut to the configured cap with `truncated` set. `search({ query, excludedPaths, includeHidden, respectGitignore })` uses packaged rg to find files and inferred ancestor directories, returning flat `{ path, type }` workspace-relative matches; [search semantics](../../packages/api/workspace-files/README.md#search) define native ignore handling, caps and failures. `changes(path)` watches one target; the Host determines its type and confines directories to the workspace. It yields `{ kind: 'ready' }` once subscribed, then `{ kind: 'change', change }` frames whose payload is `{ absolutePath, version }` or `{ absolutePath, absent: true }` ([README](../../packages/api/workspace-files/README.md#use-this-package)). File reads reject final symlinks and enforce transfer caps; `read` additionally requires UTF-8 text. Failures use `workspace-file/*` codes ([failures](../../packages/api/workspace-files/README.md)). [`dsh-api-workspace-files`](../../packages/api/workspace-files/README.md) registers the `file` provider, with `ResourceProtocolMap.file` directly naming `WorkspaceFileStat`. A Session address carries the authorizing Session and a relative or absolute path, passed unchanged to the Host for resolution. The provider waits for Host `ready` before stat and filters changes by `stat.absolutePath`. Bare `absolute` addresses have no authorizing Session and fail with `workspace-file/unknown-workspace`, without borrowing current or Tab Session. Any UI, including Global components, shares the observation for the same complete address. Preview's Remote callbacks use the Session in that address; `remote.workspaceFiles.readBytes` returns native bytes through Connection's binary RPC transport. diff --git a/docs/subsystems/sidebar-right.zh.md b/docs/subsystems/sidebar-right.zh.md index 08e1902f1b..50e1bf2536 100644 --- a/docs/subsystems/sidebar-right.zh.md +++ b/docs/subsystems/sidebar-right.zh.md @@ -135,7 +135,7 @@ Preview 记录已载入版本和读取开始时的观察版本。自动刷新默 ## Workspace Files -Host 的 `ctx.workspaceFiles` 服务与生成的 `workspaceFiles` Remote 命名空间读取 Session 文件系统后端允许的文件:`stat(path)` 返回 `{ absolutePath, version, bytes? }`;`read(path, { offset?, limit? })` 返回一页行(`offset` 1 起,`limit` 受配置页长限制),形如 `{ …stat, offset, text, eof }`;`readBytes(path, { range?, baseFile? })` 在 `maxFileBytes` 上限内返回完整文件,或在 `maxBytes` 上限内返回字节窗口,形如 `{ …stat, offset, data, eof }`,其中 `data` 为原生 `Uint8Array`。可选 `range` 使用 0 起算的 `offset` 与字节数 `length`;`baseFile` 从另一文件所在目录解析相对目标。`list(path)` 仍限定在工作区根内,返回目录的直接子项(`name`、`type: 'file' | 'directory' | 'other'`、`size?`),按配置上限截断并置 `truncated`。`changes(path)` 监听一个目标,由 Host 判断目标类型并将目录限制在工作区。订阅就绪后产出 `{ kind: 'ready' }`,随后产出 `{ kind: 'change', change }` 帧,其载荷为 `{ absolutePath, version }` 或 `{ absolutePath, absent: true }`([README](../../packages/api/workspace-files/README.zh.md#use-this-package))。文件读取拒绝末端符号链接并执行传输上限;`read` 还要求 UTF-8 文本。失败使用 `workspace-file/*` 错误码([失败](../../packages/api/workspace-files/README.zh.md))。 +Host 的 `ctx.workspaceFiles` 服务与生成的 `workspaceFiles` Remote 命名空间读取 Session 文件系统后端允许的文件:`stat(path)` 返回 `{ absolutePath, version, bytes? }`;`read(path, { offset?, limit? })` 返回一页行(`offset` 1 起,`limit` 受配置页长限制),形如 `{ …stat, offset, text, eof }`;`readBytes(path, { range?, baseFile? })` 在 `maxFileBytes` 上限内返回完整文件,或在 `maxBytes` 上限内返回字节窗口,形如 `{ …stat, offset, data, eof }`,其中 `data` 为原生 `Uint8Array`。可选 `range` 使用 0 起算的 `offset` 与字节数 `length`;`baseFile` 从另一文件所在目录解析相对目标。`list(path)` 仍限定在工作区根内,返回目录的直接子项(`name`、`type: 'file' | 'directory' | 'other'`、`size?`),按配置上限截断并置 `truncated`。`search({ query, excludedPaths, includeHidden, respectGitignore })` 通过打包的 rg 搜索文件与推导的祖先目录,返回平铺的 `{ path, type }` 工作区相对路径匹配;原生忽略规则、上限与错误语义见[搜索说明](../../packages/api/workspace-files/README.zh.md#search)。`changes(path)` 监听一个目标,由 Host 判断目标类型并将目录限制在工作区。订阅就绪后产出 `{ kind: 'ready' }`,随后产出 `{ kind: 'change', change }` 帧,其载荷为 `{ absolutePath, version }` 或 `{ absolutePath, absent: true }`([README](../../packages/api/workspace-files/README.zh.md#use-this-package))。文件读取拒绝末端符号链接并执行传输上限;`read` 还要求 UTF-8 文本。失败使用 `workspace-file/*` 错误码([失败](../../packages/api/workspace-files/README.zh.md))。 [`dsh-api-workspace-files`](../../packages/api/workspace-files/README.zh.md) 注册 `file` 提供方,`ResourceProtocolMap.file` 直接是 `WorkspaceFileStat`。Session 地址携带授权 Session 与相对或绝对路径,Host 原样接收并解析。提供方在 stat 前等待 Host 的 `ready` 帧,并按 `stat.absolutePath` 过滤变更。裸 `absolute` 地址没有授权 Session,以 `workspace-file/unknown-workspace` 失败,不借用当前或 Tab Session。任何 UI(包括 Global)访问同一完整地址都共享观察。Preview 的 Remote 回调使用地址中的 Session;`remote.workspaceFiles.readBytes` 通过 Connection 的二进制 RPC 传输返回原生字节。 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index 67636a3998..046f0b9924 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -485,6 +485,22 @@ Host Remote file reads and workspace directory observations over the composed fi */ @Remote async list(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): Promise +/** + * Search files and their inferred ancestor directories with packaged ripgrep. + * Native ignore rules apply unless disabled; VCS metadata, symlinks and empty + * directories are absent. Within the bounded set of listed files, matches + * sort by depth, then workspace-relative path. + * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. + * @param request - the query, literal exclusions, and hidden/ignore switches. + * @param signal - caller cancellation, forwarded to the subprocess; rejection preserves its reason. + * @returns matches capped by search.maxResults; incomplete marks excess rg files or exit 2. + * @throws RemoteError `gateway/bad-request`: the query is blank. + * @throws RemoteError `workspace-file/not-found`: the workspace root does not exist. + * @throws RemoteError `workspace-file/not-directory`: the workspace root is not a directory. + * @throws RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out. + */ +@Remote async search( workspaceFileScope: WorkspaceFileScope, request: WorkspaceFileSearchRequest, signal: AbortSignal, ): Promise + /** * Watch one file or a directory's direct entries in the Session's filesystem. * Files use the backend's read authority; directories remain workspace-scoped. diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 9ae905fbdc..95983eb846 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -485,6 +485,22 @@ Host Remote file reads and workspace directory observations over the composed fi */ @Remote async list(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): Promise +/** + * Search files and their inferred ancestor directories with packaged ripgrep. + * Native ignore rules apply unless disabled; VCS metadata, symlinks and empty + * directories are absent. Within the bounded set of listed files, matches + * sort by depth, then workspace-relative path. + * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. + * @param request - the query, literal exclusions, and hidden/ignore switches. + * @param signal - caller cancellation, forwarded to the subprocess; rejection preserves its reason. + * @returns matches capped by search.maxResults; incomplete marks excess rg files or exit 2. + * @throws RemoteError `gateway/bad-request`: the query is blank. + * @throws RemoteError `workspace-file/not-found`: the workspace root does not exist. + * @throws RemoteError `workspace-file/not-directory`: the workspace root is not a directory. + * @throws RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out. + */ +@Remote async search( workspaceFileScope: WorkspaceFileScope, request: WorkspaceFileSearchRequest, signal: AbortSignal, ): Promise + /** * Watch one file or a directory's direct entries in the Session's filesystem. * Files use the backend's read authority; directories remain workspace-scoped. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml new file mode 100644 index 0000000000..af6b5ec552 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md +/: + en: 8436a6f26fab028f + zh: 38236167b791e6cc +/update-account-notification-consumers: + en: bd380bec124f847c + zh: fcdb87325050b311 +/update-account-notification-consumers/change: + en: 035a33041e86f008 + zh: fa1e62eba84f58ec +/update-account-notification-consumers/migration: + en: 914732f69a48d226 + zh: 251e69c9618f7445 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md new file mode 100644 index 0000000000..d2aefe105b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "Generic account notification APIs replace bonus-specific methods and notification requests use the Harness domain." +--- + +# Update account notification consumers + +English | [中文](guide.zh.md) + +## Change + +`DeepSeekAccount.getNotifications()` and `account/getNotifications` replace `getUnnotifiedBonuses()`. They return `AccountNotificationBatch.notifications` with opaque string `id`, `createdAt`, nullable `displayUntil`, localized `title` and `body`, ordered `actions`, and optional JSON `data`. The batch also requires `nextPollAfterSeconds`, projected from the wire field `next_poll_after`. Bonus metadata belongs in `data`; the bonus-specific types and fields are removed. `reportNotificationEvent()` replaces `ackBonusNotified()` and takes `(id, event, client)` to report `displayed`, `cta_clicked`, or `dismissed` using the notification ID. `getNotificationContent()` reads localized content by notification ID, including consumed notifications, without changing consumption. + +`DeepSeekAccount.watch()` and `account/watch` emit `AccountUpdate` items containing `type` and the complete `state`. Initial subscription and login progress use `snapshot`; credential writes and removal use `credentials-changed`. + +The account provider adds `harnessOrigin`, defaulting to `https://harness.deepseek.com`, for notification list, content, and events. `platformOrigin` retains its `https://platform.deepseek.com` default for login, profile, balance, logout, external navigation, and native embedded pages. Grant issuer checks still use `platformOrigin`. + +`ui-account-notifications` owns notifications; `ui-settings-account` supplies its account state, refresh events, and presentation slot. + +## Migration + +1. Read account state from `update.state`. A `credentials-changed` event or new Remote-stream generation clears notification state and restarts polling when signed in; progress snapshots retain it. Update providers, Remote consumers, and fixtures to use the new fields, opaque string IDs, and required delay in seconds. List decoding skips malformed or unsupported notifications individually; malformed envelopes still fail the request. +2. Remove notification account-ID arguments and the batch accountId field. `getNotificationContent(id, client)` and `reportNotificationEvent(id, event, client)` use the current token directly, without a profile preflight. Credential changes end old requests, cards, and polls; late replies are discarded. Report each event once; valid `acked: true` and `acked: false` responses both finish the attempt. Failed reports keep local card state and are not retried. Report `displayed` after presentation, `cta_clicked` for every non-dismiss action with no action ID, and only `dismissed` after explicit close. Action clicks retain the card and execute without waiting for the report; closing before presentation does not generate a display event; expiry and account cleanup do not count as dismissal. Refresh current cards through `getNotificationContent()` when the language changes; retain their position and avoid another display event. +3. Remove `bonusAckRetryDelayMs` and `bonusAckRetryMaxDelayMs` from `ui-settings-account` configuration; event reporting has no retry settings. A failed report does not undo the current interaction or retry that report. If a later list offers a closed notification again, the client displays it again. +4. Keep existing `platformOrigin` configuration. Private deployments and loopback fixtures set `harnessOrigin` to their notification service origin. Confirm only list, content, and events use that origin; login, profile, balance, logout, and pages retain `platformOrigin`. +5. Load `@deepseek-ai/dsh-client-ui-account-notifications` beside account settings. Set its new `notificationPollIntervalMs` option when the ten-minute initial interval is unsuitable. Move notification-state and reporting consumers to the new plugin. Verify both plugins share one account stream, including after notification-plugin reload. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md new file mode 100644 index 0000000000..8dc5b00039 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-notification-fields/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "通用账号通知 API 替换赠金专用方法,通知请求改用 Harness 域名。" +--- + +# 更新账号通知使用方 + +[English](guide.md) | 中文 + +## 变更 + +`DeepSeekAccount.getNotifications()` 和 `account/getNotifications` 替换 `getUnnotifiedBonuses()`,返回的 `AccountNotificationBatch.notifications` 包含不透明字符串 `id`、`createdAt`、可为 null 的 `displayUntil`、本地化的 `title` 与 `body`、有序的 `actions`,以及可选 JSON `data`。批次还要求提供 `nextPollAfterSeconds`,由接口字段 `next_poll_after` 投影。赠金元数据放入 `data`;赠金专用类型和字段移除。`reportNotificationEvent()` 替换 `ackBonusNotified()`,接收 `(id, event, client)`,以通知 ID 上报 `displayed`、`cta_clicked` 或 `dismissed` 事件。`getNotificationContent()` 按通知 ID 读取本地化内容,支持已消费通知,不改变消费状态。 + +`DeepSeekAccount.watch()` 和 `account/watch` 发出包含 `type` 和完整 `state` 的 `AccountUpdate`。首次订阅和登录进度使用 `snapshot`;凭据写入和删除使用 `credentials-changed`。 + +账号提供者新增 `harnessOrigin`,默认值为 `https://harness.deepseek.com`,用于通知 list、content 和 events。`platformOrigin` 保留 `https://platform.deepseek.com` 默认值,用于登录、资料、余额、退出登录、外部导航和原生内嵌页面。授权来源仍按 `platformOrigin` 校验。 + +`ui-account-notifications` 负责通知;`ui-settings-account` 提供已有账号状态、刷新事件和展示插槽。 + +## 迁移 + +1. 从 `update.state` 读取账号状态。收到 `credentials-changed` 事件或 Remote 流进入新一代连接时,清空通知状态,已登录时重启轮询;进度快照保留当前轮询。更新提供者、Remote 使用方和测试夹具,使用新字段、不透明字符串 ID 和必填的秒数间隔。列表解码逐条跳过格式错误或不支持的通知;列表外层格式错误仍使请求失败。 +2. 移除通知方法的账号 ID 参数和批次的 accountId 字段。`getNotificationContent(id, client)` 和 `reportNotificationEvent(id, event, client)` 直接使用当前 token,不前置查询资料。凭据变化后终止旧请求、卡片与轮询,并丢弃迟到的响应。每次事件只上报一次;有效的 `acked: true` 和 `acked: false` 均结束本次尝试。上报失败保留本地卡片状态,不重试。展示后上报 `displayed`,所有非 dismiss 操作点击都上报 `cta_clicked`,不携带 action ID,主动关闭仅上报 `dismissed`。点击业务按钮保留卡片并立即执行操作,不等待上报;尚未展示就关闭时不补报展示事件;过期和账号清理不计为主动关闭。切换语言时,通过 `getNotificationContent()` 刷新当前卡片,保留位置,不重复上报展示事件。 +3. 从 `ui-settings-account` 配置中移除 `bonusAckRetryDelayMs` 和 `bonusAckRetryMaxDelayMs`;事件上报没有重试配置。上报失败不撤销当前交互,也不重试该次上报。后续列表再次返回已关闭通知时,客户端会再次展示。 +4. 保留已有的 `platformOrigin` 配置。私有部署和本机测试夹具将 `harnessOrigin` 设为各自的通知服务来源。确认仅 list、content 和 events 使用该来源;登录、资料、余额、退出登录和页面保留 `platformOrigin`。 +5. 在账号设置旁加载 `@deepseek-ai/dsh-client-ui-account-notifications`。初始十分钟间隔不适用时,设置其新增的 `notificationPollIntervalMs` 选项。将通知状态及上报使用方迁移到新插件。确认两个插件共用一条账号流,包括重载通知插件之后。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml new file mode 100644 index 0000000000..91613be43b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md +/: + en: 561965d845c4ae75 + zh: 169f6d5fe2d6d3e4 +/account-service-and-remote-imports: + en: ac80b8c714afec7b + zh: 62e1e73b51c3ea1d +/account-service-and-remote-imports/change: + en: 7839978713aa24da + zh: 0225e3baa4425c46 +/account-service-and-remote-imports/migration: + en: fcaddf93cb778db9 + zh: 4921e5ef8d75ea9e diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md new file mode 100644 index 0000000000..fe31535ab3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Move account plugin composition and Remote imports to the concrete deepseek-account service." +--- + +# Account service and Remote imports + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-deepseek-account` is a concrete `DeepSeekAccount` service owning browser login, stored credentials, and the `account` Remote namespace. The abstract account class, `@deepseek-ai/dsh-deepseek-account-platform`, and `@deepseek-ai/dsh-api-account-controller` are removed. Existing `ctx.deepseekAccount` and `ctx.remote.account` operations retain their names and arguments. Host-only credential methods are not Remote operations. The `/types` entry remains available without loading the service implementation. + +Stored credentials keep the `deepseek-account-platform/default` and `deepseek-account-platform/device` keys; this package change does not require signing in again. + +## Migration + +1. Replace `@deepseek-ai/dsh-deepseek-account-platform` with `@deepseek-ai/dsh-deepseek-account` in custom plugin rows and dependencies. Keep the existing `deepseek-account` row id and configuration. Remove any `account-controller` row and its package dependency. +2. Import `DeepSeekAccount` instead of `PlatformAccount`. The class is concrete; custom subclasses of the former abstract account definition must be updated. Existing imports of shared types from `@deepseek-ai/dsh-deepseek-account/types` remain valid. +3. Replace old provider or controller `/remote` and `/typert` imports with `@deepseek-ai/dsh-deepseek-account/remote` and `@deepseek-ai/dsh-deepseek-account/typert`. +4. Import Platform header and cookie helpers from `@deepseek-ai/dsh-deepseek-account/client-metadata`. Read the configuration schema from `DeepSeekAccount.Config`. Stop calling `installAccountTaskCancellation` directly: mounting the service installs it. `isRunningAccountTask` is internal. +5. Rebuild custom compositions and verify login, notification queries, sign-out, and cancellation of account state subscriptions. Confirm that Remote exports omit `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md new file mode 100644 index 0000000000..ce523bd32a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/account-remote-provider/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "将账号插件组合与 Remote 导入迁移到具体的 deepseek-account 服务。" +--- + +# 账号服务与 Remote 导入 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-deepseek-account` 是具体的 `DeepSeekAccount` 服务,拥有浏览器登录、已存储凭证和 `account` Remote 命名空间。抽象账号类、`@deepseek-ai/dsh-deepseek-account-platform` 和 `@deepseek-ai/dsh-api-account-controller` 被移除。已有 `ctx.deepseekAccount` 和 `ctx.remote.account` 操作保留名称和参数。凭据相关的 Host 专用方法不会成为 Remote 操作。`/types` 出口仍可用,且不会加载服务实现。 + +已存储凭证保留 `deepseek-account-platform/default` 和 `deepseek-account-platform/device` key;这次包变更不要求重新登录。 + +## 迁移 + +1. 将自定义插件行和依赖中的 `@deepseek-ai/dsh-deepseek-account-platform` 替换为 `@deepseek-ai/dsh-deepseek-account`。保留现有 `deepseek-account` 行 id 和配置。移除所有 `account-controller` 行及其包依赖。 +2. 将 `PlatformAccount` 导入改为 `DeepSeekAccount`。该类为具体实现;继承原抽象账号定义的自定义子类需要调整。从 `@deepseek-ai/dsh-deepseek-account/types` 导入共享类型的现有代码保持有效。 +3. 将旧服务或 controller 的 `/remote`、`/typert` 导入替换为 `@deepseek-ai/dsh-deepseek-account/remote` 和 `@deepseek-ai/dsh-deepseek-account/typert`。 +4. 从 `@deepseek-ai/dsh-deepseek-account/client-metadata` 导入 Platform 请求头和 Cookie 辅助函数。从 `DeepSeekAccount.Config` 读取配置 schema。不再直接调用 `installAccountTaskCancellation`:挂载服务时会安装该逻辑。`isRunningAccountTask` 为内部函数。 +5. 重新构建自定义组合,验证登录、通知查询、退出和账号状态订阅取消。确认 Remote 导出不包含 `resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity`。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml index b563eb7323..b748855bae 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml @@ -9,8 +9,8 @@ en: bc309764ab7b8b98 zh: 20fdfbce76706025 /worktree-cleanup-on-archive/change: - en: 05f27e166f2dbb40 - zh: a320ac6252fd2e38 + en: 990690039f918e72 + zh: 8e23fbabf88a777f /worktree-cleanup-on-archive/migration: - en: c9b2fca77d02e07f - zh: a4228d7f22fb7e35 + en: 05f29b760cb99ae9 + zh: 33f181ac2a582bdf diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md index 77912a2e71..74f3986277 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md @@ -9,13 +9,13 @@ English | [中文](guide.zh.md) ## Change -Archiving a Session previously retained its checkout. The worktree service now records each checkout it creates as a `plugin:worktree/created` record and, when the Session that created one is archived, removes it with a non-force `git worktree remove` when no unarchived Session refers to it, its creator's policy is not read-only, and Git finds no tracked changes, untracked files, hidden index flags, submodules, locks, or detached HEAD. Ignored files such as `node_modules` do not retain it. Branches and commits remain. The service's `retainOnArchive` setting, off by default, keeps every checkout instead. Checkouts created before this release have no such event and are never swept, nor are Sessions archived earlier. See the [worktree service](../../../../packages/experimental/worktree/README.md). +Archiving a Session previously retained its checkout. The worktree service now records each checkout it creates as a `plugin:worktree/created` record and, when the Session that created one is archived, removes it with a non-force `git worktree remove` when no unarchived Session refers to it, its creator's policy is not read-only, and Git finds no tracked changes, untracked files, initialized submodules, locks, or detached HEAD. Ignored files such as `node_modules` and edits to skip-worktree or assume-unchanged files, which `git status` hides, do not retain it; Git discards them. Git refuses to remove a checkout holding a committed embedded repository, so that checkout stays and the archive notice reports a failed cleanup. Branches and commits remain. The service's `retainOnArchive` setting, off by default, keeps every checkout instead. Checkouts created before this release have no such event and are never swept, nor are Sessions archived earlier. See the [worktree service](../../../../packages/experimental/worktree/README.md). The Forge bundle mounts one `worktree` service for both the panel and the `create_worktree` tool. The `forge-worktree` row and the `optional-forge-panel` group that isolated a second service are gone; the panel is the top-level `forge-panel` row. ## Migration -1. If a checkout must remain available outside DSH, keep its Session unarchived, lock it with `git worktree lock ` before archiving, or turn on **Keep worktrees when archiving** on the Forge bundle's worktree row of the Plugins page (`retainOnArchive`), which keeps every checkout. Ignored files are not kept. +1. If a checkout must remain available outside DSH, keep its Session unarchived, lock it with `git worktree lock ` before archiving, or turn on **Keep worktrees when archiving** on the Forge bundle's worktree row of the Plugins page (`retainOnArchive`), which keeps every checkout. Ignored files are not kept, nor are edits to skip-worktree or assume-unchanged files: commit those edits, or clear the flags with `git update-index --no-skip-worktree` or `--no-assume-unchanged`, before archiving. 2. To resume an archived Session whose checkout was removed, unarchive it and use **Restore worktree**. The retained branch is checked out at the recorded path. 3. In a profile's `cordis.patch.yml`, move any `forge-worktree` override to the `worktree` row and any `optional-forge-panel` override to the `forge-panel` row; a `disabled: true` on `forge-panel` turns off the panel alone. 4. Confirm the branch and commits are present with `git branch --list` and that **Restore worktree** makes the recorded checkout available. Session logs require no migration. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md index 5edf966298..d5295cfb18 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md @@ -9,13 +9,13 @@ description: "归档 Session 可以删除其干净的工作树并保留分支, ## 变更 -归档 Session 以前会保留检出目录。工作树服务现在把它创建的每个检出目录记录为 `plugin:worktree/created` Session 事件;当创建它的 Session 被归档时,若没有未归档的 Session 引用该目录、创建者的策略不是只读,且 Git 未发现跟踪文件改动、未跟踪文件、隐藏的索引标记、子模块、锁或分离 HEAD,就用不带 force 的 `git worktree remove` 删除它。`node_modules` 之类被忽略的文件不会保留目录。分支和提交仍会保留。服务的 `retainOnArchive` 设置默认关闭,开启后改为保留所有检出目录。本版本之前创建的检出目录没有该事件,不会被扫描;更早归档的 Session 也不会。参见[工作树服务](../../../../packages/experimental/worktree/README.zh.md)。 +归档 Session 以前会保留检出目录。工作树服务现在把它创建的每个检出目录记录为 `plugin:worktree/created` Session 事件;当创建它的 Session 被归档时,若没有未归档的 Session 引用该目录、创建者的策略不是只读,且 Git 未发现跟踪文件改动、未跟踪文件、已初始化的子模块、锁或分离 HEAD,就用不带 force 的 `git worktree remove` 删除它。`node_modules` 之类被忽略的文件,以及 `git status` 不报告的 skip-worktree 或 assume-unchanged 文件改动,都不会保留目录,Git 会丢弃它们。含已提交内嵌仓库的检出目录会被 Git 拒绝删除,因此保留,归档提示显示清理失败。分支和提交仍会保留。服务的 `retainOnArchive` 设置默认关闭,开启后改为保留所有检出目录。本版本之前创建的检出目录没有该事件,不会被扫描;更早归档的 Session 也不会。参见[工作树服务](../../../../packages/experimental/worktree/README.zh.md)。 Forge bundle 为面板和 `create_worktree` 工具挂载同一个 `worktree` 服务。隔离第二个服务的 `forge-worktree` 行与 `optional-forge-panel` 组已移除;面板是顶层的 `forge-panel` 行。 ## 迁移 -1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,在归档前用 `git worktree lock ` 锁定它,或在插件页 Forge 套件的 worktree 行上开启**归档时不删除工作树**(`retainOnArchive`),它会保留所有检出目录。被忽略的文件不会保留。 +1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,在归档前用 `git worktree lock ` 锁定它,或在插件页 Forge 套件的 worktree 行上开启**归档时不删除工作树**(`retainOnArchive`),它会保留所有检出目录。被忽略的文件不会保留,skip-worktree 或 assume-unchanged 文件的改动也不会:归档前请提交这些改动,或用 `git update-index --no-skip-worktree` 或 `--no-assume-unchanged` 清除标记。 2. 要继续使用已归档且检出目录已删除的 Session,请取消归档并使用**恢复工作树**。保留的分支会在记录的路径重新检出。 3. 在 profile 的 `cordis.patch.yml` 中,把针对 `forge-worktree` 的覆盖迁到 `worktree` 行,把针对 `optional-forge-panel` 的覆盖迁到 `forge-panel` 行;对 `forge-panel` 设置 `disabled: true` 可以只关闭面板。 4. 用 `git branch --list` 确认分支与提交仍然存在,并确认**恢复工作树**使记录的检出目录重新可用。Session 日志无需迁移。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml new file mode 100644 index 0000000000..9a48f7428c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md +/: + en: 5ebb4c8a6b20b644 + zh: 22a8983d06fa5789 +/macos-hover-keeps-the-system-pointer-in-place-by-default: + en: 6833a7851486f10d + zh: 22983f326fb725ce +/macos-hover-keeps-the-system-pointer-in-place-by-default/change: + en: 55c3070b24b4ad39 + zh: 2555d127b0f4e4a0 +/macos-hover-keeps-the-system-pointer-in-place-by-default/migration: + en: 1f0ab7e8741e821f + zh: f59adc3a23ebcb43 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md new file mode 100644 index 0000000000..f7191cc254 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "macOS mouseMove requires AX alternate UI by default and returns HOVER_UNAVAILABLE instead of moving the user's cursor." +--- + +# macOS hover keeps the system pointer in place by default + +English | [中文](guide.zh.md) + +## Change + +On macOS, `win.mouseMove(target)` uses an enabled element or ancestor that advertises both `AXShowAlternateUI` and `AXShowDefaultUI`. Without that route, previous versions moved the visible system cursor. The default now returns `HOVER_UNAVAILABLE` before sending input. + +## Migration + +1. For an available control, use its advertised action or click it directly. Use browser tools for web content that requires page hover. +2. To restore visible pointer movement, set `systemPointerHover: true` in the `config` of the macOS provider entry (`id: cua`) in your profile's `cordis.patch.yml`. Preserve the entry's other settings. If you set `helperPath`, rebuild the custom helper so it accepts `systemPointerHover` in the connection handshake. Restart the profile. +3. Call `win.mouseMove` on a foreground, unobscured control without AX alternate UI. The opt-in result reports `hoverRoute: "system-pointer"` and `systemPointerMoved: true`. Keep the default to avoid disturbing the user's cursor. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md new file mode 100644 index 0000000000..713ae43fb3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "macOS 的 mouseMove 默认要求控件支持 AX 备用界面,否则返回 HOVER_UNAVAILABLE,保留用户的光标位置。" +--- + +# macOS 悬停默认保留系统光标位置 + +[English](guide.md) | 中文 + +## 变更 + +在 macOS 上,`win.mouseMove(target)` 会查找已启用且同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的控件或祖先。找不到时,旧版会移动系统光标,新版默认在发送输入前返回 `HOVER_UNAVAILABLE`。 + +## 迁移 + +1. 对已经可用的控件,可执行它声明的动作或直接点击。需要网页悬停时可用浏览器工具。 +2. 要恢复可见光标移动,在 profile 的 `cordis.patch.yml` 中,给 macOS 提供方条目(`id: cua`)的 `config` 添加 `systemPointerHover: true`。保留该条目的其他设置。如果指定了 `helperPath`,先重新构建自定义 helper,使其在建立连接时能读取 `systemPointerHover`,然后重启 profile。 +3. 对前台未受遮挡且不提供 AX 备用界面的控件调用 `win.mouseMove`。启用配置时,结果为 `hoverRoute: "system-pointer"` 和 `systemPointerMoved: true`。要保留用户的光标位置,使用默认配置。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index 8d9654901c..a017e7f82b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: 6cabae699a340845 - zh: f2256751518c5e36 + en: a63e88dce467d6ee + zh: fc25bb283ca0eaff diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 5023ac9ff0..2675699a71 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -15,9 +15,9 @@ Providers supply startup capabilities alongside their platform guidance. The nat ## Migration -1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. +1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. 2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. -4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. 5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. 6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index 880034fbd8..b4551f624b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -15,9 +15,9 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 ## 迁移 -1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。 +1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 -4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml new file mode 100644 index 0000000000..3e10d3d26b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md +/: + en: ad1c3c4e42227656 + zh: 286eac73122ddbef +/forge-diffs-read-one-head-commit: + en: c017d657e5d9eb08 + zh: d0eb2aef480e7753 +/forge-diffs-read-one-head-commit/change: + en: 6b6465c90a0f893e + zh: fb265bd706a77196 +/forge-diffs-read-one-head-commit/migration: + en: 147b16ca7c30624c + zh: ce246be22d7c378a diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md new file mode 100644 index 0000000000..e31ee72f57 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ForgeProvider.diff and ctx.forge.diff take the head commit to read, ForgeFailure gains the stale code, and ChangeRequestSnapshot gains threadsTruncated." +--- + +# Forge diffs read one head commit + +English | [中文](guide.zh.md) + +## Change + +`ForgeProvider.diff(ref, signal)` becomes `diff(ref, headSha, signal)`, and `ctx.forge.diff(ref, signal)` becomes `ctx.forge.diff(ref, headSha, signal)`. A provider returns a patch only when it describes `headSha`; when the change request's head is another commit, it resolves to a `ForgeFailure` whose code is the new `stale`. `ctx.forge.diff` then polls the change request again at once when it is watched. The GitHub provider reads the head and base commits in one GraphQL query, returns `stale` when the head is another commit, and otherwise reads the patch through the compare API between those two commits instead of `gh pr diff`. A GitHub pull request over 300 files, which `gh pr diff` refused as too large, now shows its complete diff; only output over `maxOutputBytes` or GitHub's own refusal remains `too-large`. + +`ForgeFailure['code']` gains `stale`. `ChangeRequestSnapshot` gains the required `threadsTruncated: boolean`, which marks `unresolvedThreads` as a lower bound when the provider counted only some review threads. + +The `forgePanel.changeRequestDiff` Remote rejects with `forgePanel/stale-head` instead of returning a patch read at another head. + +This affects third-party `ForgeProvider` implementations registered with `ctx.forge.register`, code that calls `ctx.forge.diff` or `forgePanel.changeRequestDiff`, code that builds `ChangeRequestSnapshot` values, and code that switches exhaustively over `ForgeFailure['code']`. All types come from `@deepseek-ai/dsh-experimental-forge`. + +## Migration + +1. In a `ForgeProvider`, add the `headSha: string` parameter to `diff` before `signal`. Return the patch only when the host computed it at `headSha`; otherwise return `{ code: 'stale', message }`. [`GitHubProvider.diff`](../../../../packages/experimental/forge-github/src/provider.ts) reads the current head first and then a diff addressed by commit. +2. Pass the head commit to every `ctx.forge.diff` call, usually `ctx.forge.latest(ref)`'s `snapshot.headSha`. On `stale`, wait for a later status and read again at its head; do not cache the result under the old head. +3. Set `threadsTruncated` in every `ChangeRequestSnapshot` a provider builds: `false` when `unresolvedThreads` counts every review thread. +4. Handle `stale` wherever code switches exhaustively over `ForgeFailure['code']`, and `forgePanel/stale-head` wherever a caller of `forgePanel.changeRequestDiff` distinguishes Remote error codes. +5. Run your type check; it succeeds when every `diff` implementation and call passes a head commit, every snapshot sets `threadsTruncated`, and no `ForgeFailure` code is unhandled. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md new file mode 100644 index 0000000000..cb4de638a2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ForgeProvider.diff 与 ctx.forge.diff 需要传入要读取的 head 提交,ForgeFailure 新增 stale 代码,ChangeRequestSnapshot 新增 threadsTruncated。" +--- + +# Forge diff 读取指定的 head 提交 + +[English](guide.md) | 中文 + +## 变更 + +`ForgeProvider.diff(ref, signal)` 改为 `diff(ref, headSha, signal)`,`ctx.forge.diff(ref, signal)` 改为 `ctx.forge.diff(ref, headSha, signal)`。提供方只在补丁描述 `headSha` 时返回补丁;变更请求的 head 已是其他提交时,resolve 为代码为新增 `stale` 的 `ForgeFailure`。此时若该变更请求正被 watch,`ctx.forge.diff` 会立即重新轮询它。GitHub 提供方在一次 GraphQL 查询中读取 head 与基准提交,head 是其他提交时返回 `stale`,否则不再使用 `gh pr diff`,改经 compare API 读取这两个提交之间的补丁。超过 300 个文件、此前被 `gh pr diff` 判为过大的 GitHub pull request 现在显示完整 diff;只有输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才仍为 `too-large`。 + +`ForgeFailure['code']` 新增 `stale`。`ChangeRequestSnapshot` 新增必填字段 `threadsTruncated: boolean`;提供方只统计了部分评审讨论时,它表示 `unresolvedThreads` 只是下限。 + +`forgePanel.changeRequestDiff` Remote 以 `forgePanel/stale-head` 拒绝,不再返回在其他 head 读到的补丁。 + +受影响的是用 `ctx.forge.register` 注册的第三方 `ForgeProvider` 实现、调用 `ctx.forge.diff` 或 `forgePanel.changeRequestDiff` 的代码、构造 `ChangeRequestSnapshot` 的代码,以及对 `ForgeFailure['code']` 做穷尽分支的代码。这些类型都来自 `@deepseek-ai/dsh-experimental-forge`。 + +## 迁移 + +1. 在 `ForgeProvider` 的 `diff` 中,于 `signal` 之前加入 `headSha: string` 参数。只有托管平台在 `headSha` 处计算出补丁时才返回补丁,否则返回 `{ code: 'stale', message }`。[`GitHubProvider.diff`](../../../../packages/experimental/forge-github/src/provider.ts) 先读取当前 head,再读取按提交寻址的 diff。 +2. 每次调用 `ctx.forge.diff` 都传入 head 提交,通常是 `ctx.forge.latest(ref)` 的 `snapshot.headSha`。收到 `stale` 时,等待更新的状态并按其 head 重新读取;不要把结果缓存在旧 head 下。 +3. 提供方构造的每个 `ChangeRequestSnapshot` 都要设置 `threadsTruncated`:`unresolvedThreads` 统计了全部评审讨论时为 `false`。 +4. 凡对 `ForgeFailure['code']` 做穷尽分支的地方都处理 `stale`;凡区分 `forgePanel.changeRequestDiff` Remote 错误代码的调用方都处理 `forgePanel/stale-head`。 +5. 运行类型检查;所有 `diff` 实现与调用都传入 head 提交、所有快照都设置 `threadsTruncated`、没有未处理的 `ForgeFailure` 代码时,检查通过。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml new file mode 100644 index 0000000000..cc9434e9c3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md +/: + en: 0c7dd958bce09e16 + zh: 3b3c85a2152294ec +/update-replacements-for-session-append: + en: 5cc8a72cf2203e52 + zh: 22976024cf5453eb +/update-replacements-for-session-append/change: + en: 51fbd9ed1cd50cdf + zh: 103d3ac9b631414e +/update-replacements-for-session-append/migration: + en: 19c39d4582b09f41 + zh: 4345d25a52dec57e diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md new file mode 100644 index 0000000000..db74ea4789 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Code that replaces Session.append must implement both the single-event and array overloads." +--- + +# Update replacements for `Session.append` + +English | [中文](guide.zh.md) + +## Change + +In v0.2.2-rc.1, `Session.append` had a single call signature. It now accepts either one typed event call or an array of event tuples. Ordinary single-event calls still compile. Test doubles and wrappers assigned to `Session['append']` must support both overloads. + +## Migration + +1. For a wrapper around `Session.append`, preserve both overloads by wrapping the original function with a `Proxy` and forwarding from its `apply` trap with `Reflect.apply`. For a test double that only accepts one event, type the single-event helper separately and call it from the relevant test. +2. Typecheck assignments to `Session['append']`. Call replacements with both `append('turn/start', { turn: 1 })` and `append([['turn/start', { turn: 1 }]])` and verify the first returns one event and the second an array. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md new file mode 100644 index 0000000000..c71289c7f7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "替换 Session.append 的代码必须实现单事件和数组两种重载。" +--- + +# 更新 `Session.append` 的替代实现 + +[English](guide.md) | 中文 + +## 变更 + +在 v0.2.2-rc.1 中,`Session.append` 只有一个调用签名。现在它可接收一个带类型的事件调用,也可接收事件元组数组。普通单事件调用仍可编译。赋值给 `Session['append']` 的测试替身和包装函数必须支持两种重载。 + +## 迁移 + +1. 包装 `Session.append` 时,用 `Proxy` 包装原函数,在 `apply` 拦截器内用 `Reflect.apply` 转发,以保留两种重载。若测试替身只接收单个事件,给该辅助函数单独声明类型并在相应测试中调用。 +2. 检查赋值给 `Session['append']` 的代码能通过类型检查。分别以 `append('turn/start', { turn: 1 })` 和 `append([['turn/start', { turn: 1 }]])` 调用替代实现,验证前者返回一个事件,后者返回数组。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml new file mode 100644 index 0000000000..fb72a12add --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md +/: + en: fda192f58c50cd90 + zh: 2ebe5d7389eb9689 +/built-in-configurations-disable-agent-interruption: + en: c253388db5ba6f5a + zh: af138bbc7bfd31b4 +/built-in-configurations-disable-agent-interruption/change: + en: 76b23fa746332e06 + zh: d30315eab3aa53bd +/built-in-configurations-disable-agent-interruption/migration: + en: 0f5bd67305b455dc + zh: a98770b64686d612 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md new file mode 100644 index 0000000000..ddcd5a2149 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Built-in configurations disable interrupt_agent for subagents and Team mode." +--- + +# Built-in configurations disable agent interruption + +English | [中文](guide.zh.md) + +## Change + +The base bundle and the Web `standard`, `cordis`, and `ptc` presets now set `config.interrupt: false` on their `tool-subagent-control` rows. Models using these configurations no longer receive `interrupt_agent`, including in Team mode. Messaging, discovery, inbox waiting, and the subagent service interruption API remain available. The plugin's own default remains `true`; independent compositions that omit the setting retain interruption. + +## Migration + +Keep `interrupt: false` to retain the built-in behavior. To restore interruption: + +1. Edit `$DSH_HOME/profiles//cordis.patch.yml`. For base-backed profiles such as `headless`, `sdk`, and `acp`, append: + + ```yaml + - id: tool-subagent-control + config: + interrupt: true + ``` + +2. For `web` or `desktop`, instead override each required declaration: `preset-standard`, `preset-cordis`, or `preset-ptc`. Copy that declaration's complete `config` from the installed `@deepseek-ai/dsh-web-app` bundle's `presets/.patch.yml` (source: [standard](../../../../packages/bundle/web-app/presets/standard.patch.yml), [cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml), [ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml)). If your profile already overrides the declaration, edit that override to preserve your customizations. A patch replaces the whole `config`: retain `id`, `order`, and the entire `plugins` list, including the `delegation` group. Within that group's `config`, change the `tool-subagent-control` row's `config.interrupt` to `true`. Use the declaration's outer ID as the patch target, following [Change a shipped preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset). A top-level patch targeting `tool-subagent-control` does not reach the preset's child row; it only changes the disabled Host row. Leave that Host row disabled. +3. Restart the profile and create a new Session using the changed preset; existing Sessions retain their preset revision. Confirm that the model's tool definitions include `interrupt_agent`, `send_message`, `list_agents`, and `wait_agent`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md new file mode 100644 index 0000000000..7f9455936a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "内置配置关闭普通 subagent 和 Team 模式的 interrupt_agent。" +--- + +# 内置配置关闭 agent 中断 + +[English](guide.md) | 中文 + +## 变更 + +base 组合包及 Web 的 `standard`、`cordis`、`ptc` preset 现在为各自的 `tool-subagent-control` 行设置 `config.interrupt: false`。使用这些配置的模型不再获得 `interrupt_agent`,也包括 Team 模式。消息、发现、收件箱等待和 subagent 服务的中断 API 仍然可用。插件自身的默认值仍为 `true`;省略该设置的独立组合仍提供中断工具。 + +## 迁移 + +保留 `interrupt: false` 可维持内置行为。如需恢复中断工具: + +1. 编辑 `$DSH_HOME/profiles//cordis.patch.yml`。对于 `headless`、`sdk`、`acp` 等基于 base 的 profile,追加: + + ```yaml + - id: tool-subagent-control + config: + interrupt: true + ``` + +2. 对于 `web` 或 `desktop`,改为覆盖需要启用的声明行:`preset-standard`、`preset-cordis` 或 `preset-ptc`。从已安装的 `@deepseek-ai/dsh-web-app` 组合包的 `presets/.patch.yml` 中复制该声明的完整 `config`(源码:[standard](../../../../packages/bundle/web-app/presets/standard.patch.yml)、[cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml)、[ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml))。如果 profile 已经覆盖该声明,编辑已有覆盖以保留自定义配置。patch 会替换整个 `config`:保留 `id`、`order` 和完整的 `plugins` 列表,包括 `delegation` 组。在该组的 `config` 内,将 `tool-subagent-control` 行的 `config.interrupt` 改为 `true`。以声明的外层 ID 为 patch 目标,写法参见[修改内置 preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset)。顶层以 `tool-subagent-control` 为目标的 patch 无法修改 preset 内的子行,只会修改已禁用的 Host 行。保持该 Host 行禁用。 +3. 重启 profile,并使用修改后的 preset 创建新 Session;已有 Session 保留原 preset 修订。确认模型的工具定义包含 `interrupt_agent`、`send_message`、`list_agents` 和 `wait_agent`。 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 899572eab5..fb0f9c5069 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: f6fb44a85dc5e4dd - zh: 2b86ea4492c32ed7 + en: ed03fba6cf4739af + zh: b0fd9221047e1c89 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 90b70e0696..78d7807212 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,9 +20,9 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential uses the placeholder **Leave blank to use saved credentials**, with no status text below the input. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays a masked preview in the input and a green hint that the saved key will be used. The preview retains the identifier before the first hyphen or underscore, then five leading and four trailing key characters, only when at least eight middle characters stay hidden; otherwise the entire key and identifier become dots. Counts use Unicode code points. Saved keys have no eye button and cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Apply**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Apply** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. -A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Stored credentials remain write-only. +An editable, nonempty key draft has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. ## Add a custom model API diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index c580fd2ab0..9eeef277b4 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,9 +20,9 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据使用**留空使用已保存凭据**占位文字,输入框下方不显示状态文字。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中显示脱敏预览,下方显示绿色的使用已保存密钥提示。预览保留第一个连字符或下划线之前的标识,以及密钥的前五、后四个字符,但中间必须至少隐藏八个字符;否则整串和标识全部显示为点。计数使用 Unicode 码点。已保存密钥不显示眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 -密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。已保存凭据仍保持只写。 +可编辑的密钥草稿非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 ## 添加自定义模型 API diff --git a/packages/api/account-controller/README.i18n.yaml b/packages/api/account-controller/README.i18n.yaml deleted file mode 100644 index f678c0c9f0..0000000000 --- a/packages/api/account-controller/README.i18n.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/api/account-controller/README.md -/: - en: 7ba95936e0bd5c50 - zh: 6ded94fff9da8cbe -/deepseek-ai-dsh-api-account-controller: - en: 8a461bd0ed327ba1 - zh: 456b7cea744b1f3a -/deepseek-ai-dsh-api-account-controller/summary: - en: 76e317532dcd45a4 - zh: 4571ca03d06f04a1 -/deepseek-ai-dsh-api-account-controller/table-of-contents: - en: af856ba79fe31b8e - zh: 15b7d1a5d1856de2 -/deepseek-ai-dsh-api-account-controller/use-this-package: - en: 5ad12300bbc151ef - zh: 3ccfb6046ab423ef -/deepseek-ai-dsh-api-account-controller/understand-the-implementation: - en: d76d0fa4dc48033d - zh: e193caafd78250e9 -/deepseek-ai-dsh-api-account-controller/further-exploration: - en: e5d7405e19fb6d00 - zh: f92bdfe5247d758b -/deepseek-ai-dsh-api-account-controller/model-experience: - en: ee1df7ca3467ee3f - zh: 84904a5148da3862 -/deepseek-ai-dsh-api-account-controller/model-experience/kv-cache-effect: - en: ca3015e252db0114 - zh: ebca9253cf15e8e9 -/deepseek-ai-dsh-api-account-controller/known-limitations-and-deferred-work: - en: ae26f88d13444103 - zh: d875f0909e03e160 -/deepseek-ai-dsh-api-account-controller/known-limitations-and-deferred-work/dev-note: - en: 68dabcdc229fcb50 - zh: 85514a7f6087abc3 diff --git a/packages/api/account-controller/README.md b/packages/api/account-controller/README.md deleted file mode 100644 index 3e7ff7b0bc..0000000000 --- a/packages/api/account-controller/README.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -description: "Account screens use authenticated Remote commands and a snapshot stream. The controller exposes login state without returning tokens or PKCE secrets." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-api-account-controller - -English | [中文](README.zh.md) - -## Summary - -Account screens use authenticated Remote commands and a snapshot stream. The controller exposes login state without returning tokens or PKCE secrets. - -## Table of Contents - -- [Use this package](#use-this-package) -- [Model Experience](#model-experience) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - - -## Use this package - -The account namespace exposes getState, getProfile / getBalance, getUnnotifiedBonuses, ackBonusNotified, startSignIn, cancelSignIn, signOut, and watch. watch emits an initial complete state and subsequent complete states; disconnecting stops observation, not the login attempt. Cancellation names the attempt ID so a stale screen cannot cancel a newer login. getUnnotifiedBonuses returns null and ackBonusNotified returns false while the account is absent or has changed; failures the caller should retry arrive as thrown Remote errors. - -Every operation that reaches Platform takes the calling UI's `AccountClientMetadata` — client version, active language, and UTC offset in seconds — so the Host reports the requesting UI rather than the last caller it saw. Cancellation and watch remain identity-free because they never reach Platform. - -`watchExpiry` delivers live credential-expiry notifications without an initial item or replay. Desktop uses this stream to hand off a one-shot toast when switching to Welcome. - -`hasRunningAccountTasks` checks running Agents through the account-owned predicate over their latest logged request context, including tools and retries. Idle Agents and API-key contexts are excluded. The account provider independently cancels matching tasks when credentials are removed. - - -## Understand the implementation - -The controller forwards operations to the account service and maintains no independent account state. - - -## Further Exploration - -The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. - - -## Model Experience - -None, as account credentials affect HTTP authentication and never enter model prompts, Session logs, or tool results. - -#### KV Cache effect - -No model request prefix changes. - -## Known Limitations and Deferred Work - - - -- A disconnected UI can recover account state through watch, but cannot resume an attempt after the Host exits. Credentials and request-token resolution are not Remote operations. - - -### Dev Note - -The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. diff --git a/packages/api/account-controller/README.zh.md b/packages/api/account-controller/README.zh.md deleted file mode 100644 index 7007cfdd6f..0000000000 --- a/packages/api/account-controller/README.zh.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -description: "账号页面使用经过认证的 Remote 操作和快照流。控制器提供登录状态,不返回 token 或 PKCE 私密数据。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-api-account-controller - -[English](README.md) | 中文 - -## 概述 - -账号页面使用经过认证的 Remote 操作和快照流。控制器提供登录状态,不返回 token 或 PKCE 私密数据。 - -## 目录 - -- [使用此包](#use-this-package) -- [模型体验](#model-experience) -- [已知限制与后续工作](#known-limitations-and-deferred-work) - - -## 使用此包 - -account 命名空间提供 getState、getProfile / getBalance、getUnnotifiedBonuses、ackBonusNotified、startSignIn、cancelSignIn、signOut 和 watch。watch 先发送完整初始状态,随后发送完整状态变化;断开连接只停止观察,不取消登录。取消操作必须指定尝试 ID,防止旧页面取消新登录。账号缺失或已切换时 getUnnotifiedBonuses 返回 null、ackBonusNotified 返回 false;需要调用方重试的失败以抛出的 Remote 错误返回。 - -到达 Platform 的每个操作都接收调用界面的 `AccountClientMetadata`——客户端版本、当前语言和以秒为单位的 UTC 偏移——因此 Host 报告的是发起请求的界面,而不是它上一次见到的调用方。取消和 watch 不接该参数,因为它们不会到达 Platform。 - -`watchExpiry` 仅发送实时凭据失效通知,不发送初始值,也不重放历史通知。桌面端通过该流,在切换到 Welcome 时交接一次性 toast。 - -`hasRunningAccountTasks` 通过账号模块的判断函数,检查运行中 Agent 最近记录的请求上下文,包括工具和重试阶段。空闲 Agent 及 API key 上下文不计入。移除凭据时,账号提供方独立取消匹配任务。 - - -## 理解实现 - -控制器向账号服务转发操作,不维护独立的账号状态。 - - -## 深入探索 - -[凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 - - -## 模型体验 - -无,因为账号凭证只影响 HTTP 认证,不进入模型提示、Session 日志或工具结果。 - -#### KV Cache effect - -不改变模型请求前缀。 - -## 已知限制与后续工作 - - - -- UI 断线后可通过 watch 恢复状态,但不能在 Host 退出后恢复登录尝试。凭证和请求 token 解析不对 Remote 暴露。 - - -### 开发备注 - -[桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 diff --git a/packages/api/account-controller/locale/de.json b/packages/api/account-controller/locale/de.json deleted file mode 100644 index f1e7b8ca6c..0000000000 --- a/packages/api/account-controller/locale/de.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Benutzeroberfläche für den Kontobetrieb", - "description": "Bieten Sie authentifizierten Clients Kontoverwaltungsfunktionen." - } -} diff --git a/packages/api/account-controller/locale/en.json b/packages/api/account-controller/locale/en.json deleted file mode 100644 index 4c7e6dd036..0000000000 --- a/packages/api/account-controller/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "api-account-controller" - } -} diff --git a/packages/api/account-controller/locale/es.json b/packages/api/account-controller/locale/es.json deleted file mode 100644 index 7bfaac6431..0000000000 --- a/packages/api/account-controller/locale/es.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interfaz de operación de cuenta", - "description": "Proporcionar capacidades de operación de cuentas a clientes autenticados." - } -} diff --git a/packages/api/account-controller/locale/fr.json b/packages/api/account-controller/locale/fr.json deleted file mode 100644 index a77bd7e7a1..0000000000 --- a/packages/api/account-controller/locale/fr.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface d'opération de compte", - "description": "Fournir des capacités d’exploitation de compte aux clients authentifiés." - } -} diff --git a/packages/api/account-controller/locale/ja.json b/packages/api/account-controller/locale/ja.json deleted file mode 100644 index 7ffcd54dda..0000000000 --- a/packages/api/account-controller/locale/ja.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "アカウント操作 API", - "description": "認証済みクライアントにアカウント操作機能を提供します。" - } -} diff --git a/packages/api/account-controller/locale/pt.json b/packages/api/account-controller/locale/pt.json deleted file mode 100644 index 22670a3e3b..0000000000 --- a/packages/api/account-controller/locale/pt.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Interface de operação da conta", - "description": "Fornece recursos de operação de conta para clientes autenticados." - } -} diff --git a/packages/api/account-controller/locale/ru.json b/packages/api/account-controller/locale/ru.json deleted file mode 100644 index dd3e515e30..0000000000 --- a/packages/api/account-controller/locale/ru.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "Интерфейс работы со счетом", - "description": "Предоставьте возможности управления учетной записью аутентифицированным клиентам." - } -} diff --git a/packages/api/account-controller/locale/zh.json b/packages/api/account-controller/locale/zh.json deleted file mode 100644 index f404257eaa..0000000000 --- a/packages/api/account-controller/locale/zh.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "meta": { - "title": "账号操作接口", - "description": "向已认证的客户端提供账号操作能力。" - } -} diff --git a/packages/api/account-controller/package.json b/packages/api/account-controller/package.json deleted file mode 100644 index 7731b7150d..0000000000 --- a/packages/api/account-controller/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-api-account-controller", - "description": "Expose safe account operations over authenticated Remote", - "version": "0.2.2-rc.1", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/api/account-controller" - }, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./types": { - "types": "./lib/types/types.d.ts", - "default": "./lib/types/types.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json", - "./typert": { - "types": "./lib/typert.host.d.ts", - "default": "./lib/typert.host.js" - }, - "./remote": { - "types": "./lib/typert.remote-client.d.ts", - "default": "./lib/typert.remote-client.js" - }, - "./locale/*.json": "./locale/*.json" - }, - "files": [ - "locale/*.json", - "lib/index.js", - "lib/types/**/*.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "lib/**/*.js.map", - "lib/typert.host.js", - "lib/typert.host.d.ts", - "lib/typert.remote-client.js", - "lib/typert.remote-client.d.ts", - "lib/typert.remote-client.d.ts.map", - "src" - ], - "license": "MIT", - "dependencies": { - "zod": "4.6.6" - }, - "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*" - }, - "devDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-agent": "workspace:*" - } -} diff --git a/packages/api/account-controller/src/index.ts b/packages/api/account-controller/src/index.ts deleted file mode 100644 index ff065388b0..0000000000 --- a/packages/api/account-controller/src/index.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** Authenticated Remote operations for account UI consumers. */ -import { Context } from '@deepseek-ai/cordis' -import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import { isRunningAccountTask } from '@deepseek-ai/dsh-deepseek-account' -import type {} from '@deepseek-ai/dsh-agent' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import type { AccountView, SignInAttemptId } from './types.ts' - -/** Account commands and reconnect-safe state stream. */ -export class AccountController extends TypertRemoteService { - static inject = ['deepseekAccount', 'agents'] - /** @param ctx - Host with the account provider mounted. */ - constructor(ctx: Context) { super(ctx, 'accountController', { namespace: 'account' }) } - /** - * Read the safe account projection. - * @returns current account and attempt state. - */ - @Remote - getState(): Promise { return this.ctx.deepseekAccount.getState() } - /** - * Query display-safe Platform profile data. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns profile outcome, or null when the account grant is absent or changed. - */ - @Remote - getProfile(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getProfile(client) - } - /** - * Query Platform recharge-wallet balances. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns balance outcome, or null when the account grant is absent or changed. - */ - @Remote - getBalance(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getBalance(client) - } - /** - * Query the granted bonuses Platform has not yet recorded as displayed. - * @param client - identity of the requesting UI; its language selects the server-authored message. - * @returns bonuses with their account, or null when the account grant is absent or changed. - */ - @Remote - getUnnotifiedBonuses(client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.getUnnotifiedBonuses(client) - } - /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI; the Host derives Platform request headers from it. - * @returns true once Platform records the acknowledgement; false when the account is absent or changed. - */ - @Remote - ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise { - return this.ctx.deepseekAccount.ackBonusNotified(accountId, orderId, client) - } - /** - * Begin browser sign-in. - * @param client - identity of the requesting UI, captured by a new attempt. - * @param callbackOrigin - browser-accessible loopback HTTP origin. - * @param loginSource - initiating UI, used to return from a failed exchange. - * @returns a new or already-active login attempt. - */ - @Remote - startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { - return this.ctx.deepseekAccount.startSignIn(client, callbackOrigin, loginSource) - } - /** - * Cancel the named local attempt. - * @param attemptId - attempt to cancel. - * @returns settled cancellation or commit state. - */ - @Remote - cancelSignIn(attemptId: SignInAttemptId): Promise { return this.ctx.deepseekAccount.cancelSignIn(attemptId) } - /** - * Inspect the latest logged request providers of running tasks, including tools and retries. - * @returns whether running work has a latest request context on the account route. - */ - @Remote - hasRunningAccountTasks(): boolean { - return this.ctx.agents.list().some(isRunningAccountTask) - } - /** - * Remove the local account grant and revoke it through Platform in the background, without deleting API keys. - * @param client - identity of the requesting UI, captured for the background revocation retries. - * @returns state after removing the local account grant. - */ - @Remote - signOut(client: AccountClientMetadata): Promise { return this.ctx.deepseekAccount.signOut(client) } - /** - * Subscribe to credential expiry without replaying prior notifications. - * @param signal - stream lifetime. - * @returns notifications emitted while subscribed. - */ - @Remote({ mode: 'stream' }) - async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> { - let pending = 0 - let wake: (() => void) | undefined - const stop = this.ctx.on('deepseek-account/session-expired', () => { pending++; wake?.() }) - const abort = (): void => { wake?.() } - signal.addEventListener('abort', abort, { once: true }) - try { - while (!signal.aborted) { - if (pending > 0) { pending--; yield 'session-expired'; continue } - await new Promise((resolve) => { wake = resolve }) - } - } finally { - stop() - signal.removeEventListener('abort', abort) - } - } - /** - * Stream the safe account projection. - * @param signal - stream lifetime. - * @returns initial snapshot and subsequent changes. - */ - @Remote({ mode: 'stream' }) - watch(signal: AbortSignal): AsyncIterable { return this.ctx.deepseekAccount.watch(signal) } -} -export default AccountController diff --git a/packages/api/account-controller/src/types.ts b/packages/api/account-controller/src/types.ts deleted file mode 100644 index 3d105804f8..0000000000 --- a/packages/api/account-controller/src/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Account Remote values contain no credential payloads. */ -export type { AccountBonusBatch, AccountBonusNotification, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountProfile, AccountUserId, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' diff --git a/packages/api/account-controller/tests/controller.spec.ts b/packages/api/account-controller/tests/controller.spec.ts deleted file mode 100644 index 2360bdc84e..0000000000 --- a/packages/api/account-controller/tests/controller.spec.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** Account Remote delegation preserves provider results, failures, and stream lifetime. */ -import { Context } from '@deepseek-ai/cordis' -import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import type { AccountView, SignInAttemptId } from '../src/types.ts' -import { afterEach, expect, it, vi } from 'vitest' -import AccountController from '../src/index.ts' - -const roots: Context[] = [] -afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) }) -const state: AccountView = { status: 'signed-out', links: { usageUrl: 'https://platform.example/usage', topUpUrl: 'https://platform.example/top_up' }, attempt: null } -const client: AccountClientMetadata = { version: '0.0.0-test', locale: 'zh-CN', timezoneOffsetSeconds: 28_800 } - -function fixture() { - const ctx = new Context() - roots.push(ctx) - const provider = { - getState: vi.fn().mockResolvedValue(state), - getProfile: vi.fn().mockResolvedValue({ status: 'failed' }), - getBalance: vi.fn().mockResolvedValue(null), - getUnnotifiedBonuses: vi.fn().mockResolvedValue(null), - ackBonusNotified: vi.fn().mockResolvedValue(false), - startSignIn: vi.fn().mockResolvedValue(state), - cancelSignIn: vi.fn().mockResolvedValue(state), - signOut: vi.fn().mockResolvedValue(state), - watch: vi.fn(), - } - ctx.provide('deepseekAccount', provider as never) - return { ctx, provider, controller: new AccountController(ctx) } -} - -it('delegates account operations without coupling profile and balance queries', async () => { - const { provider, controller } = fixture() - expect(await controller.getState()).toBe(state) - expect(await controller.getProfile(client)).toEqual({ status: 'failed' }) - expect(provider.getBalance).not.toHaveBeenCalled() - expect(await controller.getBalance(client)).toBeNull() - expect(await controller.startSignIn(client, 'http://127.0.0.1:8080', 'desktop')).toBe(state) - expect(provider.startSignIn).toHaveBeenCalledExactlyOnceWith(client, 'http://127.0.0.1:8080', 'desktop') - const id = 'attempt' as SignInAttemptId - expect(await controller.cancelSignIn(id)).toBe(state) - expect(provider.cancelSignIn).toHaveBeenCalledExactlyOnceWith(id) - expect(await controller.signOut(client)).toBe(state) - expect(provider.signOut).toHaveBeenCalledExactlyOnceWith(client) - const failure = new Error('storage unavailable') - provider.signOut.mockRejectedValueOnce(failure) - await expect(controller.signOut(client)).rejects.toBe(failure) -}) - -it('delegates bonus reads and acknowledgements without altering their values', async () => { - const { provider, controller } = fixture() - const accountId = 'account' as AccountUserId - const orderId = 'order' as AccountBonusOrderId - const batch: AccountBonusBatch = { accountId, bonuses: [{ orderId, expiresAt: '2026-10-21T12:00:00Z', message: '已赠送您 5.00 元 DSH 体验赠金。' }] } - provider.getUnnotifiedBonuses.mockResolvedValueOnce(batch) - expect(await controller.getUnnotifiedBonuses(client)).toBe(batch) - expect(provider.getUnnotifiedBonuses).toHaveBeenCalledExactlyOnceWith(client) - provider.ackBonusNotified.mockResolvedValueOnce(true) - expect(await controller.ackBonusNotified(accountId, orderId, client)).toBe(true) - expect(provider.ackBonusNotified).toHaveBeenCalledExactlyOnceWith(accountId, orderId, client) - const failure = new Error('unavailable') - provider.getUnnotifiedBonuses.mockRejectedValueOnce(failure) - await expect(controller.getUnnotifiedBonuses(client)).rejects.toBe(failure) -}) - -it('passes the subscriber lifetime to the provider and returns its state stream', async () => { - const { provider, controller } = fixture() - const lifetime = new AbortController() - const stream: AsyncIterable = { async *[Symbol.asyncIterator]() { yield state } } - provider.watch.mockReturnValue(stream) - expect(controller.watch(lifetime.signal)).toBe(stream) - expect(provider.watch).toHaveBeenCalledExactlyOnceWith(lifetime.signal) - const received: AccountView[] = [] - for await (const value of stream) received.push(value) - expect(received).toEqual([state]) -}) - -it('delivers expiry only to current subscribers and stops on disconnect', async () => { - const { ctx, controller } = fixture() - ctx.emit('deepseek-account/session-expired') - const lifetime = new AbortController() - const iterator = controller.watchExpiry(lifetime.signal)[Symbol.asyncIterator]() - const first = iterator.next() - ctx.emit('deepseek-account/session-expired') - expect(await first).toEqual({ done: false, value: 'session-expired' }) - const next = iterator.next() - lifetime.abort() - expect(await next).toEqual({ done: true, value: undefined }) - const reconnect = new AbortController() - const reopened = controller.watchExpiry(reconnect.signal)[Symbol.asyncIterator]().next() - reconnect.abort() - expect(await reopened).toEqual({ done: true, value: undefined }) -}) diff --git a/packages/api/account-controller/tests/signout-impact.spec.ts b/packages/api/account-controller/tests/signout-impact.spec.ts deleted file mode 100644 index 837deddd27..0000000000 --- a/packages/api/account-controller/tests/signout-impact.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** Sign-out impact follows the latest logged provider of running tasks. */ -import { Context } from '@deepseek-ai/cordis' -import { expect, it } from 'vitest' -import type { Agent } from '@deepseek-ai/dsh-agent' -import { AccountController } from '../src/index.ts' - -it('reports running account requests and excludes idle or unbound tasks', async () => { - const ctx = new Context() - const active: Array> = [] - const task = (status: Agent['status'], provider?: string): Pick => ({ - status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], - }) - ctx.provide('agents', { list: () => active } as Context['agents']) - const controller = new AccountController(ctx) - try { - expect(controller.hasRunningAccountTasks()).toBe(false) - active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) - expect(controller.hasRunningAccountTasks()).toBe(false) - active.push(task('running', 'deepseek-account')) - expect(controller.hasRunningAccountTasks()).toBe(true) - active.pop() - expect(controller.hasRunningAccountTasks()).toBe(false) - } finally { await ctx.fiber.dispose() } -}) diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index bf7dbbfa08..25718e223b 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -100,7 +100,6 @@ "@deepseek-ai/dsh-plugin-market": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", - "@deepseek-ai/dsh-api-account-controller": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-agent-team": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 88a41e3830..5d91957c0a 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -8,7 +8,7 @@ import userQuestionsRemote from '@deepseek-ai/dsh-user-questions/remote' import commandsRemote from '@deepseek-ai/dsh-commands/remote' import agentTeamsRemote from '@deepseek-ai/dsh-agent-team/remote' export type {} from '@deepseek-ai/dsh-agent-team/remote' -import accountRemote from '@deepseek-ai/dsh-api-account-controller/remote' +import accountRemote from '@deepseek-ai/dsh-deepseek-account/remote' import settingsControllerRemote from '@deepseek-ai/dsh-api-settings-controller/remote' import officeKitRemote from '@deepseek-ai/dsh-office-kit/remote' import goalsRemote from '@deepseek-ai/dsh-goal/remote' @@ -60,7 +60,7 @@ export type {} from '@deepseek-ai/dsh-user-questions/remote' export type {} from '@deepseek-ai/dsh-commands/remote' export type {} from '@deepseek-ai/dsh-web/remote' export type {} from '@deepseek-ai/dsh-api-settings-controller/remote' -export type {} from '@deepseek-ai/dsh-api-account-controller/remote' +export type {} from '@deepseek-ai/dsh-deepseek-account/remote' export type {} from '@deepseek-ai/dsh-goal/remote' export type {} from '@deepseek-ai/dsh-schedule/remote' export type {} from '@deepseek-ai/dsh-office-kit/remote' diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 165661a57e..2e82590c7a 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -112,9 +112,6 @@ { "path": "../../document/office-kit" }, - { - "path": "../account-controller" - }, { "path": "../../credentials/deepseek-account" }, diff --git a/packages/api/remotes/tsconfig.host.json b/packages/api/remotes/tsconfig.host.json index 7c0421f641..33a538658d 100644 --- a/packages/api/remotes/tsconfig.host.json +++ b/packages/api/remotes/tsconfig.host.json @@ -89,9 +89,6 @@ { "path": "../../host/plugin-inventory" }, - { - "path": "../account-controller" - }, { "path": "../../credentials/deepseek-account" }, diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 3d31867b67..94482498be 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 9cac36e3c0a32959 - zh: 37c42cc3edafa798 + en: 50fa3dd0a2ce79c8 + zh: 88bd7ea6058d2122 /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index b430594b0e..f414ce78ef 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -70,7 +70,7 @@ Fork copies the exact inclusive event prefix selected by `atSeq`, including a cu A resume blocked by an existing write handle returns `session/writer-held` with the Session id; other resume failures retain `gateway/internal`. -`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` publishes one Host-selected page directly. +`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` prepares and consumes one Host-selected page; `{ deferConsumption: true }` retains that page until `consumeOlder()` publishes it synchronously. A retained page blocks another ordinary request without blocking live events. `historyLoadStatus` distinguishes `idle`, `loading`, `pendingConsumption`, and `error`; `loadingOlder` is derived from `loading`, including Turn jumps. Failures and pages without progress permit explicit retry rather than claiming exhaustion. `historyWasPartial` remembers an incomplete visible window for the Client Session lifetime, including reconnects, without persisting presentation state. The Client's initial `follow`, reconnect openings, and `loadOlder()` request at least 50 append-origin `user/message` and `assistant/message` events and cross at least two `turn/start` events, including the partial Turn at the loaded window's beginning. The Host stops at the first Turn start satisfying both minima, or at 500 counted messages or history exhaustion, whichever comes first. Steering does not add a Turn boundary. Intervening events accompany the page without counting toward the message budget. The optional `turnWindow` on page and follow requests supplies these minima under `maxMessages`. `loadThrough()` uses the same rules with a 200-message minimum per page; the 500-message cap does not limit the whole jump. Requests without `turnWindow` retain message-aligned paging. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 314ec58840..2a83f4504d 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -70,7 +70,7 @@ Fork 将 `atSeq` 选定的含边界事件前缀(包括开放轮次内的截点 恢复会话时若已有写句柄占用,返回 `session/writer-held`,并携带会话 id;其他恢复失败仍返回 `gateway/internal`。 -`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 直接发布 Host 选取的一页结果。 +`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 准备并消费 Host 选取的一页;传入 `{ deferConsumption: true }` 时保留这一页,直到 `consumeOlder()` 同步发布。暂存页阻止重复普通请求,但不阻止实时事件。`historyLoadStatus` 区分 `idle`、`loading`、`pendingConsumption` 和 `error`;`loadingOlder` 从 `loading` 派生,包含 Turn 跳转。失败和无进展页面允许明确重试,不伪装成历史耗尽。`historyWasPartial` 在客户端 Session 生命周期内记住可见窗口曾不完整,重连保留,但不持久化呈现状态。 Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 append 方式追加的 `user/message` 和 `assistant/message` 事件,并向前跨过至少两个 `turn/start`,其中包含已加载窗口开头尚未补齐的轮次。Host 在首次同时满足两个下限的轮次开头停止;若先达到 500 条计数消息或历史已耗尽,则立即返回。Steering 不增加轮次分界。区间内的其他事件随页返回,但不计入消息预算。分页和 follow 请求可选的 `turnWindow` 在 `maxMessages` 上限内指定这两个下限。`loadThrough()` 复用相同规则,仅将每页消息数下限设为 200;500 条上限不限制整次跳转。不带 `turnWindow` 的请求保留按消息对齐的分页方式。 diff --git a/packages/api/session-controller/src/client/contract/session.ts b/packages/api/session-controller/src/client/contract/session.ts index 9233ac84cb..ce060ec4aa 100644 --- a/packages/api/session-controller/src/client/contract/session.ts +++ b/packages/api/session-controller/src/client/contract/session.ts @@ -4,8 +4,8 @@ * ObservableSnapshot half), and orchestration code calls the behavior verbs * below — nothing else. Widening this interface is the explicit act of * widening what features may do to a session (and what every test fixture - * must stub); implementation-internal entry points (history staging, wire-frame - * dispatch) stay on the class, invisible out here. + * must stub); implementation-internal wire-frame dispatch stays on the class, + * invisible out here. */ import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' @@ -132,10 +132,18 @@ export interface ISession { /** * Extend history by at least 50 messages and two Turn starts, including a * partial Turn at the window's beginning. Stop at 500 messages or history - * exhaustion even when those minima cannot be met. Publish one prepend. - * @returns completion; failures land in snapshot.openState/loadingOlder. + * exhaustion even when those minima cannot be met. At most one page may be + * loading or awaiting consumption; live events remain independently visible. + * @param options - deferConsumption keeps the page unpublished until consumeOlder; omitted consumes before completion. + * @returns request completion; failures and no progress set snapshot.historyLoadStatus to error. */ - loadOlder(): Promise + loadOlder(options?: { deferConsumption?: boolean }): Promise + /** + * Publish the prepared page synchronously if its generation and starting cursor still match. + * A terminal empty page may publish hasMore=false; an invalidated page is discarded. + * @returns whether a prepared page was published; false while loading, absent, or invalidated. + */ + consumeOlder(): boolean /** * Page history backwards until the window covers `seq` (inclusive) — the * turn-jump loader. Repeated calls while a jump is paging lower its shared diff --git a/packages/api/session-controller/src/client/contract/snapshot.ts b/packages/api/session-controller/src/client/contract/snapshot.ts index 4912d19b16..b6ba71b907 100644 --- a/packages/api/session-controller/src/client/contract/snapshot.ts +++ b/packages/api/session-controller/src/client/contract/snapshot.ts @@ -78,7 +78,12 @@ export interface SessionSnapshot { readonly openState: OpenState readonly openError: RemoteFailure | null readonly hasMore: boolean + /** This Client Session has exposed an incomplete history window; remains true across replacements. */ + readonly historyWasPartial: boolean + /** Whether historyLoadStatus is loading, including Turn-jump requests. */ readonly loadingOlder: boolean + /** History request status; pendingConsumption retains an unpublished ordinary page. */ + readonly historyLoadStatus: 'idle' | 'loading' | 'pendingConsumption' | 'error' readonly promptError: PromptError | null readonly blank: boolean readonly lastAgentError: string | null diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index e74dd84422..60194de5eb 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -67,6 +67,16 @@ interface PendingHistory { readonly pages: (readonly SessionEventLikeEntry[])[] } +interface OlderHistoryRequest { + readonly generation: number + readonly beforeSeq: SessionLogOffset + page: { readonly entries: readonly SessionEventLikeEntry[]; readonly hasMore: boolean } | null + invalidated: boolean + recovering: boolean + consuming: boolean + promise?: Promise +} + /** Manager-owned observers of a Session object's local state edges. */ export interface SessionOptions { /** Catalog-discovered address selecting non-activating subagent transport. */ @@ -95,13 +105,16 @@ export class Session implements SessionFace { // ---- Window and derived state (all private; the snapshot is the only read API) ---- private baseSeq = SessionLogOffset(0) private hasMore = false + private historyWasPartial = false private openState: OpenState = 'cold' private openError: RemoteFailure | null = null private openPromise: Promise | null = null /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale * passes drop all writes once the generation moves on. */ private openGeneration = 0 - private loadingOlder = false + private get loadingOlder(): boolean { return this.historyLoadStatus === 'loading' } + private historyLoadStatus: SessionSnapshot['historyLoadStatus'] = 'idle' + private olderRequest: OlderHistoryRequest | null = null /** Shared low-water target of the running jump loop; null when no jump is paging. */ private jumpTargetSeq: SessionSeq | null = null /** The running jump loop's completion, shared by retargeting callers. */ @@ -415,30 +428,95 @@ export class Session implements SessionFace { return promise } - /** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */ - async loadOlder(): Promise { - if (this.openState !== 'open' || !this.hasMore || this.loadingOlder) return + /** @inheritdoc */ + async loadOlder(options?: { deferConsumption?: boolean }): Promise { + const request = this.prepareOlder() + await request?.promise + if (request !== null && this.olderRequest === request + && (!options?.deferConsumption || request.page?.entries.length === 0)) this.consumeOlder() + } + + private prepareOlder(): OlderHistoryRequest | null { + if (this.olderRequest !== null) return this.olderRequest const events = this.events - if (events === undefined) return - this.loadingOlder = true + if (this.openState !== 'open' || !this.hasMore || this.loadingOlder || events === undefined) return null + const request: OlderHistoryRequest = { + generation: this.openGeneration, + beforeSeq: this.baseSeq, + page: null, + invalidated: false, + recovering: false, + consuming: false, + } + this.olderRequest = request + this.historyLoadStatus = 'loading' this.notifier.markDirty() - try { - await events.prepend({ - beforeSeq: this.baseSeq, - ...HISTORY_PAGE_OPTIONS, - }) - } catch (error) { - if (!isRemoteFailure(error)) { - console.error('[session-controller] loadOlder failed:', error) + request.promise = (async () => { + try { + await events.prepend({ beforeSeq: request.beforeSeq, ...HISTORY_PAGE_OPTIONS }) + if (this.olderRequest !== request) return + if (request.invalidated || request.generation !== this.openGeneration || request.beforeSeq !== this.baseSeq) return + const page = request.page + const first = page?.entries[0] + this.historyLoadStatus = page === null || (first === undefined ? page.hasMore : first.event.seq >= request.beforeSeq) + ? 'error' : 'pendingConsumption' + } catch (error) { + if (this.olderRequest !== request) return + request.page = null + this.historyLoadStatus = 'error' + if (!isRemoteFailure(error)) console.error('[session-controller] loadOlder failed:', error) + } finally { + if (this.olderRequest === request) { + if (request.invalidated && this.events === events) { + // A replacement restores the transport cursor before another page uses the visible window. + request.recovering = true + this.historyLoadStatus = 'loading' + events.restart() + } else if (this.historyLoadStatus === 'error') this.olderRequest = null + this.notifier.markDirty() + } } + })() + return request + } + + /** @inheritdoc */ + consumeOlder(): boolean { + const request = this.olderRequest + if (request === null || request.consuming || this.historyLoadStatus !== 'pendingConsumption' || request.page === null) return false + if (this.openState !== 'open' || request.invalidated || request.generation !== this.openGeneration + || request.beforeSeq !== this.baseSeq) { + this.clearOlderHistory() + return false + } + const page = request.page + // Retain the request through synchronous feed notification so subscribers cannot reenter consumption. + request.consuming = true + try { + this.prependWindow(page.entries, page.hasMore) + return true + } catch (error) { + if (this.olderRequest === request) this.historyLoadStatus = 'error' + throw error } finally { - this.loadingOlder = false + if (this.olderRequest === request) { + this.olderRequest = null + if (this.historyLoadStatus !== 'error') this.historyLoadStatus = 'idle' + } this.notifier.markDirty() } } + private clearOlderHistory(): void { + this.olderRequest = null + this.historyLoadStatus = this.pendingHistory === null ? 'idle' : 'loading' + this.notifier.markDirty() + } + /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */ loadThrough(seq: SessionSeq): Promise { + this.consumeOlder() + if (this.olderRequest !== null) return Promise.resolve() if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve() if (this.jumpPromise !== null) { // Retarget the running loop to the lowest requested seq. @@ -459,7 +537,7 @@ export class Session implements SessionFace { } this.pendingHistory = pending this.jumpTargetSeq = seq - this.loadingOlder = true + this.historyLoadStatus = 'loading' this.notifier.markDirty() // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the // stream generation; this pass then stops instead of paging the new @@ -467,27 +545,35 @@ export class Session implements SessionFace { const generation = this.openGeneration this.jumpPromise = (async () => { try { - while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { + while (this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { if (generation !== this.openGeneration) return const before = pending.beforeSeq await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS }) + if (generation !== this.openGeneration || this.pendingHistory !== pending) return // No-progress guard: an empty or dropped page that still claims more // history must end the loop, not spin it. - if (pending.beforeSeq >= before) return + if (pending.beforeSeq >= before) { + if (pending.hasMore) this.historyLoadStatus = 'error' + return + } + if (!pending.hasMore) return } } catch (error) { + if (generation === this.openGeneration && this.pendingHistory === pending) this.historyLoadStatus = 'error' if (!isRemoteFailure(error)) { console.error('[session-controller] loadThrough failed:', error) } } finally { - this.jumpTargetSeq = null - this.jumpPromise = null - this.pendingHistory = null - this.loadingOlder = false - if (generation === this.openGeneration && pending.pages.length > 0) { - this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + if (this.pendingHistory === pending) { + this.jumpTargetSeq = null + this.jumpPromise = null + this.pendingHistory = null + if (this.historyLoadStatus === 'loading') this.historyLoadStatus = 'idle' + if (generation === this.openGeneration && pending.pages.length > 0) { + this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + } + this.notifier.markDirty() } - this.notifier.markDirty() } })() return this.jumpPromise @@ -499,6 +585,7 @@ export class Session implements SessionFace { async resync(): Promise { if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open) this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -606,6 +693,7 @@ export class Session implements SessionFace { else this.retireFailedSubmission(requestId) } this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -655,7 +743,9 @@ export class Session implements SessionFace { ) return case 'prepend': - this.prependWindow(change.entries, change.hasMore) + if (this.olderRequest !== null) { + this.olderRequest.page = { entries: change.entries, hasMore: change.hasMore } + } else this.prependWindow(change.entries, change.hasMore) return case 'append': this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry)) @@ -676,8 +766,13 @@ export class Session implements SessionFace { // attempts makes a held notification reopen follow once for an atomic // page/baseline pair instead of applying it to an unrelated repair cut. const visible = this.assistantStream.replace(entries, assistantStream) + if (this.olderRequest !== null && this.loadingOlder && !this.olderRequest.recovering) { + this.olderRequest.invalidated = true + this.olderRequest.page = null + } else this.clearOlderHistory() this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0) this.hasMore = hasMore + this.historyWasPartial ||= hasMore if (this.pendingHistory !== null) { this.pendingHistory.beforeSeq = this.baseSeq this.pendingHistory.hasMore = hasMore @@ -745,6 +840,7 @@ export class Session implements SessionFace { } this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq) this.hasMore = hasMore + this.historyWasPartial ||= hasMore this.eventSource.prepend(entries, hasMore) } @@ -892,6 +988,7 @@ export class Session implements SessionFace { if (generation !== this.openGeneration || this.events !== events) return if (!isRemoteFailure(error)) throw error this.openGeneration++ + this.clearOlderHistory() this.events = undefined this.openPromise = null this.openState = 'error' @@ -917,7 +1014,9 @@ export class Session implements SessionFace { openState: this.openState, openError: this.openError, hasMore: this.hasMore, + historyWasPartial: this.historyWasPartial, loadingOlder: this.loadingOlder, + historyLoadStatus: this.historyLoadStatus, promptError: this.promptError, blank: this.blankBit, lastAgentError: this.lastAgentError, diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index e118ef29e5..6c6d308fe9 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -199,6 +199,194 @@ describe('paging', () => { expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) }) + it('stages one page without hiding live events and consumes it once', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + await session.loadOlder({ deferConsumption: true }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + await pushEvent(mock, ev.turnStart(SessionSeq(12), 2)) + const consumeStates: { status: string; loading: boolean }[] = [] + const stop = session.eventSource.subscribe(() => { + session.handleRunning(true) + const snapshot = session.getSnapshot() + consumeStates.push({ status: snapshot.historyLoadStatus, loading: snapshot.loadingOlder }) + expect(session.consumeOlder()).toBe(false) + void session.loadOlder({ deferConsumption: true }) + }) + try { + expect(session.consumeOlder()).toBe(true) + } finally { + stop() + } + expect(consumeStates).toEqual([{ status: 'pendingConsumption', loading: false }]) + expect(session.consumeOlder()).toBe(false) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq).concat(SessionSeq(12))) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', hasMore: false }) + }) + + it('joins a deferred request for default consumption without requesting another page', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + const gate = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(gate.promise) + await session.open() + const preparing = session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) + const consuming = session.loadOlder() + gate.resolve(history(older)) + await Promise.all([preparing, consuming]) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('default loading consumes an already prepared page without another request', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadOlder() + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('does not consume a newer prepared page when an obsolete default request completes', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + const obsolete = Promise.withResolvers() + const prepend = vi.spyOn(SessionEventStream.prototype, 'prepend').mockImplementationOnce(() => obsolete.promise) + const loading = session.loadOlder() + try { + await session.resync() + await session.loadOlder({ deferConsumption: true }) + obsolete.resolve(undefined) + await loading + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + expect(session.consumeOlder()).toBe(true) + } finally { + obsolete.resolve(undefined) + await loading + prepend.mockRestore() + } + }) + + it('retains partial-history knowledge across exhaustion and replacement only for the same Session instance', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const complete = [...older, ...newer] + const session = await sessionBench(mock, start, SID) + expect(session.getSnapshot().historyWasPartial).toBe(false) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + expect(session.getSnapshot().historyWasPartial).toBe(true) + await session.loadOlder() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.stream(FOLLOW, followScript(history(complete, false))) + await session.resync() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace complete window')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(3) }) + await mock.streams.drained(FOLLOW) + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + const client = await start() + const fresh = new Session(SID, client.ctx.remote) + onTestFinished(() => fresh.dispose()) + expect(fresh.getSnapshot().historyWasPartial).toBe(false) + await fresh.open() + expect(fresh.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: false }) + }) + + it('reports no progress and allows an explicit retry to confirm exhaustion', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, 'new', 'answer'), true))) + mock.remote.session.page.mockImplementation(pageRule(history([], true))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) + expect(session.consumeOlder()).toBe(false) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(mock.log.requests(PAGE)).toHaveLength(2) + }) + + it('consumes a staged page before a turn jump fetches the remaining history', async ({ mock, start }) => { + const oldest = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const middle = plainTurn(SessionSeq(6), 1, 'middle', 'answer') + const newest = plainTurn(SessionSeq(12), 2, 'newest', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(request => history( + request.beforeSeq === 12 ? middle : oldest, request.beforeSeq === 12, + ))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadThrough(SessionSeq(0)) + expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) + expect((mock.log.requests(PAGE) as SessionPageRequest[]).map(request => request.beforeSeq)).toEqual([12, 6]) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + }) + + it('invalidates a staged page when the event window is replaced', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.resync() + expect(session.consumeOlder()).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + }) + + it('repairs the transport cursor when follow replaces a window during an older request', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + const page = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(page.promise) + await session.open() + const loading = session.loadOlder({ deferConsumption: true }) + await vi.waitFor(() => { expect(mock.log.requests(PAGE)).toHaveLength(1) }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace while paging')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(2) }) + await mock.streams.drained(FOLLOW) + page.resolve(history(older)) + await loading + await vi.waitFor(() => { + expect(mock.log.requests(FOLLOW)).toHaveLength(3) + expect(session.getSnapshot().historyLoadStatus).toBe('idle') + }) + expect(session.consumeOlder()).toBe(false) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.loadOlder() + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + }) + it('installs a page without interpreting business replacement metadata', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history([ @@ -218,7 +406,7 @@ describe('paging', () => { } }) - it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async ({ mock, start }) => { + it('reports a discontinuous older page without claiming history exhaustion', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(10), 1, '新', '页'), true))) mock.remote.session.page.mockImplementation(pageRule(history(plainTurn(SessionSeq(0), 0, '断', '层'), true))) // tail seq 5, but baseSeq is 10 → hole @@ -229,7 +417,7 @@ describe('paging', () => { await session.loadOlder() const snapshot = session.getSnapshot() expect(session.eventSource.getSnapshot().entries).toEqual(windowBefore.entries) - expect(snapshot.hasMore).toBe(false) + expect(snapshot).toMatchObject({ hasMore: true, historyLoadStatus: 'error' }) } finally { errorSpy.mockRestore() } @@ -247,11 +435,11 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(request => (request.beforeSeq === 12 ? history(middle, true) : history(oldest)))) mock.remote.session.page.mockReturnValueOnce(gate.promise) const jump = session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(true) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) gate.resolve(history(middle, true)) await jump const snapshot = session.getSnapshot() - expect(snapshot.loadingOlder).toBe(false) + expect(snapshot).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) expect(mock.log.requests(PAGE)).toMatchObject([ { beforeSeq: 12, maxMessages: 500, turnWindow: { minMessages: 200, minTurns: 2 } }, @@ -325,7 +513,7 @@ describe('paging', () => { expect(changed).toHaveBeenCalledOnce() expect(eventSeqs(session)).toEqual([...middle, ...newest].map(event => event.seq)) - expect(session.getSnapshot()).toMatchObject({ loadingOlder: false, hasMore: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) }) it('discards buffered jump pages when the Session replaces its stream', async ({ mock, start }) => { @@ -430,7 +618,19 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(history([], true))) // empty page still claiming more history await session.open() await session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + + it('loadThrough treats a terminal empty page as exhaustion rather than an error', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const newest = plainTurn(SessionSeq(12), 2, 'x', 'y') + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.open() + await session.loadThrough(SessionSeq(0)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(eventSeqs(session)).toEqual(newest.map(event => event.seq)) expect(mock.log.requests(PAGE)).toHaveLength(1) }) diff --git a/packages/api/settings-controller/README.i18n.yaml b/packages/api/settings-controller/README.i18n.yaml index 4b3f0d24d3..1077f9d6bd 100644 --- a/packages/api/settings-controller/README.i18n.yaml +++ b/packages/api/settings-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 3a654e12f423946b zh: 4e3a19aaee58f8a7 /settings-controller/use-this-package: - en: cf2f4de5bee8be55 - zh: b2630dcba4be5ae8 + en: 40b15565ed552a0e + zh: 3b0f125e3308aa13 /settings-controller/configuration: en: e0297f144b649af7 zh: e70ed56edffd97f0 diff --git a/packages/api/settings-controller/README.md b/packages/api/settings-controller/README.md index b38072546d..e85a4d12f1 100644 --- a/packages/api/settings-controller/README.md +++ b/packages/api/settings-controller/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) Mount this package as a Loader entry in a profile that serves browser configuration. The entry registers both namespaces independently of their providers so a missing provider produces a named configuration error at invocation. Its generated descriptors enter the strict Typert registry, while the settings and credential Definitions remain plain Cordis Services with no wire obligations of their own. -`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Secret values cross in this direction only: no method here returns one. +`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. The view may include a provider-generated `masked` preview, never the full stored value. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Full secret values cross in this direction only: no method here returns one. `settings.describe()` returns deployment facts and every namespace under `redactSecrets: true`. `settings.update`, `settings.replace`, and `settings.mutate` expose the settings service's three write operations and return the namespace's new redacted view; stale writes use `settings-conflict` and other provider refusals use `settings-rejected`. diff --git a/packages/api/settings-controller/README.zh.md b/packages/api/settings-controller/README.zh.md index 3c9e876740..c7d324b98e 100644 --- a/packages/api/settings-controller/README.zh.md +++ b/packages/api/settings-controller/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" 请把本包作为 Loader entry 挂载到提供浏览器配置的 profile 中。本 entry 不依赖提供方是否存在而注册两个 namespace,因此缺少提供方会在调用时产生具名配置错误。它生成的 descriptor 进入严格 Typert 注册表,而 settings 与凭据 Definition 仍是普通 Cordis 服务,自身不承担任何 wire 义务。 -`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 +`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。视图可包含提供方生成的 `masked` 预览,不包含完整的已保存值。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。完整机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 `settings.describe()` 返回部署信息,以及在 `redactSecrets: true` 下读取的所有 namespace。`settings.update`、`settings.replace` 与 `settings.mutate` 暴露 settings 服务的三种写入操作,并返回该 namespace 的新脱敏视图;陈旧写入使用 `settings-conflict`,其他提供方拒绝使用 `settings-rejected`。 diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 3889669048..038239ab49 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -47,6 +47,7 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo { configured: info.configured, ...info.source === undefined ? {} : { source: info.source }, writable: info.writable, + ...info.masked === undefined ? {} : { masked: info.masked }, } } @@ -61,7 +62,7 @@ declare module '@deepseek-ai/cordis' { * Host service backing the generated `ctx.remote.credentials` namespace. It * carries every wire obligation the credential seam itself does not: the batch * fan-out bound, the field-by-field view projection, the reference-grammar - * guard, and the refusal mapping. Secret values cross in one direction only — + * guard, and the refusal mapping. Full secret values cross in one direction only — * no method here returns one. */ export class CredentialsController extends TypertRemoteService { diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 5eeb190385..14f2ea2923 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -9,7 +9,7 @@ import { MemoryCredentials } from '../../../credentials/credentials/tests/memory class LeakyCredentials extends MemoryCredentials { override describe(): Promise { return Promise.resolve( - { configured: true, source: 'memory', writable: true, value: 'sk-leaked' } as CredentialInfo, + { configured: true, source: 'memory', writable: true, masked: '•'.repeat(9), value: 'sk-leaked', preview: 'sk…ed' } as CredentialInfo, ) } } @@ -101,8 +101,9 @@ describe('the credentials Remote namespace a configuration surface calls', () => it('answers only the fields the view declares, whatever a provider returns', async () => { const controller = await boot({}, LeakyCredentials) const described = await controller.describe(['DEEPSEEK_API_KEY']) - expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true }) + expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true, masked: '•'.repeat(9) }) expect(JSON.stringify(described)).not.toContain('sk-leaked') + expect(JSON.stringify(described)).not.toContain('sk…ed') }) it('stores and removes through the same references the batch describes', async () => { diff --git a/packages/api/workspace-files/README.i18n.yaml b/packages/api/workspace-files/README.i18n.yaml index 0dbb9b3f71..596997972c 100644 --- a/packages/api/workspace-files/README.i18n.yaml +++ b/packages/api/workspace-files/README.i18n.yaml @@ -3,20 +3,20 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/api/workspace-files/README.md /: - en: f83c75aa73ae21dd - zh: e8873aafd23a8038 + en: 47d66aa37cb2ffab + zh: 1568b049534ffa55 /deepseek-ai-dsh-api-workspace-files: en: d2885c72d12d9924 zh: e111f03d02383229 /deepseek-ai-dsh-api-workspace-files/summary: - en: 27c562441286bdbf - zh: 205dfac32c96873b + en: 1c5fd2461a374199 + zh: 914bb3f5c6d3d523 /deepseek-ai-dsh-api-workspace-files/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-api-workspace-files/use-this-package: - en: 874054ed5e950973 - zh: e8b55d62939c4c2f + en: a7cf7f26d6183666 + zh: 832b0b33fd389771 /deepseek-ai-dsh-api-workspace-files/use-this-package/addressing-and-paths: en: b9565cfa7a1da451 zh: fc4078a58322fc7f @@ -27,14 +27,17 @@ en: 93ca9e832fbfd632 zh: 69412adba259c6f8 /deepseek-ai-dsh-api-workspace-files/use-this-package/file-read-and-directory-checks: - en: aa85c7754557a22f - zh: c576d06749fbe0a5 + en: c53c72a4fab3d957 + zh: e20b359c6ea5caa5 +/deepseek-ai-dsh-api-workspace-files/use-this-package/search: + en: f5d2244caef36e4b + zh: d6df79a18f4caf36 /deepseek-ai-dsh-api-workspace-files/use-this-package/the-change-feed: en: 8bd2d820a512d461 zh: 0614ddd842ae7526 /deepseek-ai-dsh-api-workspace-files/use-this-package/configuration: - en: e606e8b22ac6e0d0 - zh: 13a7214448036d7b + en: 99ce72f0f731c570 + zh: 3f4c9bbd62844f1d /deepseek-ai-dsh-api-workspace-files/use-this-package/failures: en: c53d597c8f255e69 zh: 1e00318f9a34f3bb @@ -48,8 +51,8 @@ en: c3a8852c33dcc0e9 zh: d24fd47da7faaa29 /deepseek-ai-dsh-api-workspace-files/understand-the-implementation/source-map: - en: 596a75f43bfafda3 - zh: 3cb267a0946cd75e + en: c18e235fbd03e6be + zh: da1c4d03bf34657d /deepseek-ai-dsh-api-workspace-files/further-exploration: en: 71f00fb919d12181 zh: 1e3819cd90dfca31 @@ -60,8 +63,8 @@ en: ca75c51c89c2c9b0 zh: 03126f3b1aac5859 /deepseek-ai-dsh-api-workspace-files/known-limitations-and-deferred-work: - en: ee05e55f5d16f253 - zh: 0c937eeac8fa3f08 + en: 6e6286d98f3caf3f + zh: ab4d13e020a9cc34 /deepseek-ai-dsh-api-workspace-files/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/api/workspace-files/README.md b/packages/api/workspace-files/README.md index 9ceb0105fa..23cbaddcf7 100644 --- a/packages/api/workspace-files/README.md +++ b/packages/api/workspace-files/README.md @@ -1,5 +1,5 @@ --- -description: "Workspace file service for the web GUI: bounded reads and target-scoped filesystem watches, plus directory listing inside the Session workspace root." +description: "Workspace file service for the web GUI: bounded reads and target-scoped filesystem watches, plus directory listing and name or path search inside the Session workspace root." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Use this package to preview files readable through a Session's filesystem from the web client. It reads UTF-8 text by page, reads bounded byte windows or complete files, resolves related files from a base file's directory, and reports file metadata. Follow changes to a file or a directory's direct entries. File reads and watches may target paths outside the workspace; directory listing and watches remain workspace-scoped. The service exposes no mutation operation. +Use this package to preview files readable through a Session's filesystem from the web client. It reads UTF-8 text by page, reads bounded byte windows or complete files, resolves related files from a base file's directory, and reports file metadata. Follow changes to a file or a directory's direct entries. Search the workspace for entries by name or relative path. File reads and watches may target paths outside the workspace; directory listing, search, and directory watches remain workspace-scoped. The service exposes no mutation operation. ## Table of Contents @@ -25,7 +25,7 @@ Use this package to preview files readable through a Session's filesystem from t ## Use this package -Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session header or uses persistence `stat` for a cold Session; it does not activate an Agent, read the event body, or borrow a parent Session's root. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. +Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, `search(sessionId, request, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session header or uses persistence `stat` for a cold Session; it does not activate an Agent, read the event body, or borrow a parent Session's root. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. | Method | Returns | Purpose | |---|---|---| @@ -33,6 +33,7 @@ Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and | `read(path, { offset?, limit? })` | `WorkspaceFileText` = stat + `{ offset, text, lines, eof }` | One window of lines from a UTF-8 text file; `lines` counts them, so one empty line and a page past the end read differently | | `readBytes(path, { range?, baseFile? })` | `WorkspaceFileBytes` = stat + `{ offset, data, eof }` | Complete file or bounded byte range as `Uint8Array`; optionally resolve from another file's directory | | `list(path)` | `WorkspaceDirectoryListing { path, entries, truncated }` | Direct children of one directory | +| `search({ query, excludedPaths, includeHidden, respectGitignore })` | `WorkspaceFileSearchResult { matches, truncated, incomplete }` | Entries anywhere in the workspace whose name or relative path contains the query | | `changes(path)` | stream of `WorkspaceFileWatchFrame` | Subscription readiness, then invalidations of one file or a directory's direct entries | ### Addressing and paths @@ -51,7 +52,16 @@ Pass the required options object as `{}` for a complete file under `maxFileBytes ### File-read and directory checks -Every operation first uses `lstat` to reject a missing path or the wrong file kind; the file-reading operations also refuse a final symlink, even one pointing back inside the workspace. `list` instead follows a final link — a directory symlink on any platform, including a Windows junction — and requires it to resolve to a directory inside the workspace root, so a linked directory lists like its target; `changes` confines the watched directory the same way. File operations then resolve and read through the composed filesystem without an additional workspace-containment check. The configured page, window, complete-file, and listing caps still apply. Text pages additionally reject invalid UTF-8 and NUL bytes; byte reads do not decode content. An empty read or listing path is a `gateway/bad-request`. +Every path-taking operation first uses `lstat` to reject a missing path or the wrong file kind; the file-reading operations also refuse a final symlink, even one pointing back inside the workspace. `list` instead follows a final link — a directory symlink on any platform, including a Windows junction — and requires it to resolve to a directory inside the workspace root, so a linked directory lists like its target; `changes` confines the watched directory the same way. File operations then resolve and read through the composed filesystem without an additional workspace-containment check. The configured page, window, complete-file, and listing caps still apply. Text pages additionally reject invalid UTF-8 and NUL bytes; byte reads do not decode content. An empty read or listing path is a `gateway/bad-request`. + + +### Search + +`search` trims `query` and refuses an empty result as `gateway/bad-request`. Queries without `/` match names; queries with `/` match `/`-joined workspace-relative paths. Both use case-insensitive substring matching. Matches include files and deduplicated ancestor directories inferred from those files; empty directories are absent. An `excludedPaths` value without `/` excludes that name at every depth; a value with `/` excludes the exact path rooted at the workspace. Glob metacharacters are literal. With `includeHidden` false, hidden files and directories are skipped; VCS metadata is always excluded. + +`respectGitignore` uses native ripgrep ignore rules, including its repository detection, nested and parent `.gitignore`, `.git/info/exclude`, global Git excludes and `.ignore`. Disabling it passes `--no-ignore`. The service does not parse Git configuration or apply `core.ignorecase` to ignore matching. `maxFileBytes` does not bound ignore files; read failures follow rg exit semantics. + +Each call obtains `subprocess` on demand and runs packaged `rg --files --sort=path`. It considers at most `search.maxEntries` listed files, sorts matches from that bounded set by depth then path, and keeps `search.maxResults`; extra matches set `truncated`. An additional file record detects overflow without contributing matches. Exceeding the file cap terminates rg and sets `incomplete`; rg exit 2 also returns partial results, while exit 1 means no results. File and directory links are neither returned nor followed. Cancellation reaches the subprocess and rejects with the signal reason after cleanup. Missing subprocess, launch/execution failure and timeout all fail with `workspace-file/search-failed`, with the cause explained in the message; no JS traversal fallback exists, and other file operations remain available. ### The change feed @@ -65,6 +75,11 @@ Every operation first uses `lstat` to reject a missing path or the wrong file ki | `maxFileBytes` | `33554432` (32 MiB) | Inclusive complete-file cap for `readBytes` without `range`; larger files fail with `too-large` | | `maxLines` | `5000` | Default and largest page size in lines; a larger `limit` is refused | | `maxEntries` | `2000` | Cap on returned directory entries; the rest is dropped and reported cut | +| `search.maxResults` | `512` | Returned match cap; additional matches set `truncated` | +| `search.maxEntries` | `100000` | Cap on files considered from rg output; an extra file terminates the process and sets `incomplete` | +| `search.graceMs` | `3000` | Process termination grace in milliseconds | +| `search.timeoutMs` | `30000` | Search deadline in milliseconds; expiry rejects | +| `search.stderrMaxBytes` | `65536` | Retained process stderr diagnostic byte cap | The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-api-workspace-files) is the exhaustive source for every accepted field and its JSDoc. @@ -100,7 +115,8 @@ Complete-file reads delegate size enforcement to `fs.readBytes` and return raw b | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | `WorkspaceFiles`: the `workspaceFiles` service and Remote namespace, `Config`, the gates, the page cutter, `read`, `readBytes`, `stat`, `list` | +| [`src/index.ts`](src/index.ts) | `WorkspaceFiles`: the `workspaceFiles` service and Remote namespace, `Config`, the gates, the page cutter, `read`, `readBytes`, `stat`, `list`, `search` | +| [`src/search.ts`](src/search.ts) | rg arguments, file-ancestor inference, sorting and bounded search | | [`src/changes.ts`](src/changes.ts) | `WorkspaceChangeFeed`: target watchers, matching `fs/observed` notifications, and one queue per generation | | [`src/types.ts`](src/types.ts) | Wire types and the `RemoteErrorDetailsMap` codes, published as `./types` for Client packages | | [`src/client/index.ts`](src/client/index.ts), [`provider.ts`](src/client/provider.ts), [`change-feed.ts`](src/client/change-feed.ts) | Browser plugin, file metadata, and per-target change feeds | @@ -145,6 +161,7 @@ None; this package neither assembles nor sends a provider request. - **Reads are not transactional** — result metadata comes from stat before content is read; a concurrent write can make the reported version and returned contents differ. - **Unbounded generation queue** — a `changes` generation buffers operation observations and target invalidations until its consumer pulls; a stalled consumer grows Host memory for the life of the stream. - **`maxEntries` bounds the answer, not the listing** — `list` asks `ctx.fs.listDir` for every child and cuts the array afterwards, so a directory far above the cap still costs the Host the whole listing (on `fs-local`, one stat per child); bounding that work needs a limit on the filesystem seam's `listDir`. +- **Search execution world** — each search starts rg without an index. The subprocess provider must execute the Host-packaged binary and share the filesystem workspace; otherwise search fails, including SSH profiles missing that path. The path prefix read before the file cap can omit shallower matches; `incomplete` reports that limitation. - **Dead feeds retain metadata** — after the Host ends `changes` or the stream fails terminally, open values retain their last state until reopened. diff --git a/packages/api/workspace-files/README.zh.md b/packages/api/workspace-files/README.zh.md index e1f0e0000d..938fe8ba9d 100644 --- a/packages/api/workspace-files/README.zh.md +++ b/packages/api/workspace-files/README.zh.md @@ -1,5 +1,5 @@ --- -description: "面向 Web GUI 的工作区文件服务:有界文件读取、按目标监听文件系统变化,以及 Session 工作区根内的目录列举。" +description: "面向 Web GUI 的工作区文件服务:有界文件读取、按目标监听文件系统变化,以及 Session 工作区根内的目录列举与按名称或路径搜索。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -使用本包可从 Web Client 预览 Session 文件系统允许读取的文件。它按页读取 UTF-8 文本、按有界窗口或完整文件读取原始字节、从基文件目录解析关联文件,并报告文件元数据。可以跟随一个文件或一个目录直接子项的变化。文件读取和监听可以指向工作区外路径;目录列举和监听仍限定于工作区。本服务不提供修改操作。 +使用本包可从 Web Client 预览 Session 文件系统允许读取的文件。它按页读取 UTF-8 文本、按有界窗口或完整文件读取原始字节、从基文件目录解析关联文件,并报告文件元数据。可以跟随一个文件或一个目录直接子项的变化。可以按名称或相对路径搜索工作区条目。文件读取和监听可以指向工作区外路径;目录列举、搜索和目录监听仍限定于工作区。本服务不提供修改操作。 ## 目录 @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 读取 live Session header,cold Session 则使用持久层 `stat`;它不会激活 Agent、读取事件正文或借用父 Session 的根。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 +把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)`、`search(sessionId, request, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 读取 live Session header,cold Session 则使用持久层 `stat`;它不会激活 Agent、读取事件正文或借用父 Session 的根。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 | 方法 | 返回 | 用途 | |---|---|---| @@ -33,6 +33,7 @@ kind: "package-reference" | `read(path, { offset?, limit? })` | `WorkspaceFileText` = stat + `{ offset, text, lines, eof }` | UTF-8 文本文件的一个行窗口;`lines` 计行数,使单个空行与越过文件末尾的页可区分 | | `readBytes(path, { range?, baseFile? })` | `WorkspaceFileBytes` = stat + `{ offset, data, eof }` | 以 `Uint8Array` 返回完整文件或有界字节范围;可从另一个文件所在目录解析目标 | | `list(path)` | `WorkspaceDirectoryListing { path, entries, truncated }` | 一个目录的直接子项 | +| `search({ query, excludedPaths, includeHidden, respectGitignore })` | `WorkspaceFileSearchResult { matches, truncated, incomplete }` | 工作区任意位置中名称或相对路径包含查询的条目 | | `changes(path)` | `WorkspaceFileWatchFrame` 流 | 订阅就绪确认,随后为单个文件或目录直接子项的失效通知 | ### 寻址与路径 @@ -51,7 +52,16 @@ kind: "package-reference" ### 文件读取与目录检查 -每项操作都先通过 `lstat` 拒绝不存在的路径或错误的文件类型;读取文件的操作还拒绝末端符号链接,包括指回工作区内的链接。`list` 改为跟随末端链接——任何平台上的目录符号链接,包括 Windows 目录联接——要求它解析为工作区内的目录,因此被链接的目录与其目标一样可列举;`changes` 也以同样方式把被监听的目录限制在工作区内。文件操作随后通过组合文件系统解析和读取,不做额外的工作区包含检查。配置的分页、窗口、完整文件和目录列举上限仍然适用。文本页还拒绝无效 UTF-8 与 NUL 字节;字节读取不解码内容。读取或列举的空路径是 `gateway/bad-request`。 +每个带路径的操作都先通过 `lstat` 拒绝不存在的路径或错误的文件类型;读取文件的操作还拒绝末端符号链接,包括指回工作区内的链接。`list` 改为跟随末端链接——任何平台上的目录符号链接,包括 Windows 目录联接——要求它解析为工作区内的目录,因此被链接的目录与其目标一样可列举;`changes` 也以同样方式把被监听的目录限制在工作区内。文件操作随后通过组合文件系统解析和读取,不做额外的工作区包含检查。配置的分页、窗口、完整文件和目录列举上限仍然适用。文本页还拒绝无效 UTF-8 与 NUL 字节;字节读取不解码内容。读取或列举的空路径是 `gateway/bad-request`。 + + +### 搜索 + +`search` 对 `query` 做 trim,结果为空时以 `gateway/bad-request` 拒绝。不含 `/` 的查询按名称匹配,含 `/` 的查询按以 `/` 连接的工作区相对路径匹配;两者都为不区分大小写的子串匹配。匹配包含文件与从文件推导并去重的祖先目录;空目录不出现。`excludedPaths` 不含 `/` 的值按任意深度的名称排除,含 `/` 的值只排除根下的精确相对路径;所有 glob 元字符均按字面处理。`includeHidden` 为 false 时跳过隐藏文件与目录;VCS 元数据始终排除。 + +`respectGitignore` 使用 ripgrep 原生忽略规则,包括其仓库检测、嵌套与祖先 `.gitignore`、`.git/info/exclude`、全局 Git 排除文件及 `.ignore`。关闭时传入 `--no-ignore`。本服务不解析 Git 配置,也不把 `core.ignorecase` 用于忽略匹配。`maxFileBytes` 不限制忽略文件;读取错误沿用 rg 的退出语义。 + +每次调用通过按需获取的 `subprocess` 运行打包的 `rg --files --sort=path`。最多处理 rg 列出的 `search.maxEntries` 个文件,在此有界文件集内按深度与路径排序并截到 `search.maxResults`;匹配数超过结果上限时置 `truncated`。额外的一条文件记录只用于检测超限,不贡献匹配。超过文件数上限会终止 rg 并置 `incomplete`,rg 退出码 2 同样表示部分结果;退出码 1 表示无结果。链接文件与目录均不返回,也不跟随。取消信号传给子进程,调用等待进程清理后以 signal 的 reason 拒绝。缺少 subprocess、启动或执行失败以及超时均以 `workspace-file/search-failed` 失败,消息说明具体原因;不回退到 JS 遍历,其他文件操作不受影响。 ### 变更流 @@ -65,6 +75,11 @@ kind: "package-reference" | `maxFileBytes` | `33554432`(32 MiB) | `readBytes` 未传 `range` 时的完整文件字节上限(含);更大文件以 `too-large` 失败 | | `maxLines` | `5000` | 页大小的缺省值与上限(行);更大的 `limit` 被拒绝 | | `maxEntries` | `2000` | 返回目录条目数上限;其余丢弃并报告截断 | +| `search.maxResults` | `512` | 返回匹配数上限;更多匹配置 `truncated` | +| `search.maxEntries` | `100000` | 处理 rg 输出的文件数上限;发现额外文件时终止进程并置 `incomplete` | +| `search.graceMs` | `3000` | 进程终止宽限期(毫秒) | +| `search.timeoutMs` | `30000` | 搜索截止时间(毫秒);到期拒绝调用 | +| `search.stderrMaxBytes` | `65536` | 子进程 stderr 诊断保留字节上限 | 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-api-workspace-files)是每个可接受字段及其 JSDoc 的完备来源。 @@ -100,7 +115,8 @@ kind: "package-reference" | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | `WorkspaceFiles`:`workspaceFiles` 服务与 Remote 命名空间、`Config`、四道关、切页器、`read`、`readBytes`、`stat`、`list` | +| [`src/index.ts`](src/index.ts) | `WorkspaceFiles`:`workspaceFiles` 服务与 Remote 命名空间、`Config`、四道关、切页器、`read`、`readBytes`、`stat`、`list`、`search` | +| [`src/search.ts`](src/search.ts) | rg 参数、文件祖先推导、排序与有界搜索 | | [`src/changes.ts`](src/changes.ts) | `WorkspaceChangeFeed`:目标监听、匹配的 `fs/observed` 通知与每代流各自的队列 | | [`src/types.ts`](src/types.ts) | 线路类型与 `RemoteErrorDetailsMap` 错误码,以 `./types` 发布给 Client 包 | | [`src/client/index.ts`](src/client/index.ts)、[`provider.ts`](src/client/provider.ts)、[`change-feed.ts`](src/client/change-feed.ts) | 浏览器插件、文件元数据与按目标建立的变更流 | @@ -145,6 +161,7 @@ Typert 生成 `./typert` 与 `./remote` 暴露的 Host 与 Client Remote 产物 - **读取不具备事务性**——结果元数据来自内容读取之前的 stat;并发写入可能使报告版本与返回内容不一致。 - **generation 队列无界**——一个 `changes` generation 会缓冲操作观察与目标失效通知直到消费方 pull;停滞的消费方会在流的生命期内持续增长 Host 内存。 - **`maxEntries` 限制的是答案,不是列举**——`list` 让 `ctx.fs.listDir` 列出全部子项后再截断数组,远超上限的目录仍让 Host 付出整个列举的代价(`fs-local` 上每个子项一次 stat);要限制这份工作,需要文件系统 seam 的 `listDir` 支持上限。 +- **搜索执行环境**——每次搜索重新运行 rg,不维护索引。子进程提供方必须能执行 Host 打包的二进制,并与文件系统共享工作区;不满足时搜索失败,包括缺少该路径的 SSH 配置。文件数上限前的路径前缀可能漏掉较浅的匹配;`incomplete` 明确报告这种不完整性。 - **失效流保留元数据**——Host 结束 `changes` 或流终态失败后,已打开的值保持最后已知状态,直到重新打开。 diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index 5e39822c0a..0c501b990a 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -56,7 +56,8 @@ "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "zod": "4.6.6" + "zod": "4.6.6", + "@deepseek-ai/dsh-util-ripgrep": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" @@ -73,7 +74,9 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-persistence": "workspace:*", - "@deepseek-ai/dsh-util-workspace-path": "workspace:*" + "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/api/workspace-files/src/index.ts b/packages/api/workspace-files/src/index.ts index d6ecbc68c1..66b25581f3 100644 --- a/packages/api/workspace-files/src/index.ts +++ b/packages/api/workspace-files/src/index.ts @@ -1,13 +1,14 @@ /** * Workspace file service: read-only file previews, workspace directory - * listings, and the filesystem-observation change feed, exposed as - * `workspaceFiles`. + * listings, workspace-wide name and path search, and the + * filesystem-observation change feed, exposed as `workspaceFiles`. * * File reads follow the composed filesystem's read access, including paths * outside the workspace. The selected Session header supplies the base for * relative paths, with the sandbox policy root as its no-cwd fallback, not a - * read-containment restriction. Directory listings and change observations - * remain workspace-scoped. File-kind checks and configured read caps apply to + * read-containment restriction. Directory listings, searches, and change + * observations remain workspace-scoped; a search reports workspace-relative + * paths. File-kind checks and configured read caps apply to * every preview; this service exposes no mutations. * * A page is cut from `streamText`, which decodes and rejects non-UTF-8 as it @@ -30,6 +31,7 @@ import type {} from '@deepseek-ai/dsh-session-persistence' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { Remote, RemoteError, TypertRemoteService, type TypertLookup } from '@deepseek-ai/dsh-typert-protocol' import { WorkspaceChangeFeed } from './changes.ts' +import { searchWorkspace, type SearchLimits } from './search.ts' import type { WorkspaceByteRange, WorkspaceByteReadOptions, @@ -37,6 +39,8 @@ import type { WorkspaceDirectoryListing, WorkspaceFileBytes, WorkspaceFileRange, + WorkspaceFileSearchRequest, + WorkspaceFileSearchResult, WorkspaceFileStat, WorkspaceFileText, WorkspaceFileWatchFrame, @@ -66,7 +70,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { } } -/** 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. @@ -82,6 +86,8 @@ 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 } /** One page cut from a decoded text stream. */ @@ -188,13 +194,20 @@ export class WorkspaceFiles extends TypertRemoteService { maxFileBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER - 1).default(32 * 1024 * 1024), maxLines: z.number().step(1).min(1).default(5000), maxEntries: z.number().step(1).min(1).default(2000), + search: z.object({ + maxResults: z.number().step(1).min(1).default(512), + maxEntries: z.number().step(1).min(1).default(100000), + graceMs: z.number().step(1).min(1).max(2147483647).default(3000), + timeoutMs: z.number().step(1).min(1).max(2147483647).default(30000), + stderrMaxBytes: z.number().step(1).min(1).default(65536), + }), }) private readonly feed: WorkspaceChangeFeed /** * @param ctx - Host context carrying the filesystem and the sandbox policy. - * @param config - deployment caps on one page or one listing. + * @param config - deployment caps on one page, one listing, or one search. */ constructor(ctx: Context, private readonly config: Config) { super(ctx, 'workspaceFiles') @@ -328,6 +341,52 @@ export class WorkspaceFiles extends TypertRemoteService { } } + /** + * Search files and their inferred ancestor directories with packaged ripgrep. + * Native ignore rules apply unless disabled; VCS metadata, symlinks and empty + * directories are absent. Within the bounded set of listed files, matches + * sort by depth, then workspace-relative path. + * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. + * @param request - the query, literal exclusions, and hidden/ignore switches. + * @param signal - caller cancellation, forwarded to the subprocess; rejection preserves its reason. + * @returns matches capped by search.maxResults; incomplete marks excess rg files or exit 2. + * @throws RemoteError `gateway/bad-request`: the query is blank. + * @throws RemoteError `workspace-file/not-found`: the workspace root does not exist. + * @throws RemoteError `workspace-file/not-directory`: the workspace root is not a directory. + * @throws RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out. + */ + @Remote + async search( + workspaceFileScope: WorkspaceFileScope, + request: WorkspaceFileSearchRequest, + signal: AbortSignal, + ): Promise { + const query = request.query.trim() + if (query.length === 0) throw new RemoteError('gateway/bad-request', 'query must not be blank', {}) + signal.throwIfAborted() + const { workspaceRoot } = workspaceFileScope + const root = await this.ctx.fs.resolve(workspaceRoot, { signal }) + const info = await this.ctx.fs.stat(root, signal) + if (info === undefined) { + throw new RemoteError('workspace-file/not-found', `no entry at "${workspaceRoot}"`, { path: workspaceRoot }) + } + if (info.type !== 'directory') { + throw new RemoteError('workspace-file/not-directory', `"${workspaceRoot}" is a ${info.type}`, { path: workspaceRoot, kind: info.type }) + } + const subprocess = this.ctx.get('subprocess') + if (subprocess === undefined) { + throw new RemoteError('workspace-file/search-failed', 'Workspace file search requires a subprocess provider', {}) + } + return searchWorkspace(subprocess, { + cwd: this.ctx.fs.processPath(root), + query, + excludedPaths: request.excludedPaths, + includeHidden: request.includeHidden, + respectGitignore: request.respectGitignore, + ...this.config.search, + }, signal) + } + /** * Watch one file or a directory's direct entries in the Session's filesystem. * Files use the backend's read authority; directories remain workspace-scoped. diff --git a/packages/api/workspace-files/src/search.ts b/packages/api/workspace-files/src/search.ts new file mode 100644 index 0000000000..d1a316a001 --- /dev/null +++ b/packages/api/workspace-files/src/search.ts @@ -0,0 +1,124 @@ +/** Workspace-relative name and path discovery through packaged ripgrep. */ +import { readRipgrepLines, spawnRipgrep, type RipgrepLinesResult } from '@deepseek-ai/dsh-util-ripgrep' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import type { WorkspaceFileSearchMatch, WorkspaceFileSearchResult } from './types.ts' + +/** 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 +} + +/** Resolved inputs of one search; the caller validates the root and trims the query. */ +export interface SearchSpec extends SearchLimits { + /** Canonical workspace root in the subprocess execution world. */ + readonly cwd: string + /** Non-empty query without surrounding whitespace. */ + readonly query: string + /** Literal names at any depth, or exact root-relative paths when containing `/`. */ + readonly excludedPaths: readonly string[] + /** Whether hidden files and directories may participate. */ + readonly includeHidden: boolean + /** Whether ripgrep's native ignore rules apply. */ + readonly respectGitignore: boolean +} + +/** VCS metadata never contributes files or inferred directories. */ +const VCS_NAMES = ['.git', '.svn', '.hg', '.bzr', '.jj', '.sl'] + +/** Quote names as literal rg glob components, not patterns. */ +function exclusion(path: string): string { + const literal = path.replace(/[\\*?\[\]{}!]/g, '\\$&') + return `--glob=!${path.includes('/') ? '/' : ''}${literal}` +} + +/** + * Match names, or relative paths for queries containing `/`, without case. + * Directories derive only from listed files; empty directories and links are + * absent. Results sort by depth, then path, after scanning the bounded file set. + * Native ignore handling and read failures belong to rg: exit 2 reports partial + * results; launch and other execution failures reject with a RemoteError. + * @param subprocess - the composed process spawner, co-located with the filesystem. + * @param spec - validated root, query, filters and process budgets. + * @param signal - cancellation; rejection preserves its exact reason. + * @returns bounded shallow-first matches and independent truncation/incompleteness flags. + */ +export async function searchWorkspace( + subprocess: Pick, + spec: SearchSpec, + signal: AbortSignal, +): Promise { + const timeout = new AbortController() + const timer = setTimeout(() => { + timeout.abort(new RemoteError('workspace-file/search-failed', 'Workspace file search timed out; narrow the workspace or increase search.timeoutMs', {})) + }, spec.timeoutMs) + const combined = AbortSignal.any([signal, timeout.signal]) + const needle = spec.query.toLowerCase() + const byPath = spec.query.includes('/') + const entries = new Map() + const admit = (path: string, type: WorkspaceFileSearchMatch['type']): void => { + const name = path.slice(path.lastIndexOf('/') + 1) + if ((byPath ? path : name).toLowerCase().includes(needle)) entries.set(path, { path, type }) + } + try { + combined.throwIfAborted() + let run: RipgrepLinesResult + let stderr = '' + try { + const handle = await spawnRipgrep(subprocess, { + argv: [ + '--files', '--sort=path', '--null', '--path-separator=/', + ...spec.includeHidden ? ['--hidden'] : [], + ...spec.respectGitignore ? [] : ['--no-ignore'], + ...[...VCS_NAMES, ...spec.excludedPaths].map(exclusion), + ], + cwd: spec.cwd, + stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: spec.stderrMaxBytes } }, + graceMs: spec.graceMs, + signal: combined, + }) + let listed = 0 + run = await readRipgrepLines(handle, '\0', (path) => { + if (listed === spec.maxEntries) return false + admit(path, 'file') + let end = path.lastIndexOf('/') + while (end !== -1) { + admit(path.slice(0, end), 'directory') + end = path.lastIndexOf('/', end - 1) + } + listed += 1 + return true + }) + stderr = handle.collected.stderr?.readFrom(0).text.trim() ?? '' + } catch (cause: unknown) { + signal.throwIfAborted() + timeout.signal.throwIfAborted() + throw new RemoteError('workspace-file/search-failed', 'Could not launch or read workspace file search; the subprocess provider must be able to execute the packaged ripgrep binary', {}, { cause }) + } + const { outcome, stopped } = run + combined.throwIfAborted() + if (!stopped && (outcome.signal !== null || (outcome.exitCode !== 0 && outcome.exitCode !== 1 && outcome.exitCode !== 2))) { + throw new RemoteError('workspace-file/search-failed', `Workspace file search exited with code ${outcome.exitCode} and signal ${outcome.signal}; check the subprocess provider${stderr.length > 0 ? `: ${stderr}` : ''}`, {}) + } + const matches = [...entries.values()].sort((a, b) => { + const depth = a.path.split('/').length - b.path.split('/').length + return depth || (a.path < b.path ? -1 : 1) + }) + return { + matches: matches.slice(0, spec.maxResults), + truncated: matches.length > spec.maxResults, + incomplete: stopped || outcome.exitCode === 2, + } + } finally { + clearTimeout(timer) + } +} diff --git a/packages/api/workspace-files/src/types.ts b/packages/api/workspace-files/src/types.ts index ea6bc2c086..987324435d 100644 --- a/packages/api/workspace-files/src/types.ts +++ b/packages/api/workspace-files/src/types.ts @@ -10,6 +10,9 @@ * same path. * - `list` speaks workspace paths — the same syntax its `path` argument accepts — * because its consumer is a tree rooted at the workspace root. + * - `search` reports `/`-joined workspace-relative paths, and its query and + * exclusions use the same relative syntax, because its consumer is the same + * workspace tree. * * @module @deepseek-ai/dsh-api-workspace-files/types */ @@ -122,6 +125,56 @@ export interface WorkspaceDirectoryListing { readonly truncated: boolean } +/** One workspace-wide search by entry name or workspace-relative path. */ +export interface WorkspaceFileSearchRequest { + /** + * Case-insensitive substring to find. Surrounding whitespace is trimmed, and + * an empty result is refused. Without `/` it matches entry names; with `/` it + * matches `/`-joined workspace-relative paths. + */ + readonly query: string + /** + * Literal exclusions passed as escaped rg globs. A value without `/` excludes + * that name at any depth; a value with `/` excludes the exact path rooted at + * the workspace. Glob metacharacters in names are not interpreted as patterns. + */ + readonly excludedPaths: readonly string[] + /** Whether rg includes hidden files and directories; VCS metadata remains excluded. */ + readonly includeHidden: boolean + /** + * Whether native rg ignore rules apply, including repository detection, + * nested and parent `.gitignore`, `.git/info/exclude`, global Git excludes + * and `.ignore`. The service does not read `core.ignorecase`; false passes + * `--no-ignore`. + */ + readonly respectGitignore: boolean +} + +/** One entry a workspace search found. */ +export interface WorkspaceFileSearchMatch { + /** `/`-joined path relative to the workspace root, never empty. */ + readonly path: string + /** What the entry resolves to, as {@link WorkspaceDirectoryEntry.type} reports it. */ + readonly type: WorkspaceDirectoryEntry['type'] +} + +/** The outcome of one workspace search. */ +export interface WorkspaceFileSearchResult { + /** + * Matching files and inferred ancestor directories from the bounded set of + * listed files, sorted by depth then workspace-relative path and cut to the + * configured result cap. + */ + readonly matches: readonly WorkspaceFileSearchMatch[] + /** Whether matches exceeded the result cap after scanning the bounded file set. */ + readonly truncated: boolean + /** + * Whether rg listed more files than the file cap and was terminated early, + * or exited with code 2 to report partial discovery. + */ + readonly incomplete: boolean +} + /** * Current target metadata after a filesystem invalidation. File consumers may * ignore an already known version; directory consumers relist on every frame @@ -152,6 +205,8 @@ export type WorkspaceFileWatchFrame = declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { + /** Search cannot run: missing subprocess, launch/execution failure, or configured timeout. */ + 'workspace-file/search-failed': Record /** The filesystem provider cannot initialize a watch for this target. */ 'workspace-file/watch-unsupported': { readonly path: string } /** No entry exists at that path inside the workspace. */ diff --git a/packages/api/workspace-files/tests/binary-rpc.spec.ts b/packages/api/workspace-files/tests/binary-rpc.spec.ts index dc42bfbe02..40ce2472be 100644 --- a/packages/api/workspace-files/tests/binary-rpc.spec.ts +++ b/packages/api/workspace-files/tests/binary-rpc.spec.ts @@ -23,7 +23,13 @@ beforeEach(async () => { await ctx.plugin(RemoteAccessService) await ctx.plugin(TypertGateway) await ctx.plugin((scope) => { new HostConnectionService(scope, [], {} as BrowserAuth) }) - await ctx.plugin(WorkspaceFiles, { maxBytes: 8, maxFileBytes: 4, maxLines: 100, maxEntries: 100 }) + await ctx.plugin(WorkspaceFiles, { + maxBytes: 8, + maxFileBytes: 4, + maxLines: 100, + maxEntries: 100, + search: { maxResults: 100, maxEntries: 1000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, + }) ctx.sessions.create(harness.scope.sessionId, { meta: { cwd: harness.workspace, origin: 'subagent' } }) const connection = ctx.get('connection') as HostConnectionService const handler = connection.createSharedFetchHandler('/api') diff --git a/packages/api/workspace-files/tests/changes.spec.ts b/packages/api/workspace-files/tests/changes.spec.ts index 687951e45c..c79423893b 100644 --- a/packages/api/workspace-files/tests/changes.spec.ts +++ b/packages/api/workspace-files/tests/changes.spec.ts @@ -72,7 +72,13 @@ async function ready(stream: ReturnType): Promise { async function ownedEndpoint() { let service: WorkspaceFiles | undefined const fiber = await harness.ctx.plugin(Object.assign((ctx: Context) => { - service = new WorkspaceFiles(ctx, { maxBytes: 1024, maxFileBytes: 1024, maxLines: 10, maxEntries: 10 }) + service = new WorkspaceFiles(ctx, { + maxBytes: 1024, + maxFileBytes: 1024, + maxLines: 10, + maxEntries: 10, + search: { maxResults: 100, maxEntries: 1000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, + }) }, { inject: ['fs', 'sandboxPolicy'] })) cleanups.push(() => fiber.dispose()) if (service === undefined) throw new Error('plugin body did not run') diff --git a/packages/api/workspace-files/tests/harness.ts b/packages/api/workspace-files/tests/harness.ts index cbb73c8c9d..9ee138be34 100644 --- a/packages/api/workspace-files/tests/harness.ts +++ b/packages/api/workspace-files/tests/harness.ts @@ -24,6 +24,9 @@ function fileScope(workspaceRoot: string): WorkspaceFileScope { export const signal = (): AbortSignal => new AbortController().signal +/** Per-test service caps; omitted read, list and search fields keep the suite defaults. */ +export type Caps = Partial> & { readonly search?: Partial } + /** One temp workspace and the context serving it. */ export interface Harness { readonly workspace: string @@ -34,7 +37,7 @@ export interface Harness { * The service under test, at the given caps. One per test: the service key is * global to the Context, so a second call with caps is a defect in the test. */ - endpoint(caps?: Partial): WorkspaceFiles + endpoint(caps?: Caps): WorkspaceFiles dispose(): Promise } @@ -72,6 +75,13 @@ export async function openWorkspace(prefix: string): Promise { maxFileBytes: caps?.maxFileBytes ?? 1024 * 1024, maxLines: caps?.maxLines ?? 5000, maxEntries: caps?.maxEntries ?? 2000, + search: { + maxResults: caps?.search?.maxResults ?? 512, + maxEntries: caps?.search?.maxEntries ?? 100000, + graceMs: caps?.search?.graceMs ?? 3000, + timeoutMs: caps?.search?.timeoutMs ?? 30000, + stderrMaxBytes: caps?.search?.stderrMaxBytes ?? 65536, + }, }) return service }, diff --git a/packages/api/workspace-files/tests/scope.spec.ts b/packages/api/workspace-files/tests/scope.spec.ts index d954063bfd..3f6f4338c5 100644 --- a/packages/api/workspace-files/tests/scope.spec.ts +++ b/packages/api/workspace-files/tests/scope.spec.ts @@ -10,6 +10,7 @@ const CAPS = { maxFileBytes: 1024, maxLines: 100, maxEntries: 100, + search: { maxResults: 100, maxEntries: 1000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, } function header(id: SessionId, cwd?: string): SessionHeader { diff --git a/packages/api/workspace-files/tests/search-harness.ts b/packages/api/workspace-files/tests/search-harness.ts new file mode 100644 index 0000000000..e940d7b63f --- /dev/null +++ b/packages/api/workspace-files/tests/search-harness.ts @@ -0,0 +1,18 @@ +/** Local subprocess fixture with private Git configuration, without mutating process.env. */ +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import type { Harness } from './harness.ts' + +/** Mount rg's real process provider with a per-test home for native global ignore rules. */ +export async function mountSearchSubprocess(harness: Harness): Promise { + const home = join(harness.outside, 'home') + await mkdir(home) + await harness.ctx.plugin(LocalSubprocessRuntime) + const spawn = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + harness.ctx.subprocess.spawn = spec => spawn({ + ...spec, + env: { HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: home, ...spec.env }, + }) + return home +} diff --git a/packages/api/workspace-files/tests/search-rg.spec.ts b/packages/api/workspace-files/tests/search-rg.spec.ts new file mode 100644 index 0000000000..290971dd2b --- /dev/null +++ b/packages/api/workspace-files/tests/search-rg.spec.ts @@ -0,0 +1,258 @@ +/** Process failures, budgets and lossless literal path filters over real ripgrep. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { chmod, mkdir, realpath, symlink, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { PassThrough } from 'node:stream' +import { mountSearchSubprocess } from './search-harness.ts' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import { WorkspaceFiles, type Config, type WorkspaceFileSearchRequest } from '../src/index.ts' +import { failureOf, openWorkspace, signal, type Caps, type Harness } from './harness.ts' + +let harness: Harness +beforeEach(async () => { + harness = await openWorkspace('dsh-workspace-search-rg-') +}) +afterEach(async () => { + vi.restoreAllMocks() + await harness.ctx.fiber.dispose() + await harness.dispose() +}) +async function files(...paths: string[]): Promise { + for (const path of paths) { + const absolute = join(harness.workspace, path) + await mkdir(dirname(absolute), { recursive: true }) + await writeFile(absolute, '') + } +} +const request = (query: string, options: Partial = {}): WorkspaceFileSearchRequest => ({ + query, includeHidden: true, respectGitignore: false, excludedPaths: [], ...options, +}) +const search = (query: string, caps?: Caps, options?: Partial, abort = signal()) => + harness.endpoint(caps).search(harness.scope, request(query, options), abort) + +describe('ripgrep-backed workspace discovery', () => { + beforeEach(async () => { await mountSearchSubprocess(harness) }) + + it('sorts shallow matches before path-sorted deep files and truncates only matching results', async () => { + await files('a-match/deep-match/file-match', 'z-match', 'b-match') + expect(await search('match', { search: { maxResults: 3 } })).toEqual({ matches: [ + { path: 'a-match', type: 'directory' }, { path: 'b-match', type: 'file' }, { path: 'z-match', type: 'file' }, + ], truncated: true, incomplete: false }) + }) + + it('sorts full paths independently of rg directory visitation order', async () => { + await files('a/file', 'a-file/file') + expect((await search('file')).matches.map(match => match.path)).toEqual(['a-file', 'a-file/file', 'a/file']) + }) + + it('does not truncate at exactly the result cap', async () => { + await files('a1', 'a2') + expect(await search('a', { search: { maxResults: 2 } })).toMatchObject({ truncated: false, incomplete: false }) + }) + + it.each([2, 3])('reports incompleteness only when %s files exceed the two-file cap', async (total) => { + await files(...Array.from({ length: total }, (_, i) => i < 2 ? `a${i}` : `z-a/a${i}`)) + const original = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + const terminate = vi.fn() + const waitForExit = vi.fn() + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation((spec) => { + const handle = original(spec) + return { ...handle, + terminate: () => { terminate(); handle.terminate() }, + waitForExit: async () => { waitForExit(); return handle.waitForExit() }, + } + }) + expect(await search('a', { search: { maxEntries: 2 } })).toEqual({ matches: [ + { path: 'a0', type: 'file' }, { path: 'a1', type: 'file' }, + ], truncated: false, incomplete: total > 2 }) + expect(terminate).toHaveBeenCalledTimes(total > 2 ? 1 : 0) + expect(waitForExit).toHaveBeenCalledOnce() + }) + + it('uses native hidden/ignore switches, path sorting, lossless separators and no ambient config', async () => { + const spawn = vi.spyOn(harness.ctx.subprocess, 'spawn') + await search('absent') + expect(spawn.mock.calls[0]?.[0]).toMatchObject({ cwd: await realpath(harness.workspace), graceMs: 3000 }) + expect(spawn.mock.calls[0]?.[0].argv).toEqual(expect.arrayContaining([ + '--no-config', '--files', '--sort=path', '--null', '--path-separator=/', '--hidden', '--no-ignore', + ])) + expect(spawn.mock.calls[0]?.[0].argv[1]).toBe('--no-config') + }) + + it.each(['.git', '.svn', '.hg', '.bzr', '.jj', '.sl'])('excludes %s internals even with hidden and ignored files enabled', async (vcs) => { + await files(`${vcs}/a.txt`, `sub/${vcs}/a.txt`, 'a.txt') + expect((await search('a.txt')).matches).toEqual([{ path: 'a.txt', type: 'file' }]) + expect((await search(vcs)).matches).toEqual([]) + }) + + it.each(['[x]', '{x,y}', '!x'])('quotes the portable glob metacharacters in %s literally', async (name) => { + await files(`${name}/target`, `sub/${name}/target`, 'x/target', 'y/target') + expect((await search('target', undefined, { excludedPaths: [name] })).matches.map(m => m.path)).toEqual(['x/target', 'y/target']) + expect((await search('target', undefined, { excludedPaths: [`sub/${name}`] })).matches.map(m => m.path)).toEqual([`${name}/target`, 'x/target', 'y/target'].sort()) + }) + + it.skipIf(process.platform === 'win32')('quotes star, question mark and backslash names and preserves embedded newlines', async () => { + // Windows does not permit these literal filename characters. + await files('a*/target', 'a?/target', 'a\\b/target', 'ax/target', 'new\nline/target') + expect((await search('target', undefined, { excludedPaths: ['a*', 'a?', 'a\\b'] })).matches.map(m => m.path)).toEqual(['ax/target', 'new\nline/target']) + }) + + it('does not return empty directories or directory links inside/outside the root', async () => { + await files('real/target') + await mkdir(join(harness.workspace, 'empty')) + await writeFile(join(harness.outside, 'outside-target'), '') + await symlink(join(harness.workspace, 'real'), join(harness.workspace, 'linked'), 'junction') + await symlink(harness.outside, join(harness.workspace, 'outside-link'), 'junction') + expect((await search('link')).matches).toEqual([]) + expect((await search('empty')).matches).toEqual([]) + expect((await search('target')).matches).toEqual([{ path: 'real/target', type: 'file' }]) + }) + + it.skipIf(process.platform === 'win32')('omits regular and broken file symlinks', async () => { + // File symlinks on Windows require privileges absent from some test hosts. + await files('target') + await symlink(join(harness.workspace, 'target'), join(harness.workspace, 'file-link')) + await symlink(join(harness.workspace, 'missing'), join(harness.workspace, 'broken-link')) + expect((await search('link')).matches).toEqual([]) + }) + + it('keeps git ignore repository detection and does not interpret core.ignorecase', async () => { + await files('SECRET.txt') + await writeFile(join(harness.workspace, '.gitignore'), 'SECRET.txt\n') + expect((await search('secret', undefined, { respectGitignore: true })).matches).toHaveLength(1) + await mkdir(join(harness.workspace, '.git')) + expect((await search('secret', undefined, { respectGitignore: true })).matches).toEqual([]) + await writeFile(join(harness.workspace, '.gitignore'), 'secret.txt\n') + await writeFile(join(harness.workspace, '.git', 'config'), '[core]\nignorecase = true\n') + expect((await search('secret', undefined, { respectGitignore: true })).matches).toHaveLength(1) + }) + + it('honors the private home global Git exclude file', async () => { + const home = join(harness.outside, 'home') + await mkdir(join(harness.workspace, '.git')) + await writeFile(join(home, '.gitconfig'), '[core]\nexcludesFile = ~/.global-ignore\n') + await writeFile(join(home, '.global-ignore'), 'global.txt\n') + await files('global.txt', 'keep.txt') + expect((await search('.txt', undefined, { respectGitignore: true })).matches).toEqual([{ path: 'keep.txt', type: 'file' }]) + expect((await search('global.txt')).matches).toEqual([{ path: 'global.txt', type: 'file' }]) + }) + + it('honors parent .gitignore and .ignore without disabling native defaults', async () => { + await mkdir(join(dirname(harness.workspace), '.git')) + await writeFile(join(dirname(harness.workspace), '.gitignore'), 'parent.txt\n') + await writeFile(join(harness.workspace, '.ignore'), 'dot.txt\n') + await files('parent.txt', 'dot.txt', 'keep.txt') + expect((await search('.txt', undefined, { respectGitignore: true })).matches).toEqual([{ path: 'keep.txt', type: 'file' }]) + }) + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('returns actual rg exit-2 partial results for an unreadable directory', async () => { + // POSIX permissions cannot deny reads to root and have no Windows equivalent. + await files('a.txt', 'blocked/a.txt') + const blocked = join(harness.workspace, 'blocked') + await chmod(blocked, 0) + try { + expect(await search('a.txt')).toEqual({ matches: [{ path: 'a.txt', type: 'file' }], truncated: false, incomplete: true }) + } finally { + await chmod(blocked, 0o700) + } + }) + + it('reports synchronous and asynchronous launch failures with a stable Remote code', async () => { + const spawn = vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation(() => { throw new Error('remote executable missing') }) + expect((await failureOf(search('a'))).code).toBe('workspace-file/search-failed') + spawn.mockRestore() + const original = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation(spec => original({ ...spec, argv: [join(harness.workspace, 'missing-rg')] })) + expect((await failureOf(search('a'))).code).toBe('workspace-file/search-failed') + }) + + it.each([ + { exitCode: 2, signal: null }, { exitCode: 3, signal: null }, { exitCode: null, signal: 'SIGTERM' }, { exitCode: null, signal: null }, + ] satisfies SubprocessOutcome[])('classifies exit facts %j independently from retained paths', async (outcome) => { + await files('a.txt') + const original = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation((spec) => { + const handle = original(spec) + return { ...handle, done: handle.done.then(() => outcome) } + }) + if (outcome.exitCode === 2) expect(await search('a')).toEqual({ matches: [{ path: 'a.txt', type: 'file' }], truncated: false, incomplete: true }) + else expect((await failureOf(search('a'))).code).toBe('workspace-file/search-failed') + }) + + it('includes the configured bounded stderr excerpt in execution failures', async () => { + const original = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation((spec) => { + const handle = original({ ...spec, argv: [...spec.argv, '--unknown-search-flag'] }) + return { ...handle, done: handle.done.then(() => ({ exitCode: 3, signal: null })) } + }) + const pending = search('a', { search: { stderrMaxBytes: 65536 } }) + await expect(pending).rejects.toMatchObject({ code: 'workspace-file/search-failed' }) + await expect(pending).rejects.toThrow('unknown-search-flag') + }) + + it('preserves cancellation before start and after real stdout arrives', async () => { + const aborted = new AbortController() + const reason = new Error('cancel search') + aborted.abort(reason) + await expect(search('a', undefined, undefined, aborted.signal)).rejects.toBe(reason) + await files('a.txt') + const active = new AbortController() + const original = harness.ctx.subprocess.spawn.bind(harness.ctx.subprocess) + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation((spec) => { + const handle = original(spec) + handle.stdout!.once('data', () => { active.abort(reason) }) + return handle + }) + await expect(search('a', undefined, undefined, active.signal)).rejects.toBe(reason) + }) + + it('enforces the configured deadline and waits for process cleanup', async () => { + const exited = vi.fn(async () => true) + vi.spyOn(harness.ctx.subprocess, 'spawn').mockImplementation((spec) => { + const stdout = new PassThrough() + let finish!: (outcome: SubprocessOutcome) => void + const done = new Promise((resolve) => { finish = resolve }) + const terminate = () => { stdout.end(); finish({ exitCode: null, signal: 'SIGTERM' }) } + spec.signal!.addEventListener('abort', terminate, { once: true }) + return { stdout, stdin: undefined, stderr: undefined, control: undefined, + collected: {}, done, terminate, waitForExit: exited } satisfies SubprocessHandle + }) + expect((await failureOf(search('a', { search: { timeoutMs: 1 } }))).code).toBe('workspace-file/search-failed') + expect(exited).toHaveBeenCalledOnce() + }) +}) + +it('fails only search when subprocess is absent; reads and listings remain usable', async () => { + await files('a.txt') + expect((await failureOf(search('a'))).code).toBe('workspace-file/search-failed') + expect((await harness.endpoint().list(harness.scope, '.', signal())).entries).toHaveLength(1) + expect((await harness.endpoint().read(harness.scope, 'a.txt', {}, signal())).text).toBe('') +}) + +/** Parse loader input, which may omit any defaulted field, including the whole `search` group. */ +const parseConfig = (input: object): Config => new WorkspaceFiles.Config(input as Config) + +it('validates subprocess budgets and supplies defaults', () => { + const defaults = new WorkspaceFiles.Config() + expect(defaults.search).toMatchObject({ graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }) + for (const name of ['graceMs', 'timeoutMs', 'stderrMaxBytes']) { + expect(() => parseConfig({ search: { ...defaults.search, [name]: 0 } })).toThrow() + expect(() => parseConfig({ search: { ...defaults.search, [name]: 1.5 } })).toThrow() + } + expect(() => parseConfig({ search: { ...defaults.search, timeoutMs: 2147483648 } })).toThrow() +}) + +it('fills every search default when the search group is omitted', () => { + expect(parseConfig({ maxEntries: 7 })).toEqual({ + maxBytes: 2 * 1024 * 1024, + maxFileBytes: 32 * 1024 * 1024, + maxLines: 5000, + maxEntries: 7, + search: { maxResults: 512, maxEntries: 100000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, + }) +}) + +it('fills the remaining search defaults when the search group is partial', () => { + expect(parseConfig({ search: { maxResults: 3, timeoutMs: 10 } }).search) + .toEqual({ maxResults: 3, maxEntries: 100000, graceMs: 3000, timeoutMs: 10, stderrMaxBytes: 65536 }) +}) diff --git a/packages/api/workspace-files/tests/search.spec.ts b/packages/api/workspace-files/tests/search.spec.ts new file mode 100644 index 0000000000..64a6d25ac1 --- /dev/null +++ b/packages/api/workspace-files/tests/search.spec.ts @@ -0,0 +1,144 @@ +/** The `search` endpoint: matching, filters, ignore files, caps, failures, cancellation, and links. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { mountSearchSubprocess } from './search-harness.ts' +import type { WorkspaceFileSearchRequest, WorkspaceFileSearchResult } from '../src/index.ts' +import { failureOf, openWorkspace, signal, type Caps, type Harness } from './harness.ts' + +let harness: Harness +let workspace: string + +beforeEach(async () => { + harness = await openWorkspace('dsh-workspace-files-search-') + await mountSearchSubprocess(harness) + workspace = harness.workspace +}) + +afterEach(async () => { + vi.restoreAllMocks() + await harness.ctx.fiber.dispose() + await harness.dispose() +}) + +/** Create empty files, and their parent directories, at workspace-relative paths. */ +async function files(...paths: string[]): Promise { + for (const path of paths) { + await mkdir(dirname(join(workspace, path)), { recursive: true }) + await writeFile(join(workspace, path), '', 'utf8') + } +} + +/** Write one text file at a workspace-relative path. */ +async function text(path: string, content: string | Uint8Array): Promise { + await mkdir(dirname(join(workspace, path)), { recursive: true }) + await writeFile(join(workspace, path), content) +} + +const search = ( + query: string, + options: Partial> = {}, + caps?: Caps, + abort: AbortSignal = signal(), +): Promise => + harness.endpoint(caps).search(harness.scope, { + query, + excludedPaths: options.excludedPaths ?? [], + includeHidden: options.includeHidden ?? false, + respectGitignore: options.respectGitignore ?? false, + }, abort) + +const pathsOf = (result: WorkspaceFileSearchResult): string[] => result.matches.map(match => match.path) + +describe('workspaceFiles.search — matching', () => { + it('matches entry names case-insensitively, shallower levels first, with each type', async () => { + await files('src/deep/Button.tsx', 'BUTTON.md', 'notes.txt') + await files('src/button-group/a', 'src/button-group/b') + await mkdir(join(workspace, 'empty-button')) + const result = await search(' button ') + expect(result).toEqual({ + matches: [ + { path: 'BUTTON.md', type: 'file' }, + { path: 'src/button-group', type: 'directory' }, + { path: 'src/deep/Button.tsx', type: 'file' }, + ], + truncated: false, + incomplete: false, + }) + }) + + it('matches workspace-relative paths case-insensitively when the query holds a slash', async () => { + await files('src/app/main.ts', 'lib/src/app.ts', 'other/main.ts') + const result = await search('SRC/APP') + expect(pathsOf(result)).toEqual(['src/app', 'lib/src/app.ts', 'src/app/main.ts']) + }) + + it('refuses a blank query as a bad request', async () => { + const failure = await failureOf(search(' \t ')) + expect(failure.code).toBe('gateway/bad-request') + }) + + it('reports a missing workspace root as not found and a file root as not a directory', async () => { + await files('root-file') + const service = harness.endpoint() + const request = { query: 'a', excludedPaths: [], includeHidden: false, respectGitignore: false } + const missing = await failureOf(service.search({ ...harness.scope, workspaceRoot: join(workspace, 'gone') }, request, signal())) + expect(missing.code).toBe('workspace-file/not-found') + const file = await failureOf(service.search({ ...harness.scope, workspaceRoot: join(workspace, 'root-file') }, request, signal())) + expect(file).toMatchObject({ code: 'workspace-file/not-directory', details: { kind: 'file' } }) + }) +}) + +describe('workspaceFiles.search — exclusions and hidden entries', () => { + it('excludes a name at every depth without entering it', async () => { + await files('node_modules/pkg/index.ts', 'app/node_modules/dep/index.ts', 'app/index.ts') + const result = await search('index', { excludedPaths: ['node_modules'] }) + expect(pathsOf(result)).toEqual(['app/index.ts']) + }) + + it('excludes one exact relative path without entering it', async () => { + await files('a/b/target.txt', 'c/a/b/target.txt', 'a/target.txt') + const result = await search('target', { excludedPaths: ['a/b'] }) + expect(pathsOf(result)).toEqual(['a/target.txt', 'c/a/b/target.txt']) + expect(pathsOf(await search('b', { excludedPaths: ['a/b'] }))).toEqual(['c/a/b']) + }) + + it('leaves hidden entries out and unentered unless they are included', async () => { + await files('.env', '.config/env.ts', 'env.md') + expect(pathsOf(await search('env'))).toEqual(['env.md']) + expect(pathsOf(await search('env', { includeHidden: true }))).toEqual(['.env', 'env.md', '.config/env.ts']) + }) +}) + +describe('workspaceFiles.search — ignore files', () => { + beforeEach(async () => { + await text('.gitignore', '*.log\n!keep.log\nbuild/\n') + await text('sub/.gitignore', 'secret.txt\n!sub-keep.log\n') + await text('.git/info/exclude', 'excluded.txt\n') + await files( + 'debug.log', 'keep.log', 'secret.txt', 'excluded.txt', + 'sub/secret.txt', 'sub/sub-keep.log', 'sub/other.log', + 'other/secret.txt', 'out/build/target.txt', 'tools/build', + ) + }) + + it('applies nested .gitignore files to their own subtree, with negation and directory-only patterns', async () => { + const result = await search('.', { respectGitignore: true }) + expect(pathsOf(result)).toEqual(['keep.log', 'secret.txt', 'other/secret.txt', 'sub/sub-keep.log']) + expect(result.incomplete).toBe(false) + expect(pathsOf(await search('build', { respectGitignore: true }))).toEqual(['tools/build']) + expect(pathsOf(await search('target', { respectGitignore: true }))).toEqual([]) + }) + + it('applies the root .git/info/exclude', async () => { + expect(pathsOf(await search('excluded', { respectGitignore: true }))).toEqual([]) + }) + + it('applies no ignore file when ignore files are not respected', async () => { + const result = await search('.', {}) + expect(pathsOf(result)).toEqual([ + 'debug.log', 'excluded.txt', 'keep.log', 'secret.txt', + 'other/secret.txt', 'sub/other.log', 'sub/secret.txt', 'sub/sub-keep.log', 'out/build/target.txt', + ]) + }) +}) diff --git a/packages/api/workspace-files/tsconfig.host.json b/packages/api/workspace-files/tsconfig.host.json index 3bf11f5177..572cac209c 100644 --- a/packages/api/workspace-files/tsconfig.host.json +++ b/packages/api/workspace-files/tsconfig.host.json @@ -8,7 +8,8 @@ "files": [ "src/index.ts", "src/types.ts", - "src/changes.ts" + "src/changes.ts", + "src/search.ts" ], "references": [ { @@ -34,6 +35,12 @@ }, { "path": "../../util/deque" + }, + { + "path": "../../util/ripgrep" + }, + { + "path": "../../subprocess/subprocess" } ] } diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index 5a187dc4ac..d27fec562e 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: c4a9acdb98de091d - zh: 417d8bafe75157ec + en: 9dba73eeabe9887f + zh: 19291d764da21077 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 483285658e267dd5 zh: 846bec2daac59a96 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index cccb096c15..3418cd519b 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -41,7 +41,7 @@ A plugin toggle updates only `disabled` in the last matching override in the pro Bundle platform declarations are checked before saving an enabled selection. Unsupported Hosts return `unsupported-platform`. The bundle remains visible with its display metadata and can still be deselected. Automatic activation after a package operation uses the same check. The agent-facing next step asks the user to run the bundle on a supported Host. -`listBundles` retains default-hidden bundles and derives `listedByDefault` from each package’s visibility declaration and Host platform support. Unsupported bundles are hidden from default GUI lists, including More; explicit profile dependencies and saved selections remain manageable with the platform reason and deselection available. The offline Official catalog carries the same package-owned platform declaration, so uninstalled entries are checked without resolving provider code or querying a registry. These checks do not change selection or activation. A non-boolean declaration returns a metadata diagnostic. A selected bundle that cannot load remains in `listBundles` with an `error`; `enabled` records the saved selection, not successful loading. The plugin page shows the error and allows deselection. A broken bundle cannot be enabled. Management bundles remain protected if their files become unreadable. +`listBundles` retains default-hidden bundles and derives `listedByDefault` from each package’s visibility declaration and Host platform support. Unsupported bundles are hidden from default GUI lists, including More; explicit profile dependencies and saved selections remain manageable with the platform reason and deselection available. The offline Official catalog carries the same package-owned platform declaration, so uninstalled entries are checked without resolving provider code or querying a registry. These checks do not change selection or activation. A non-boolean declaration returns a metadata diagnostic, because the launcher does not read it. A selected bundle that cannot load remains in `listBundles` with an `error` and no row carrying an `entryId`; `enabled` records the saved selection, not successful loading. The plugin page marks it as not running and allows deselection. A broken bundle cannot be enabled. Management bundles remain protected if their files become unreadable. `listBundles` includes optional display `meta` for each bundle and its declared plugin rows, including disabled bundles. The Client selects a language from these values. The separate `description` field is the bundle's raw `package.json.description`; a metadata diagnostic does not block management. `source` gives a profile dependency as a spec `pnpm add` accepts: a git address or URL as recorded without the user information of an http(s) URL (a query string stays as recorded), a `file:` or `link:` path made absolute against the profile or the home directory for `~`, and a registry range, tag, or alias after the package name, as is any spec of a package installed under another name; a bundle the installation supplies has none, even when the profile also depends on it, because the installation's copy is the one that loads. The `plugin_manager` tool omits UI display metadata and update eligibility from list results. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index cfc0c99f3a..8cc04bb296 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference" 组合包的平台声明会在保存启用选择前检查。Host 不受支持时返回 `unsupported-platform`。组合包仍保留显示信息,并允许取消选择。包操作后的自动启用执行同一检查。给模型的下一步说明会提示用户在受支持的 Host 上运行该组合包。 -`listBundles` 保留默认隐藏的组合包,根据各包的展示声明和 Host 平台支持范围生成 `listedByDefault`。不支持的组合包默认不出现在主列表或“更多”中;profile 显式安装的依赖和已保存的选择仍可管理,显示平台原因并允许关闭。官方离线目录携带同一份包级平台声明,因此无需解析提供方代码或查询注册表,也能检查未安装的条目。这些检查不改变选择或激活状态。声明不是布尔值时返回元数据诊断。已选择但无法加载的组合包仍会出现在 `listBundles` 中,并携带 `error`;`enabled` 表示保存的选择,不代表加载成功。插件页面显示错误并允许取消选择。损坏的组合包无法启用。管理组合包的文件变得不可读后仍受保护。 +`listBundles` 保留默认隐藏的组合包,根据各包的展示声明和 Host 平台支持范围生成 `listedByDefault`。不支持的组合包默认不出现在主列表或“更多”中;profile 显式安装的依赖和已保存的选择仍可管理,显示平台原因并允许关闭。官方离线目录携带同一份包级平台声明,因此无需解析提供方代码或查询注册表,也能检查未安装的条目。这些检查不改变选择或激活状态。声明不是布尔值时返回元数据诊断,因为启动器不读取该声明。已选择但无法加载的组合包仍会出现在 `listBundles` 中,携带 `error`,且没有带 `entryId` 的行;`enabled` 表示保存的选择,不代表加载成功。插件页面将其标记为未运行,并允许取消选择。损坏的组合包无法启用。管理组合包的文件变得不可读后仍受保护。 `listBundles` 为各组合包及其声明的插件行提供可选的展示 `meta`,包括已禁用的组合包。Client 从这些值中选择语言。单独的 `description` 字段是该组合包原始的 `package.json.description`;元信息诊断不会阻止管理操作。`source` 以 `pnpm add` 接受的 spec 给出 profile 依赖:git 地址或 URL 按记录给出,但去掉 http(s) URL 的 user information(查询字符串保持原样);`file:` 或 `link:` 路径按 profile 目录解析为绝对路径,`~` 展开为主目录;注册表版本范围、标签或别名接在包名的 `@` 之后,以别名安装的包的 spec 也是如此。安装提供的组合包没有该字段,即使 profile 也依赖它,因为实际加载的是安装中的副本。`plugin_manager` 工具的列表结果不包含 UI 展示元信息和更新资格。 diff --git a/packages/boot/plugin-manager/src/index.ts b/packages/boot/plugin-manager/src/index.ts index 86a0f57ca1..a2cdc5e01a 100644 --- a/packages/boot/plugin-manager/src/index.ts +++ b/packages/boot/plugin-manager/src/index.ts @@ -561,14 +561,18 @@ export class PluginManager extends TypertRemoteService { } version = info.version const listedByDefault = info.dsh?.bundle?.listedByDefault - if (listedByDefault !== undefined) { - if (typeof listedByDefault !== 'boolean') throw new Error('dsh.bundle.listedByDefault must be a boolean') - listing = { listedByDefault } - } + // The launcher ignores this display field, so an invalid value is a metadata diagnostic, not a load error. + const listingDiagnostic = listedByDefault === undefined || typeof listedByDefault === 'boolean' + ? undefined + : 'dsh.bundle.listedByDefault must be a boolean' + if (typeof listedByDefault === 'boolean') listing = { listedByDefault } const compatibility = evaluatePluginCompatibility(info, exemptions) if (compatibility !== undefined && !compatibility.exempted) throw new ManagementFailure('incompatible-version', [incompatiblePlugin(compatibility)]) const dir = resolveBundleDir('dsh', name, this.profile.installAnchor, this.profile.dir) - const meta = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href) + const read: BundleInfo['meta'] = offered?.meta ?? readPluginMeta(info.name ?? name, pathToFileURL(join(dir, 'package.json')).href) + const meta = listingDiagnostic === undefined + ? read + : { ...read, error: read?.error === undefined ? listingDiagnostic : `${read.error}; ${listingDiagnostic}` } let platformError: ManagementError | undefined try { assertBundlePlatform(info.dsh?.bundle?.platforms, process.platform) } catch (error) { platformError = managementError(error) } diff --git a/packages/boot/plugin-manager/src/types.ts b/packages/boot/plugin-manager/src/types.ts index f7655644b6..7181461421 100644 --- a/packages/boot/plugin-manager/src/types.ts +++ b/packages/boot/plugin-manager/src/types.ts @@ -85,7 +85,10 @@ export interface BundleInfo { description?: string /** Default GUI visibility after package and Host checks; selected or profile-installed bundles remain manageable. */ listedByDefault?: boolean - /** Selected in the profile manifest; a load error means its layer was skipped. */ + /** + * Selected in the profile manifest; a selected bundle whose layer was skipped carries the load `error`, and none of + * its `rows` has an `entryId`. + */ enabled: boolean /** Whether the profile declares this dependency; availability separately reports whether its files can be read. */ installed: boolean diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index ae71a3db8f..efe840989a 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -470,8 +470,16 @@ it('projects each bundle\'s default GUI listing without changing its selection, } manifest.dsh.bundle.listedByDefault = 'hidden' writeFileSync(path, JSON.stringify(manifest)) - expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({ enabled: true, - error: { diagnostic: 'dsh.bundle.listedByDefault must be a boolean' } }) + // The launcher ignores the field, so an invalid value is a metadata diagnostic beside the running layer's live row. + const invalid = (await manager.listBundles()).find(row => row.name === 'extra') + expect(invalid).toMatchObject({ enabled: true, meta: { error: 'dsh.bundle.listedByDefault must be a boolean' }, + rows: [{ rowId: 'managed', entryId: 'include:managed' }] }) + expect(invalid?.error).toBeUndefined() + expect(invalid?.listedByDefault).toBeUndefined() + // An unreadable icon keeps its own diagnostic beside the listing one. + writeFileSync(path, JSON.stringify({ ...manifest, icon: 'missing.svg' })) + expect((await manager.listBundles()).find(row => row.name === 'extra')?.meta?.error) + .toMatch(/^Plugin metadata for extra: .+; dsh\.bundle\.listedByDefault must be a boolean$/) }) it('names where each installed bundle comes from as a spec pnpm installs', async () => { diff --git a/packages/bundle/base/README.i18n.yaml b/packages/bundle/base/README.i18n.yaml index b475ce9b82..bd859ea112 100644 --- a/packages/bundle/base/README.i18n.yaml +++ b/packages/bundle/base/README.i18n.yaml @@ -21,8 +21,8 @@ en: 0f971f7ac7c09139 zh: ceb866da681c709c /deepseek-ai-dsh-base/use-this-package/what-you-get: - en: ab2fb279cdd726c5 - zh: ae84c61bddc00ddf + en: dd7e69c32d06cb6a + zh: 9301140a8e023b41 /deepseek-ai-dsh-base/use-this-package/shell-tools-per-platform: en: 2dce12f82d6ee955 zh: d4599eb899a3cd88 diff --git a/packages/bundle/base/README.md b/packages/bundle/base/README.md index 5b5f163694..b2ab5dcf1e 100644 --- a/packages/bundle/base/README.md +++ b/packages/bundle/base/README.md @@ -53,6 +53,8 @@ Both `subagent` and `subagent_fork` create managed children and return the child The bundle also mounts [Agent Teams](../../team/agent-team/README.md) and its task tools. Team mode defaults off per root Session; the root conversation’s **Use Agent Teams** menu switch enables collaboration for that tree without changing the profile. +The `tool-subagent-control` row sets `interrupt: false`, so ordinary subagents and Team mode omit `interrupt_agent`. Set `config.interrupt: true` on that row in a later patch to enable it. The plugin itself still defaults to `true`. + The built-in `working_directory` tool changes the directory for subsequent operations while existing processes and write permissions remain independent. Current directory information appears in user context. Default file editing uses `read`, `write`, and `edit`. The `str_replace_editor` tool remains available as an explicit opt-in. To add it to a base-backed profile, put this entry in the profile, home, or invocation patch: ```yaml diff --git a/packages/bundle/base/README.zh.md b/packages/bundle/base/README.zh.md index 62d6ad03b9..223b88bb0a 100644 --- a/packages/bundle/base/README.zh.md +++ b/packages/bundle/base/README.zh.md @@ -53,6 +53,8 @@ kind: "package-bundle" 此 bundle 还挂载 [Agent Teams](../../team/agent-team/README.zh.md) 及其任务工具。每个根 Session 的 Team 模式默认关闭;根会话菜单中的**使用智能体团队**开关为当前树开启协作,无需修改 profile。 +`tool-subagent-control` 行显式设置 `interrupt: false`,因此普通 subagent 和 Team 模式均不提供 `interrupt_agent`。在后续 patch 中为该行设置 `config.interrupt: true` 可启用它。插件自身的默认值仍为 `true`。 + 内置 `working_directory` 工具改变后续操作使用的目录,已有进程与写权限保持独立。当前目录信息出现在用户上下文中。默认文件编辑使用 `read`、`write` 和 `edit`。`str_replace_editor` 工具仍可显式启用。要将它加入基于 base 的 profile,请在 profile、home 或逐次调用 patch 中添加以下条目: ```yaml diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index d94f5cf2dd..18286618f9 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -118,7 +118,7 @@ name: '@deepseek-ai/dsh-authorization' - id: deepseek-account - name: '@deepseek-ai/dsh-deepseek-account-platform' + name: '@deepseek-ai/dsh-deepseek-account' config: desktopPlatform: !!js "ctx.get('profileContext')?.name === 'desktop' && ['darwin', 'win32'].includes(process.platform) ? process.platform : null" @@ -385,6 +385,8 @@ # separately loaded follow-up tool registers the one global `send_message`. - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index cba883cd57..4ab644e138 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -57,7 +57,7 @@ "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-config-editor": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", - "@deepseek-ai/dsh-deepseek-account-platform": "workspace:*", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", diff --git a/packages/bundle/headless/tests/terminal-failures.spec.ts b/packages/bundle/headless/tests/terminal-failures.spec.ts index c92f095334..959eebb401 100644 --- a/packages/bundle/headless/tests/terminal-failures.spec.ts +++ b/packages/bundle/headless/tests/terminal-failures.spec.ts @@ -7,7 +7,7 @@ import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { SessionId } from '@deepseek-ai/dsh-session' +import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' import { apply } from '../src/index.ts' import { internals } from '../src/runner-internals.ts' @@ -62,11 +62,10 @@ describe('headless terminal failures', () => { test.ctx.on('agent/error', ({ error }) => { failures.push(error) }) const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => { const append = parent.session.append.bind(parent.session) - const failAppend: typeof parent.session.append = (type, data, ...intent) => { + vi.spyOn(parent.session, 'append').mockImplementation((type, data, ...intent) => { if (type === failedEvent) throw new Error(`summary ${failedEvent} unavailable`) - return append(type, data, ...intent) - } - vi.spyOn(parent.session, 'append').mockImplementation(failAppend) + return Reflect.apply(append, undefined, [type, data, ...intent]) as SessionEvent + }) followup(parent) return Promise.resolve(true) }).mockResolvedValue(false) @@ -110,14 +109,13 @@ describe('headless terminal failures', () => { const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => { const append = parent.session.append.bind(parent.session) let failed = false - const failAppend: typeof parent.session.append = (type, data, ...intent) => { + vi.spyOn(parent.session, 'append').mockImplementation((type, data, ...intent) => { if (!failed && type === failedEvent) { failed = true throw new Error(`summary ${failedEvent} unavailable`) } - return append(type, data, ...intent) - } - vi.spyOn(parent.session, 'append').mockImplementation(failAppend) + return Reflect.apply(append, undefined, [type, data, ...intent]) as SessionEvent + }) followup(parent) return Promise.resolve(true) }).mockImplementationOnce((parent: Agent) => { diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 7a16271db2..1a650beec8 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -21,8 +21,8 @@ en: e3cac911f080d8ef zh: 60749e9f5c39c1bc /deepseek-ai-dsh-web-app/use-this-package/configuration: - en: b1787804544f2587 - zh: ce09d2c248ffd999 + en: f876c60a37e3cb0e + zh: 42a535554fe4bc40 /deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments: en: e6ddea1d2fc40501 zh: ff08b6fa3fc24136 @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: fdf38cb6e1b24464 - zh: c14a8bcac9d4e5cd + en: 1f16cd1737256729 + zh: 1d24cd133933ad9e /deepseek-ai-dsh-web-app/understand-the-implementation: en: cc4f6d02a4d11d58 zh: 276e0929502b4fca @@ -53,6 +53,30 @@ /deepseek-ai-dsh-web-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill: + en: 276322084b9659d1 + zh: 759aae367669520a +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/what-the-model-sees: + en: 120d7eb063f9d498 + zh: 4960aab0c5e89535 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/token-effect: + en: a639f2167f49dd3d + zh: 7b627d16829f1c75 +/deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/kv-cache-effect: + en: f4c47481baa2ab03 + zh: 31360e2558fca7f5 +/deepseek-ai-dsh-web-app/model-experience/creator-persona: + en: da4ec024b0def1bd + zh: 79dc1eae53f87aa5 +/deepseek-ai-dsh-web-app/model-experience/creator-persona/what-the-model-sees: + en: e0605965a933e81f + zh: 75473753ced8658b +/deepseek-ai-dsh-web-app/model-experience/creator-persona/token-effect: + en: ba18342fd9e04f77 + zh: 8d7a8af6f07becb0 +/deepseek-ai-dsh-web-app/model-experience/creator-persona/kv-cache-effect: + en: d0825b48e8703dcd + zh: 4afb139ba7da5bbe /deepseek-ai-dsh-web-app/model-experience/web-runtime-variable: en: 623bf8a0bf05599d zh: 398ded2e7b20c1ea diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index e2713f168b..aed6c22d91 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -61,6 +61,8 @@ The `minimal` agent preset uses a persistent shell, the `read_image` tool, and a The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-web-app) lists this runtime plugin's accepted fields and their JSDoc. The shipped composition inserts the `schedule` service row and the `ui-schedule` task page row, while the clock reading and the four reminder tools belong to the `standard`, `cordis`, and `ptc` presets. The `tool-subagent` and `tool-subagent-fork` rows in those presets deny the four tools, so a delegated child's scope never lists them. +The `standard`, `cordis`, and `ptc` presets set `config.interrupt: false` on their `tool-subagent-control` rows. To expose `interrupt_agent`, including in Team mode, override the relevant preset declaration as described in the [migration steps](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md); changing the disabled Host row does not change preset tools. + ### Listening, trust, and public deployments @@ -92,6 +94,10 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. +Standard and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. + +The packaged skill uses the custom skill root: a same-named project skill overrides it, and it overrides same-named user skills. One catalog entry wins without an error; see [skill-root priority](../../skill/skill-filesystem/README.md). + ----- @@ -150,6 +156,34 @@ Read these pages when you want to go deeper into the shared core, the browser re ## Model Experience +### DSH documentation skill + +#### What the model sees + +Standard and Creator list `dsh-doc` in the skill catalog. The `skill` tool loads its instructions and directs the agent to references for the current task. Other presets retain their own skill sources. Loading the skill does not modify workspace files or profile settings. + +#### Token effect + +The preset contributes one catalog entry. A session with no other skills also receives the catalog's shared invocation instructions. Skill bodies and reference files enter context only when loaded. + +#### KV Cache effect + +The catalog is logged at the first step and remains stable until its entries change. Loading the skill appends tool output without changing the tool schemas. + +### Creator persona + +#### What the model sees + +The Creator preset adds “You help the user customize DeepSeek Harness itself.” after the shared coding-agent sentence. Plugin implementation and authorization rules remain in the on-demand `dsh-doc` skill. + +#### Token effect + +One fixed sentence is added to Creator requests. Standard requests are unchanged. + +#### KV Cache effect + +The sentence is stable within the Creator preset; switching to a different preset changes the persona prefix. + ### Web runtime variable #### What the model sees diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 994400807e..80b1fd2216 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -61,6 +61,8 @@ dsh --profile web --no-open --port 8080 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-web-app)列出了本运行时插件接受的字段及其 JSDoc。随发行版交付的组合插入 `schedule` 服务行与 `ui-schedule` 任务页面行,时钟读数与四个提醒工具则属于 `standard`、`cordis` 与 `ptc` 三个 preset。这三个 preset 的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,因此被委派子 agent 的作用域不会列出它们。 +`standard`、`cordis` 和 `ptc` 三个 preset 在各自的 `tool-subagent-control` 行中设置 `config.interrupt: false`。如需提供 `interrupt_agent`(也适用于 Team 模式),按[迁移步骤](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md)覆盖相应 preset 声明;修改已禁用的 Host 行不会改变 preset 的工具。 + ### 监听、信任与公开部署 @@ -92,6 +94,10 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 +标准模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 + +打包的 skill 使用自定义 skill 根目录:同名的项目 skill 会覆盖打包的 skill,打包的 skill 又会覆盖同名的用户 skill。skill 目录中只保留优先级最高的一个条目,不会报错;参见 [skill 根目录优先级](../../skill/skill-filesystem/README.zh.md)。 + ----- @@ -150,6 +156,34 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 ## 模型体验 +### DSH 文档 skill + +#### 模型看到什么 + +标准模式和创造模式的 skill 目录都列出 `dsh-doc`。`skill` 工具加载其指令,并引导 agent 查阅当前任务所需的参考资料。其他 preset 保留各自的 skill 来源。加载该 skill 不会修改工作区文件或 profile 设置。 + +#### Token 影响 + +preset 提供一条目录项。没有其他 skill 的会话还会收到目录的通用调用说明。skill 正文和参考文件仅在加载时进入上下文。 + +#### KV Cache 影响 + +目录在第一个步骤写入日志,在条目改变前保持不变。加载 skill 会追加工具输出,不改变工具 schema。 + +### 创造模式角色设定 + +#### 模型看到什么 + +创造模式预设在共享的编码 Agent 描述句之后添加“You help the user customize DeepSeek Harness itself.”。插件实现和授权规则仍保留在按需加载的 `dsh-doc` skill 中。 + +#### Token 影响 + +创造模式请求增加一句固定文本。标准模式请求不变。 + +#### KV Cache 影响 + +该句在创造模式预设内保持稳定;切换到其他预设会改变角色设定前缀。 + ### Web 运行时变量 #### 模型看到什么 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 59b3473ba5..e842d8e3e1 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -140,8 +140,8 @@ - id: ui-settings-account name: '@deepseek-ai/dsh-client-ui-settings-account' - - id: account-controller - name: '@deepseek-ai/dsh-api-account-controller' + - id: ui-account-notifications + name: '@deepseek-ai/dsh-client-ui-account-notifications' - id: settings-controller name: '@deepseek-ai/dsh-api-settings-controller' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index dd4860c5c0..2858130d13 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -78,20 +78,23 @@ "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", + "@deepseek-ai/dsh-client-ui-account-notifications": "workspace:*", "@deepseek-ai/dsh-client-ui-agent-preset": "workspace:*", "@deepseek-ai/dsh-client-ui-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", "@deepseek-ai/dsh-client-ui-attachment": "workspace:*", "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", - "@deepseek-ai/dsh-message-quotes": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-commands": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-cordis": "workspace:*", "@deepseek-ai/dsh-client-ui-deliverables": "workspace:*", "@deepseek-ai/dsh-client-ui-directory-picker-browse": "workspace:*", "@deepseek-ai/dsh-client-ui-directory-picker-native": "workspace:*", "@deepseek-ai/dsh-client-ui-entry-customization": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", "@deepseek-ai/dsh-client-ui-goal": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-jobs": "workspace:*", @@ -155,6 +158,7 @@ "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-message-feedback": "workspace:*", + "@deepseek-ai/dsh-message-quotes": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-persona": "workspace:*", "@deepseek-ai/dsh-plan-mode": "workspace:*", @@ -198,19 +202,7 @@ "@deepseek-ai/dsh-workspace-changes": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "commander": "^15.0.0", - "open": "^11.0.2", - "@deepseek-ai/dsh-api-account-controller": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-ui-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-product-analytics": "workspace:*", - "@deepseek-ai/dsh-host-product-telemetry-otel": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*", - "@deepseek-ai/dsh-harness-dev-context": "workspace:*", - "@deepseek-ai/dsh-deliverable-file-references": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*" + "open": "^11.0.2" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index 0fc32e6248..912fb7d3ac 100644 --- a/packages/bundle/web-app/presets/cordis.patch.yml +++ b/packages/bundle/web-app/presets/cordis.patch.yml @@ -8,13 +8,13 @@ id: cordis order: 4 plugins: - # Same persona as `standard`: tool descriptions and the skill catalog carry - # the operating detail, and the dsh-doc skill owns the preset-authoring rules. + # The dsh-doc skill owns plugin implementation and authorization guidance. - id: persona name: '@deepseek-ai/dsh-persona' config: prefix: >- You are a coding agent powered by the {{model}} model. + You help the user customize DeepSeek Harness itself. - id: agent-instructions name: '@deepseek-ai/dsh-agent-instructions' config: @@ -90,6 +90,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 86ccc4f0ad..7a9329e5db 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -91,6 +91,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index a40aab5aa9..a3532d0f3a 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -39,6 +39,9 @@ name: '@deepseek-ai/dsh-tool-schedule' - id: skill-filesystem name: '@deepseek-ai/dsh-skill-filesystem' + config: + customSkillDirs: + - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills') - id: tool-skill name: '@deepseek-ai/dsh-tool-skill' - id: command-goal @@ -91,6 +94,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/client/locale/src/locales/de.ts b/packages/client/locale/src/locales/de.ts index cb0bb45579..dd88cf6fc4 100644 --- a/packages/client/locale/src/locales/de.ts +++ b/packages/client/locale/src/locales/de.ts @@ -33,8 +33,6 @@ export const de = { 'more': 'Mehr', 'collapse': 'Einklappen', 'expand': 'Ausklappen', - 'subtitle.expand': 'Beschreibung für {name} ausklappen', - 'subtitle.collapse': 'Beschreibung für {name} einklappen', 'back': 'Zurück', 'brand.localBuild': 'Lokaler DSH-Build', 'workspace.defaultName': 'Standardarbeitsbereich', diff --git a/packages/client/locale/src/locales/en.ts b/packages/client/locale/src/locales/en.ts index 47a03d69ef..b649bbc3dc 100644 --- a/packages/client/locale/src/locales/en.ts +++ b/packages/client/locale/src/locales/en.ts @@ -32,8 +32,6 @@ export const en = { 'more': 'More', 'collapse': 'Collapse', 'expand': 'Expand', - 'subtitle.expand': 'Expand description for {name}', - 'subtitle.collapse': 'Collapse description for {name}', 'back': 'Back', 'brand.localBuild': 'DSH Local Build', 'workspace.defaultName': 'Default workspace', diff --git a/packages/client/locale/src/locales/es.ts b/packages/client/locale/src/locales/es.ts index 4fba984885..7eb95374e1 100644 --- a/packages/client/locale/src/locales/es.ts +++ b/packages/client/locale/src/locales/es.ts @@ -33,8 +33,6 @@ export const es = { 'more': 'Más', 'collapse': 'Contraer', 'expand': 'Expandir', - 'subtitle.expand': 'Expandir la descripción de {name}', - 'subtitle.collapse': 'Contraer la descripción de {name}', 'back': 'Atrás', 'brand.localBuild': 'Compilación local de DSH', 'workspace.defaultName': 'Espacio de trabajo predeterminado', diff --git a/packages/client/locale/src/locales/fr.ts b/packages/client/locale/src/locales/fr.ts index f0e5030f41..c57f1a3b11 100644 --- a/packages/client/locale/src/locales/fr.ts +++ b/packages/client/locale/src/locales/fr.ts @@ -33,8 +33,6 @@ export const fr = { 'more': 'Plus', 'collapse': 'Réduire', 'expand': 'Développer', - 'subtitle.expand': 'Développer la description de {name}', - 'subtitle.collapse': 'Réduire la description de {name}', 'back': 'Retour', 'brand.localBuild': 'Version locale de DSH', 'workspace.defaultName': 'Espace de travail par défaut', diff --git a/packages/client/locale/src/locales/ja.ts b/packages/client/locale/src/locales/ja.ts index 2b70cbb156..1186838c31 100644 --- a/packages/client/locale/src/locales/ja.ts +++ b/packages/client/locale/src/locales/ja.ts @@ -33,8 +33,6 @@ export const ja = { 'more': 'その他', 'collapse': '折りたたむ', 'expand': '展開', - 'subtitle.expand': '{name} の説明を展開', - 'subtitle.collapse': '{name} の説明を折りたたむ', 'back': '戻る', 'brand.localBuild': 'DSHローカルビルド', 'workspace.defaultName': 'デフォルトワークスペース', diff --git a/packages/client/locale/src/locales/pt.ts b/packages/client/locale/src/locales/pt.ts index adf711152d..75cdb19c29 100644 --- a/packages/client/locale/src/locales/pt.ts +++ b/packages/client/locale/src/locales/pt.ts @@ -33,8 +33,6 @@ export const pt = { 'more': 'Mais', 'collapse': 'Recolher', 'expand': 'Expandir', - 'subtitle.expand': 'Expandir descrição de {name}', - 'subtitle.collapse': 'Recolher descrição de {name}', 'back': 'Voltar', 'brand.localBuild': 'Versão local do DSH', 'workspace.defaultName': 'Espaço de trabalho padrão', diff --git a/packages/client/locale/src/locales/ru.ts b/packages/client/locale/src/locales/ru.ts index e75620fe21..a8a6d829da 100644 --- a/packages/client/locale/src/locales/ru.ts +++ b/packages/client/locale/src/locales/ru.ts @@ -33,8 +33,6 @@ export const ru = { 'more': 'Ещё', 'collapse': 'Свернуть', 'expand': 'Развернуть', - 'subtitle.expand': 'Развернуть описание {name}', - 'subtitle.collapse': 'Свернуть описание {name}', 'back': 'Назад', 'brand.localBuild': 'Локальная сборка DSH', 'workspace.defaultName': 'Рабочая область по умолчанию', diff --git a/packages/client/locale/src/locales/zh.ts b/packages/client/locale/src/locales/zh.ts index 6350caae3c..11ff789b8a 100644 --- a/packages/client/locale/src/locales/zh.ts +++ b/packages/client/locale/src/locales/zh.ts @@ -30,8 +30,6 @@ export const zh = { 'more': '更多', 'collapse': '收起', 'expand': '展开', - 'subtitle.expand': '展开{name}的描述', - 'subtitle.collapse': '收起{name}的描述', 'back': '返回', 'brand.localBuild': 'DSH 本地构建', 'workspace.defaultName': '默认工作区', diff --git a/packages/client/ui-account-notifications/README.i18n.yaml b/packages/client/ui-account-notifications/README.i18n.yaml new file mode 100644 index 0000000000..1ce8f44b0d --- /dev/null +++ b/packages/client/ui-account-notifications/README.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-account-notifications/README.md +/: + en: 46ed0081fc307e5d + zh: d9ed06af27b3cb29 +/deepseek-ai-dsh-client-ui-account-notifications: + en: c8d24427c7fcd3aa + zh: 5c0cf16f36ae6165 +/deepseek-ai-dsh-client-ui-account-notifications/summary: + en: 46cf31a87b0b765c + zh: 04f6b33570b046f7 +/deepseek-ai-dsh-client-ui-account-notifications/table-of-contents: + en: af856ba79fe31b8e + zh: c9b0188689359236 +/deepseek-ai-dsh-client-ui-account-notifications/use-this-package: + en: c466836df88d4ae1 + zh: 036e859139daa51d +/deepseek-ai-dsh-client-ui-account-notifications/model-experience: + en: 5fed5504300020e6 + zh: efd8e7c32b699e7e +/deepseek-ai-dsh-client-ui-account-notifications/model-experience/kv-cache-effect: + en: ca3015e252db0114 + zh: fb634b5b32d09f37 +/deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work: + en: 0d59eea475321fd0 + zh: 1cf67a196e76b832 +/deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work/dev-note: + en: 64006edb418180b1 + zh: 12f7d7ab2cbccd43 diff --git a/packages/client/ui-account-notifications/README.md b/packages/client/ui-account-notifications/README.md new file mode 100644 index 0000000000..10a0eeaadb --- /dev/null +++ b/packages/client/ui-account-notifications/README.md @@ -0,0 +1,57 @@ +--- +description: "Display account notifications and refresh their localized content." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-account-notifications + +English | [中文](README.zh.md) + +## Summary + +Show server-authored account notifications beside the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) + + +## Use this package + +The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; the account menu supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports. + +Startup with a stored account, sign-in, and each Settings entry start a new polling cycle with an immediate request. `notificationPollIntervalMs` on the `ui-account-notifications` row supplies the initial delay, defaulting to 600,000 ms. A successful list response replaces it with `next_poll_after` seconds, including empty lists. The delay starts after the request settles; failures retain the latest delay, and restarting restores the configured initial value. Polling continues in the background. + +Account settings owns the sole account stream and exposes its current state and lifecycle events through `accountUi` and `account-ui/change`. Login-progress updates retain cards and polling. Credential replacement, disconnection, access revocation, sign-out, and plugin disposal clear cards, stop polling, and discard late replies. Notification requests do not wait for profile or avatar data. Notification state is not stored in the browser. + +Cards render inside the sidebar above the account launcher and below menus and dialogs without taking focus. Their width follows the expanded launcher up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences. + +Notifications wait for Desktop and model-credential onboarding to finish. Only the foreground card is interactive and reports `displayed`, once per mount after a painted frame while it intersects the viewport and the sidebar and document are visible. The Settings overlay does not exclude that frame. A displayed foreground card remains until close or expiry even when a later list omits it; waiting cards follow server order. + +Each card uses the server's plain-text title, body, and ordered primary or secondary buttons. Every non-dismiss action reports `cta_clicked` with the notification ID, executes immediately, and retains the card; the account action opens Account settings. Closing through the close button or a dismiss action reports only `dismissed` as the card is removed, before the next card moves into place. Closing before the first painted frame does not report `displayed`. Expiry and account cleanup do not report dismissal. Click reports contain no action ID or target. + +Each interaction is reported once without waiting or retrying; either boolean acknowledgement completes that attempt. A failed report logs a diagnostic without an account UI error or undoing the interaction. The server owns consumption: a later list may offer a closed card again. List failures keep the current cards. + +Switching language requests current cards through the content endpoint, including consumed cards, without another list query or display report. Content updates preserve card identity, order, and focus. Failed reads retain the previous text and log a diagnostic; replies for an older language, signed-out account, or closed card cannot restore stale content. + + +## Model Experience + +None, as notifications remain client presentation data and never enter model requests or Session logs. + +#### KV Cache effect + +No model request prefix changes. + +## Known Limitations and Deferred Work + + + +- Cards retain the existing expiry and foreground-retention behavior. Server copy is plain text; supported actions dismiss the card or open Account settings. Network failures keep current cards and resume on the next poll. + + +### Dev Note + +The package tests cover lifecycle ownership; the Web notification scenario checks the assembled account menu. diff --git a/packages/client/ui-account-notifications/README.zh.md b/packages/client/ui-account-notifications/README.zh.md new file mode 100644 index 0000000000..adbae8cac4 --- /dev/null +++ b/packages/client/ui-account-notifications/README.zh.md @@ -0,0 +1,57 @@ +--- +description: "展示账号通知并刷新本地化内容。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-account-notifications + +[English](README.md) | 中文 + +## 概述 + +在账号菜单旁展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。 + +## 目录 + +- [使用此包](#use-this-package) +- [模型体验](#model-experience) +- [已知限制与待办](#known-limitations-and-deferred-work) + + +## 使用此包 + +Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号菜单提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。 + +带有已存账号的启动、登录及每次进入设置页都会启动新一轮轮询,并立即请求。`ui-account-notifications` 行中的 `notificationPollIntervalMs` 提供初始间隔,默认 600,000 ms。成功的列表响应通过 `next_poll_after` 秒替换间隔,空列表也相同。从请求结束时开始计时;失败沿用最近间隔,重启轮询恢复配置的初始值。轮询在后台继续。 + +账号设置拥有唯一的账号流,通过 `accountUi` 和 `account-ui/change` 提供当前状态及生命周期事件。登录进度更新沿用卡片和轮询。凭据替换、断连、权限撤销、退出登录和插件卸载会清空卡片、停止轮询并丢弃迟到响应。通知请求不等待资料或头像。通知状态不写入浏览器存储。 + +卡片在侧栏内部、账号入口上方渲染,位于菜单和对话框之下,不抢占焦点。宽度跟随展开的账号入口,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。 + +通知等待 Desktop 和模型凭据引导完成。只有前排卡片可交互并上报 `displayed`:卡片与视口相交、侧栏和文档可见并完成一帧绘制后,同一次挂载只上报一次。设置蒙层不排除该帧。已展示的前排卡片保留至关闭或过期,即使后续列表不再返回它;待展示卡片遵循服务端顺序。 + +每张卡片使用服务端纯文本标题、正文和有序的主要或次要按钮。所有非 dismiss 操作都携带通知 ID 上报 `cta_clicked`,立即执行并保留卡片;账号操作会打开账号设置。通过关闭按钮或 dismiss 操作关闭时,在移除卡片、下一张开始补位前只上报 `dismissed`。首帧绘制前关闭不会补报 `displayed`。过期和账号清理不上报关闭。点击上报不携带 action ID 或 target。 + +每次交互只上报一次,不等待、不重试;任一布尔确认结果都会结束本次尝试。上报失败会记录诊断日志,不在账号界面报错,也不撤销交互。消费状态由服务端决定:后续列表可能再次返回已关闭的卡片。列表失败保留当前卡片。 + +切换语言通过内容接口请求当前卡片,支持已消费通知,不重新查询列表或上报展示。内容更新保留卡片身份、顺序和焦点。读取失败保留原文并记录诊断日志;旧语言、已退登账号或已关闭卡片的响应不会恢复过时内容。 + + +## 模型体验 + +无,通知属于客户端展示数据,不进入模型请求或 Session 日志。 + +#### KV 缓存影响 + +模型请求前缀不变。 + +## 已知限制与待办 + + + +- 卡片保留现有的过期与前排保留行为。服务端文案使用纯文本;支持的操作为关闭卡片或打开账号设置。网络失败保留当前卡片,并在下次轮询时继续。 + + +### 开发备注 + +包内测试覆盖生命周期所有权;Web 通知场景验证组合后的账号菜单。 diff --git a/packages/client/ui-account-notifications/locale/de.json b/packages/client/ui-account-notifications/locale/de.json new file mode 100644 index 0000000000..3584bba2da --- /dev/null +++ b/packages/client/ui-account-notifications/locale/de.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Kontobenachrichtigungen" + } +} diff --git a/packages/client/ui-account-notifications/locale/en.json b/packages/client/ui-account-notifications/locale/en.json new file mode 100644 index 0000000000..e2cad8bd35 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Account notifications" + } +} diff --git a/packages/client/ui-account-notifications/locale/es.json b/packages/client/ui-account-notifications/locale/es.json new file mode 100644 index 0000000000..ae797bfded --- /dev/null +++ b/packages/client/ui-account-notifications/locale/es.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notificaciones de la cuenta" + } +} diff --git a/packages/client/ui-account-notifications/locale/fr.json b/packages/client/ui-account-notifications/locale/fr.json new file mode 100644 index 0000000000..254e2e6fa3 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/fr.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notifications du compte" + } +} diff --git a/packages/client/ui-account-notifications/locale/ja.json b/packages/client/ui-account-notifications/locale/ja.json new file mode 100644 index 0000000000..8a82ef90bf --- /dev/null +++ b/packages/client/ui-account-notifications/locale/ja.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "アカウント通知" + } +} diff --git a/packages/client/ui-account-notifications/locale/pt.json b/packages/client/ui-account-notifications/locale/pt.json new file mode 100644 index 0000000000..19f27cc8e7 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/pt.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Notificações da conta" + } +} diff --git a/packages/client/ui-account-notifications/locale/ru.json b/packages/client/ui-account-notifications/locale/ru.json new file mode 100644 index 0000000000..743b8451dd --- /dev/null +++ b/packages/client/ui-account-notifications/locale/ru.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Уведомления аккаунта" + } +} diff --git a/packages/client/ui-account-notifications/locale/zh.json b/packages/client/ui-account-notifications/locale/zh.json new file mode 100644 index 0000000000..e8b0422500 --- /dev/null +++ b/packages/client/ui-account-notifications/locale/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "账号通知" + } +} diff --git a/packages/client/ui-account-notifications/package.json b/packages/client/ui-account-notifications/package.json new file mode 100644 index 0000000000..de3bd6aa8b --- /dev/null +++ b/packages/client/ui-account-notifications/package.json @@ -0,0 +1,74 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-account-notifications", + "description": "Display account notifications and refresh localized content", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-account-notifications" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-settings-account" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@testing-library/react": "^16.3.3", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + } +} diff --git a/packages/client/ui-settings-account/src/client/AccountNotice.module.css b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css similarity index 82% rename from packages/client/ui-settings-account/src/client/AccountNotice.module.css rename to packages/client/ui-account-notifications/src/client/AccountNotifications.module.css index 4ece2277fc..cd508405b9 100644 --- a/packages/client/ui-settings-account/src/client/AccountNotice.module.css +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.module.css @@ -1,11 +1,13 @@ /* Each deeper card is centered 4px above the preceding card and narrows by the - design's 272/280 ratio. The foreground alone determines the stack height. */ -.stack { position: fixed; z-index: 40; isolation: isolate; width: 280px; max-width: calc(100vw - 16px); } + design's 252/260 ratio. The foreground alone determines the stack height. */ +.stack { position: relative; isolation: isolate; width: 100%; max-width: 280px; } .card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; } .card[data-front="false"] { position: absolute; inset: 0; height: 100%; overflow: hidden; pointer-events: none; } @media (prefers-reduced-motion: reduce) { .card { transition: none; } } .copy { display: flex; flex-direction: column; gap: 2px; overflow-wrap: anywhere; } .copy p { margin: 0; white-space: pre-wrap; } +.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } +.action { max-width: 100%; height: auto; min-height: 28px; white-space: normal; overflow-wrap: anywhere; } .title { display: flex; align-items: flex-start; gap: 2px; line-height: 20px; font-weight: 500; } .icon { display: flex; flex: none; width: 14px; height: 14px; margin-top: 1px; color: var(--dsw-alias-brand-primary-new-colorprimary-new-color); } .close { position: absolute; top: 6px; right: 6px; display: flex; align-items: center; justify-content: center; width: 18px; height: 18px; padding: 4px; border: 0; background: transparent; color: var(--dsw-alias-label-caption); cursor: pointer; } diff --git a/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx new file mode 100644 index 0000000000..1776aee512 --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/AccountNotifications.tsx @@ -0,0 +1,175 @@ +/** Notification extension rendered inside the sidebar account menu. */ +import { useEffect, useRef, type CSSProperties } from 'react' +import { Button, IconCloseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-settings-account/client' +import type { AccountNotice } from './notification-controller.ts' +import type { NotificationKey } from './locales.ts' +import css from './AccountNotifications.module.css' +import { dismissNotice } from './notice-transition.ts' + +/** Notification view and interactions supplied by the notification plugin. */ +export interface AccountNotificationsInjected { + hooks: { notices: HostObservable } + /** @param id - notification that completed a displayed frame. */ + shown: (id: AccountNotice['id']) => void + /** @param id - foreground notification whose non-dismiss action was clicked. */ + ctaClicked: (id: AccountNotice['id']) => void + /** @param id - notification explicitly closed by the user. */ + dismiss: (id: AccountNotice['id']) => void +} + +/** Notification component props derived from its parent-owned slot. */ +export type AccountNotificationsProps = PropsRuntime<'settings.launcher.notifications'> + & InjectFace & PropsLocale<'account.notifications'> + +/** @param props - account-menu availability and notification content. @returns the anchored notification stack. */ +export function AccountNotifications({ active, openAccount, useNotices, shown, ctaClicked, dismiss, t }: AccountNotificationsProps) { + const notices = useNotices(value => value) + return active && +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { 'account.notifications': NotificationKey } +} + +/* v8 ignore next 3 -- closed-union defaults only defend future source widening */ +function assertNever(_value: never): never { + throw new Error('unsupported account notification target') +} + +/** @param displayUntil - server display deadline. @returns whether the notification remains eligible for display. */ +function live(displayUntil: string | null): boolean { + if (displayUntil === null) return true + const expires = Date.parse(displayUntil) + // An unparsable timestamp is not evidence of expiry, so the notice still shows. + return Number.isNaN(expires) || expires > Date.now() +} + +/** + * @param run - callback to invoke once one presented frame has passed. + * @returns a canceller for a card that unmounts or hides first. + */ +function afterPaint(run: () => void): () => void { + if (typeof requestAnimationFrame !== 'function') { + // Without a frame clock, the following task is the best available paint boundary. + const timer = setTimeout(run, 0) + return () => { clearTimeout(timer) } + } + let cancelled = false + let timer: ReturnType | undefined + const frame = requestAnimationFrame(() => { + // The frame callback runs before its paint; the following task runs after it. + timer = setTimeout(() => { + if (!cancelled) run() + }, 0) + }) + return () => { + cancelled = true + cancelAnimationFrame(frame) + if (timer !== undefined) clearTimeout(timer) + } +} + +/** @param props - server-ordered notices, localized fallback copy, and display callbacks. + * @returns a non-modal stack whose foreground card alone can report display or be closed. + */ +export function AccountNoticeStack({ notices, closeLabel, onShown, onCtaClicked, onDismiss, onOpenAccount }: { + notices: readonly AccountNotice[] + closeLabel: string + /** Open the account settings route while retaining the notification. */ + onOpenAccount: () => void + /** Called after the foreground card has passed a visible presented frame. */ + onShown: (id: AccountNotice['id']) => void + /** Called when the user clicks any non-dismiss action on the foreground card. */ + onCtaClicked: (id: AccountNotice['id']) => void + /** Called when the user closes the foreground card. */ + onDismiss: (id: AccountNotice['id']) => void +}) { + const liveNotices = notices.filter(notice => live(notice.displayUntil)) + return
+ {liveNotices.map((notice, depth) => )} +
+} + +/** One stable card node remains mounted as the cards before it are dismissed. */ +function NoticeCard({ notice, depth, closeLabel, onShown, onCtaClicked, onDismiss, onOpenAccount }: { + notice: AccountNotice + depth: number + closeLabel: string + onOpenAccount: () => void + onShown: (id: AccountNotice['id']) => void + onCtaClicked: (id: AccountNotice['id']) => void + onDismiss: (id: AccountNotice['id']) => void +}) { + const foreground = depth === 0 + const card = useRef(null) + const reported = useRef(false) + const actionSlots = new Map() + useEffect(() => { + if (!foreground || reported.current || !live(notice.displayUntil)) return + const element = card.current + /* v8 ignore next -- React attaches the card ref before running this effect. */ + if (element === null) return + let intersecting = false + let cancel: (() => void) | undefined + const visible = () => intersecting && document.visibilityState !== 'hidden' && !element.closest('[hidden], [inert]') + const attempt = () => { + if (reported.current || cancel !== undefined || !live(notice.displayUntil)) return + if (!visible()) return + cancel = afterPaint(() => { + cancel = undefined + if (reported.current || !visible() || !live(notice.displayUntil)) return + reported.current = true + onShown(notice.id) + }) + } + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + intersecting = entry.isIntersecting + attempt() + } + }) + observer.observe(element) + document.addEventListener('visibilitychange', attempt) + return () => { + observer.disconnect() + document.removeEventListener('visibilitychange', attempt) + cancel?.() + } + }, [foreground, notice.id, notice.displayUntil, onShown]) + return +} diff --git a/packages/client/ui-account-notifications/src/client/index.ts b/packages/client/ui-account-notifications/src/client/index.ts new file mode 100644 index 0000000000..3b5adafe27 --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/index.ts @@ -0,0 +1,68 @@ +/** Account notifications driven by the existing account UI stream. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { AccountUiState } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from '../config.ts' +import { AccountNotifications, type AccountNotificationsInjected } from './AccountNotifications.tsx' +import { createNotificationController, type AccountNotice } from './notification-controller.ts' +import { en, zh, ja, es, fr, de, ru, pt } from './locales.ts' +export type { AccountNotificationsInjected, AccountNotificationsProps } from './AccountNotifications.tsx' + +/** Services used for notification lifecycle and presentation. */ +export const inject = ['slots', 'locale', 'remote', 'remote.account', 'accountUi'] + +/** @param ctx - client plugin context sharing the account owner's existing state stream. */ +export function apply(ctx: Context): void { + const page = globalThis as Partial> + const config = Config(page[NOTIFICATIONS_CONFIG_GLOBAL] ?? {}) + ctx.effect(() => ctx.locale.register('account.notifications', { en, zh, ja, es, fr, de, ru, pt }), 'notifications: dictionaries') + let snapshot: readonly AccountNotice[] = [] + const listeners = new Set<() => void>() + const controller = createNotificationController({ + locale: ctx.locale.getSnapshot().active, + pollIntervalMs: config.notificationPollIntervalMs, + read: async (locale) => { + const result = await ctx.remote.account.getNotifications(ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification read failed') + return result.value + }, + readContent: async (id, locale) => { + const result = await ctx.remote.account.getNotificationContent(id, ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification content read failed') + return result.value + }, + reportEvent: async (id, event) => { + const result = await ctx.remote.account.reportNotificationEvent(id, event, + ctx.accountUi.clientMetadata(ctx.locale.getSnapshot().active)) + if (!result.ok) throw new Error('account notification event report failed') + return result.value + }, + publish: (notices) => { snapshot = notices; for (const listener of listeners) listener() }, + }) + const update = (state: AccountUiState, reset: boolean): void => { + const signedIn = state.view?.status === 'credential-stored' && !state.failed + if (reset || !signedIn) controller.end() + if (signedIn && reset) controller.begin() + } + ctx.effect(() => () => { controller.end() }, 'notifications: account lifetime') + ctx.on('account-ui/change', update) + ctx.on('account-ui/refresh', () => controller.refresh()) + ctx.on('locale/change', (state) => { void controller.setLocale(state.active) }) + update(ctx.accountUi.getSnapshot(), true) + const state = { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }, + } + const injected: AccountNotificationsInjected = { + hooks: { notices: state }, + shown: (id) => { controller.shown(id) }, + ctaClicked: (id) => { controller.ctaClicked(id) }, + dismiss: (id) => { controller.dismiss(id) }, + } + ctx.slots.inject('settings.launcher.notifications', () => ctx.slots.register({ + name: 'settings.launcher.notifications', locale: 'account.notifications', + inject: () => injected, + }, AccountNotifications)) +} diff --git a/packages/client/ui-account-notifications/src/client/locales.ts b/packages/client/ui-account-notifications/src/client/locales.ts new file mode 100644 index 0000000000..be4ef4fd3f --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/locales.ts @@ -0,0 +1,18 @@ +/** Close-control copy owned by account notifications; notification content is server-localized. */ +export const en = { close: 'Close' } +/** Chinese notification controls. */ +export const zh = { close: '关闭' } +/** Japanese notification controls. */ +export const ja = { close: '閉じる' } +/** Spanish notification controls. */ +export const es = { close: 'Cerrar' } +/** French notification controls. */ +export const fr = { close: 'Fermer' } +/** German notification controls. */ +export const de = { close: 'Schließen' } +/** Russian notification controls. */ +export const ru = { close: 'Закрыть' } +/** Portuguese notification controls. */ +export const pt = { close: 'Fechar' } +/** Localized notification control keys. */ +export type NotificationKey = keyof typeof en diff --git a/packages/client/ui-settings-account/src/client/notice-transition.ts b/packages/client/ui-account-notifications/src/client/notice-transition.ts similarity index 100% rename from packages/client/ui-settings-account/src/client/notice-transition.ts rename to packages/client/ui-account-notifications/src/client/notice-transition.ts diff --git a/packages/client/ui-account-notifications/src/client/notification-controller.ts b/packages/client/ui-account-notifications/src/client/notification-controller.ts new file mode 100644 index 0000000000..6c1ba0d01b --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/notification-controller.ts @@ -0,0 +1,248 @@ +/** + * Lifecycle of account notifications: one foreground card in a stack, one read result in + * force at a time, and independent display, action-click, and dismissal reports. Account activation + * and Settings entry replace the polling cycle with an immediate read. Each read + * settles before the next delay begins; the server owns unconsumed notifications. + * + * A displayed event is sent once the foreground card reports a presented frame: the card has + * a position, the document is visible, and it painted one frame. The card measures + * no cover, so a card painted under the open Settings overlay reports like any + * other. Business-action clicks report without waiting or closing the card. + * Explicit dismissal sends only a dismissed event. + * Expiry and account cleanup do not report dismissal. + * + * One lifecycle covers one signed-in session. Login-progress updates retain the + * card and active poll. Credential and connection changes end + * that lifecycle before another begins. Signing out and unloading also clear + * the cards; a later sign-in shows whatever the server offers. + * @module @deepseek-ai/dsh-client-ui-account-notifications/src/client/notification-controller + */ +import type { + AccountNotification, AccountNotificationBatch, AccountNotificationEvent, AccountNotificationId, +} from '@deepseek-ai/dsh-deepseek-account/types' + +/** Notification content currently available to the sidebar presentation. */ +export type AccountNotice = AccountNotification + +/** Collaborators and polling interval of one account notification lifecycle. */ +export interface NotificationControllerOptions { + /** Initial delay for each poll, retained until the server provides a new one. */ + readonly pollIntervalMs: number + /** UI language in effect when the controller starts. */ + readonly locale: string + /** Read the signed-in account's unconsumed notifications. @returns the batch, or null when no account is signed in. */ + read: (locale: string) => Promise + /** + * Query localized content for an existing card without changing consumption. + * @param id - notification requested by stable identity. + * @param locale - language captured for this request. + * @returns content, or null when the account changed; failures reject. + */ + readContent: (id: AccountNotificationId, locale: string) => Promise + /** + * Report one notification interaction. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @returns false when the account changed or signed out; a protocol failure rejects. + */ + reportEvent: (id: AccountNotificationId, event: AccountNotificationEvent) => Promise + /** @param notices - notices in front-to-back order; empty when none are shown. */ + publish: (notices: readonly AccountNotice[]) => void +} + +/** Commands the account plugin issues to the account notification lifecycle. */ +export interface NotificationController { + /** + * Start the signed-in lifecycle and restart polling with an immediate read. + * Re-entry retains cards; the caller ends the lifecycle on credential or connection changes. + */ + begin(): void + /** Stop the lifecycle, drop the displayed notice, and ignore late event failures. */ + end(): void + /** + * Restart polling with an immediate read, retaining cards. + * @returns after the immediate read settles, without waiting for later polls. + */ + refresh(): Promise + /** + * Refresh current cards in a new UI language, retaining order and consumption. + * @param locale - active UI language; an unchanged value issues no request. + * @returns after content requests settle; failures retain the previous content. + */ + setLocale(locale: string): Promise + /** @param id - notice whose card passed a presented frame while visible. */ + shown(id: AccountNotificationId): void + /** @param id - foreground notice whose non-dismiss action was clicked; reports without removing the card. */ + ctaClicked(id: AccountNotificationId): void + /** @param id - foreground notice the user explicitly closed; reports only a dismissed event. */ + dismiss(id: AccountNotificationId): void +} + +/** One replaceable query cycle; an obsolete request cannot publish or schedule another read. */ +interface NotificationPoll { + intervalMs: number + timer?: ReturnType +} + +/** + * @param displayUntil - server expiration timestamp. + * @param at - milliseconds since epoch. + * @returns whether the notification can no longer be shown. + */ +function expired(displayUntil: string | null, at: number): boolean { + if (displayUntil === null) return false + const expires = Date.parse(displayUntil) + // An unparsable timestamp is not evidence of expiry, so the notice still shows. + return !Number.isNaN(expires) && expires <= at +} + +/** + * Own the read, display, and interaction reporting lifecycle of account notifications. + * @param options - collaborators and timings. + * @returns the controller the account plugin drives from account and settings state. + */ +export function createNotificationController(options: NotificationControllerOptions): NotificationController { + let scope: object | undefined + let locale = options.locale + let contentGeneration = 0 + /** Notice currently published to the sidebar, including the expiration checked at display time. */ + let current: readonly AccountNotice[] = [] + let poll: NotificationPoll | undefined + /** Notifications the card on screen already reported, so one mount cannot report display twice. */ + const reported = new Set() + const setCurrent = (notices: readonly AccountNotice[]): void => { + if (notices.length === current.length && notices.every((notice, index) => { + return JSON.stringify(notice) === JSON.stringify(current[index]) + })) return + const retained = new Set(notices.map(notice => notice.id)) + for (const id of reported) if (!retained.has(id)) reported.delete(id) + current = notices + options.publish(notices) + } + /** + * Keep a presented foreground card until dismissal or expiration, refreshing + * its copy when offered again; other live candidates follow in server order. + */ + const apply = (batch: AccountNotificationBatch, preserveCopy: boolean): void => { + const notifications = batch.notifications.map((notice) => { + const previous = preserveCopy ? current.find(value => value.id === notice.id) : undefined + return previous === undefined ? notice : { ...notice, title: previous.title, body: previous.body, actions: previous.actions } + }) + const foreground = current[0] + const retained = foreground !== undefined && reported.has(foreground.id) + ? notifications.find(notice => notice.id === foreground.id) ?? foreground + : undefined + const at = Date.now() + const candidates = notifications.filter(notice => !expired(notice.displayUntil, at)) + setCurrent(retained !== undefined && !expired(retained.displayUntil, at) + ? [retained, ...candidates.filter(notice => notice.id !== retained.id)] + : candidates) + } + + /** Refresh only cards that still belong to this account and language when the replies settle. */ + async function refreshContent(): Promise { + const scopeAtCall = scope + if (scopeAtCall === undefined || current.length === 0) return + const generation = ++contentGeneration + const requestedLocale = locale + const responses = await Promise.allSettled(current.map(async notice => options.readContent(notice.id, requestedLocale))) + if (scope !== scopeAtCall || generation !== contentGeneration) return + if (responses.some(response => response.status === 'rejected')) console.error('[deepseek-account] notification content read failed') + const updates = responses.flatMap(response => response.status === 'fulfilled' && response.value !== null ? [response.value] : []) + setCurrent(current.map((notice) => { + const update = updates.find(value => value.id === notice.id) + return update == null ? notice : { ...notice, title: update.title, body: update.body, actions: update.actions } + })) + } + + /** + * Read once for the active poll, retaining cards on failure. Replacement and + * sign-out discard late replies and prevent another read from being scheduled. + * @param pollAtRead - query cycle that owns this read. + * @returns after this read settles. + */ + async function runRead(pollAtRead: NotificationPoll): Promise { + const requestedLocale = locale + let batch: AccountNotificationBatch | null + try { batch = await options.read(requestedLocale) } + catch (_error) { + if (poll !== pollAtRead) return + console.error('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + batch = null + } + if (poll !== pollAtRead) return + if (batch !== null) { + pollAtRead.intervalMs = batch.nextPollAfterSeconds * 1_000 + apply(batch, requestedLocale !== locale) + if (requestedLocale !== locale) await refreshContent() + } + if (poll !== pollAtRead) return + pollAtRead.timer = setTimeout(() => { void runRead(pollAtRead) }, pollAtRead.intervalMs) + } + + const stopPolling = (): void => { + if (poll?.timer !== undefined) clearTimeout(poll.timer) + poll = undefined + } + const restartPolling = (): Promise => { + stopPolling() + poll = { intervalMs: options.pollIntervalMs } + return runRead(poll) + } + + /** Attempt each interaction once without changing the card on failure. */ + const report = async (id: AccountNotificationId, event: AccountNotificationEvent): Promise => { + const scopeAtReport = scope + if (scopeAtReport === undefined || current[0]?.id !== id || (event === 'displayed' && reported.has(id))) return + if (event === 'displayed') reported.add(id) + try { await options.reportEvent(id, event) } + catch (_error) { + if (scope === scopeAtReport) { + console.error('[deepseek-account] notification event report failed; keeping local state without retry', { event }) + } + } + } + + const endLifecycle = (): void => { + if (scope === undefined) return + stopPolling() + scope = undefined + contentGeneration++ + reported.clear() + setCurrent([]) + } + + return { + begin() { + scope ??= {} + void restartPolling() + }, + end: endLifecycle, + refresh(): Promise { + if (scope === undefined) return Promise.resolve() + return restartPolling() + }, + async setLocale(value) { + if (value === locale) return + locale = value + contentGeneration++ + await refreshContent() + }, + shown(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'displayed') + }, + ctaClicked(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'cta_clicked') + }, + dismiss(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'dismissed') + setCurrent(current.slice(1).filter(notice => !expired(notice.displayUntil, Date.now()))) + }, + } +} diff --git a/packages/client/ui-account-notifications/src/config.ts b/packages/client/ui-account-notifications/src/config.ts new file mode 100644 index 0000000000..4a37e8392a --- /dev/null +++ b/packages/client/ui-account-notifications/src/config.ts @@ -0,0 +1,14 @@ +/** Public polling configuration shared by the notification Host and Client halves. */ +import Schema from '@deepseek-ai/schemastery' + +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +/** Validate notification polling configuration. */ +export const Config = Schema.object({ + notificationPollIntervalMs: Schema.natural().min(1).max(2_147_483_647).default(600_000), +}) +/** Bootstrap key for public notification configuration. */ +export const NOTIFICATIONS_CONFIG_GLOBAL = '__DSH_ACCOUNT_NOTIFICATIONS_CONFIG__' diff --git a/packages/client/ui-account-notifications/src/css-modules.d.ts b/packages/client/ui-account-notifications/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-account-notifications/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-account-notifications/src/index.ts b/packages/client/ui-account-notifications/src/index.ts new file mode 100644 index 0000000000..45b84f3cea --- /dev/null +++ b/packages/client/ui-account-notifications/src/index.ts @@ -0,0 +1,12 @@ +/** Publishes public configuration for the account notification client plugin. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from './config.ts' +export { Config } from './config.ts' + +/** @param ctx - Host page bootstrap collector. @param config - validated notification configuration. */ +export function apply(ctx: Context, config: Config): void { + ctx.on('webserver/index-inject', (table) => { + table.push({ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: config }) + }) +} diff --git a/packages/client/ui-account-notifications/tests/apply.client.spec.ts b/packages/client/ui-account-notifications/tests/apply.client.spec.ts new file mode 100644 index 0000000000..ba0b42bfd2 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/apply.client.spec.ts @@ -0,0 +1,350 @@ +// @vitest-environment jsdom +/** Notification integration shares the account plugin's single state stream. */ +import { afterEach, beforeEach, expect, onTestFinished, vi } from 'vitest' +import { ok } from '@deepseek-ai/dsh-remote-mock' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' +import type { AccountNotificationBatch, AccountNotificationId, AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import type { AccountNotificationsInjected } from '../src/client/AccountNotifications.tsx' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' +import { notification } from './notification-fixture.ts' + +const it = createClientTest({ roster: webApp }) +const SELF = '@deepseek-ai/dsh-client-ui-settings-account' +const view: AccountView = { status: 'signed-out', attempt: null, + links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } +const stored: AccountView = { ...view, status: 'credential-stored' } +function bonus(orderId: string, message = 'Awarded 5.00'): AccountNotificationBatch { + return { nextPollAfterSeconds: 300, notifications: [notification(orderId, { body: message, displayUntil: '2099-01-01T00:00:00Z' })] } +} +function operations(c: TestClient): AccountSectionInjected { + const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!() + return injected as AccountSectionInjected +} +function notificationOperations(c: TestClient): AccountNotificationsInjected { + const injected: object = c.ctx.slots.entries('settings.launcher.notifications')[0]!.inject!() + return injected as AccountNotificationsInjected +} +beforeEach(() => { vi.stubEnv('DSH_CLIENT_VERSION', '0.0.0-test') }) +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.restoreAllMocks() }) + +it('reads the unnotified bonus in the active locale and acknowledges only after the card renders', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' })) + // A successful read is not a display, so nothing may be acknowledged yet. + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + notificationOperations(c).shown(orderId as AccountNotificationId) + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'displayed', expect.objectContaining({ locale: 'en' })) + }) + notificationOperations(c).ctaClicked(orderId as AccountNotificationId) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith( + orderId, 'cta_clicked', expect.objectContaining({ locale: 'en' })) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(orderId) + notificationOperations(c).dismiss(orderId as AccountNotificationId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'dismissed', expect.objectContaining({ locale: 'en' })) + }) +}, 60_000) + +it('starts one notification poll across the credential commit and login-success frames', async ({ start }) => { + const c = await start() + c.mock.remote.session.initializeDefaultModel.mockResolvedValue(ok(undefined)) + const reads = c.mock.remote.account.getNotifications + const id = 'one-login' as SignInAttemptId + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'committing' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) +}, 60_000) + +for (const outcome of ['null', 'failure'] as const) it(`queries a replacement credential without adopting the old ${outcome} reply`, async ({ start }) => { + const c = await start() + const previous = Promise.withResolvers>>() + const reads = c.mock.remote.account.getNotifications + reads.mockReturnValueOnce(previous.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + reads.mockResolvedValueOnce(ok(bonus('replacement-notice'))) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(2) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') + if (outcome === 'null') previous.resolve(ok(null)) + else previous.reject(new Error('obsolete credential')) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') +}, 60_000) + +it('clears notification cards and ignores old event failures when credentials change despite a failed replacement list', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + const event = Promise.withResolvers>>() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockReturnValueOnce(event.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(id) + await vi.advanceTimersByTimeAsync(0) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + c.mock.remote.account.getNotifications.mockRejectedValueOnce(new Error('replacement offline')) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + event.reject(new Error('old request failed')) + await vi.advanceTimersByTimeAsync(3_000) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + expect(log).toHaveBeenCalledWith('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice without retrying its event across repeated signed-in frames', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(orderId) + await vi.advanceTimersByTimeAsync(0) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + await vi.advanceTimersByTimeAsync(60_000) + notificationOperations(c).shown(orderId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith( + '[deepseek-account] notification event report failed; keeping local state without retry', { event: 'displayed' }) + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice absent when the bonus read is refused, then shows the next read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValueOnce({ + ok: false, error: new RemoteError('gateway/internal', 'offline', {}), + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + await actions.refreshAccount() + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) +}, 60_000) + +it('drops the previous account notice and stops reading after sign-out', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000001'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + // Signing out ends the lifecycle, so no further read follows. + const reads = c.mock.remote.account.getNotifications.mock.calls.length + await new Promise((resolve) => { setTimeout(resolve, 20) }) + expect(c.mock.remote.account.getNotifications.mock.calls.length).toBe(reads) +}, 60_000) + +it('refreshes balances and notifications immediately on Settings entry', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const balance: AccountDetails['balance'] = { + status: 'ready', value: [{ currency: 'CNY', balance: '12.34' }], bonusWallets: [{ currency: 'CNY', balance: '5.00' }], + } + c.mock.remote.account.getBalance.mockResolvedValue(ok(balance)) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + // Account activation starts with an immediate read. + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + // Signing in already read the wallet once through the details refresh. + const balances = c.mock.remote.account.getBalance.mock.calls.length + await actions.refreshAccount() + expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(balances + 1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + // The bonus read carries the active UI language. + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'en' })) +}, 60_000) + +it('replaces polling on startup, sign-in and Settings entry and stops on sign-out or unload', async ({ start }) => { + vi.stubGlobal(NOTIFICATIONS_CONFIG_GLOBAL, { notificationPollIntervalMs: 1_000 }) + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + try { + await c.reload(SELF) + await c.flush() + const actions = operations(c) + const reads = c.mock.remote.account.getNotifications + reads.mockClear() + // Startup receives the stored account in its initial stream snapshot. + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(500) + await actions.refreshAccount() + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(4) + await c.unload(SELF) + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(4) + } finally { vi.useRealTimers() } +}, 60_000) + +it('publishes a failed balance from a Settings entry without dropping the bonus read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + await actions.refreshAccount() + expect(actions.hooks.account.getSnapshot().details?.balance).toEqual({ status: 'failed' }) + // The bonus read still ran: a failed wallet read does not cancel it. + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) +}, 60_000) + +it('refreshes consumed notification content on a locale change without reading the unconsumed list again', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.remote.account.getNotificationContent.mockResolvedValue(ok(notification(id, { title: '公告', body: '新的中文内容' }))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(id) }) + notificationOperations(c).shown(id as AccountNotificationId) + await vi.waitFor(() => { expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) }) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('新的中文内容') }) + expect(c.mock.remote.account.getNotificationContent).toHaveBeenCalledWith( id, expect.objectContaining({ locale: 'zh' })) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) +}, 60_000) + +it('retains notification content when the localization RPC is refused', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + const output = vi.spyOn(console, 'error').mockImplementation(() => {}) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.getNotificationContent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(output).toHaveBeenCalledWith('[deepseek-account] notification content read failed') }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') +}, 60_000) + +it('clears notifications and stops polling when the account carrier fails', async ({ start }) => { + const c = await start() + const open = c.ctx.remote.$stream.bind(c.ctx.remote) + let fail: (() => void) | undefined + vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { + if (options.name === 'account') fail = () => { options.carrierFailed?.(new Error('connection lost')) } + return open(options) + }) + await c.reload(SELF) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000000'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toHaveLength(1) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + vi.useFakeTimers() + try { + fail?.() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + await vi.advanceTimersByTimeAsync(600_000) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + } finally { vi.useRealTimers() } +}, 60_000) + +it('reloads notifications without opening another account stream', async ({ start }) => { + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('retained'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + const stream = vi.spyOn(c.ctx.remote, '$stream') + const before = c.mock.remote.account.getNotifications.mock.calls.length + await c.reload('@deepseek-ai/dsh-client-ui-account-notifications') + await c.flush() + expect(stream).not.toHaveBeenCalled() + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(before + 1) + expect(notificationOperations(c).hooks.notices.getSnapshot()[0]?.id).toBe('retained') +}) + +it('publishes notification changes through one stable source and releases its subscribers', async ({ start }) => { + const c = await start() + const source = notificationOperations(c).hooks.notices + expect(notificationOperations(c).hooks.notices).toBe(source) + const listener = vi.fn() + const dispose = source.subscribe(listener) + onTestFinished(dispose) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('first'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(source.getSnapshot()[0]?.id).toBe('first') + expect(listener).toHaveBeenCalled() + dispose() + listener.mockClear() + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + expect(source.getSnapshot()).toEqual([]) + expect(listener).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/config.client.spec.ts b/packages/client/ui-account-notifications/tests/config.client.spec.ts new file mode 100644 index 0000000000..7c479ec7f4 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/config.client.spec.ts @@ -0,0 +1,27 @@ +/** Notification configuration reaches the client without account secrets. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished } from 'vitest' +import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' +import { apply, Config } from '../src/index.ts' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' + +it('publishes polling configuration and removes the publisher on disposal', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin({ apply, Config }, { notificationPollIntervalMs: 250 }) + const table: IndexInjection[] = [] + const peer = { principal: { kind: 'owner' } } as Parameters[1] + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([{ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: { notificationPollIntervalMs: 250 } }]) + await ctx.fiber.dispose() + table.length = 0 + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([]) +}) + +it('defaults to ten minutes and rejects intervals outside browser timer limits', () => { + expect(Config({}).notificationPollIntervalMs).toBe(600_000) + for (const notificationPollIntervalMs of [0, -1, 1.5, 2_147_483_648]) { + expect(() => Config({ notificationPollIntervalMs })).toThrow() + } +}) diff --git a/packages/client/ui-settings-account/tests/expected/notice.txt b/packages/client/ui-account-notifications/tests/expected/notice.txt similarity index 100% rename from packages/client/ui-settings-account/tests/expected/notice.txt rename to packages/client/ui-account-notifications/tests/expected/notice.txt diff --git a/packages/client/ui-settings-account/tests/notice-transition.client.spec.ts b/packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts similarity index 100% rename from packages/client/ui-settings-account/tests/notice-transition.client.spec.ts rename to packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts diff --git a/packages/client/ui-settings-account/tests/notice.client.spec.tsx b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx similarity index 50% rename from packages/client/ui-settings-account/tests/notice.client.spec.tsx rename to packages/client/ui-account-notifications/tests/notice.client.spec.tsx index 5fbbfc3994..6491f93619 100644 --- a/packages/client/ui-settings-account/tests/notice.client.spec.tsx +++ b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx @@ -1,17 +1,38 @@ // @vitest-environment jsdom /** * The bonus notice card reports display only when the server's copy is - * actually on screen: it needs an anchor position, a visible document, and one - * presented frame. Closing counts as seen because the user acted on it. + * actually on screen: it needs a visible sidebar and document, and one presented + * frame. Closing counts as seen because the user acted on it. */ -import { createRef } from 'react' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { act } from 'react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AccountBonusOrderId } from '@deepseek-ai/dsh-deepseek-account/types' -import { AccountNoticeStack } from '../src/client/AccountNotice.tsx' +import { AccountNoticeStack } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' const disconnect = vi.fn() +const observers: VisibilityObserver[] = [] +let intersecting = true + +class VisibilityObserver implements IntersectionObserver { + readonly root = null + readonly rootMargin = '0px' + readonly scrollMargin = '0px' + readonly thresholds = [0] + private target!: Element + constructor(private readonly callback: IntersectionObserverCallback) { observers.push(this) } + observe(target: Element): void { this.target = target; this.notify(intersecting) } + unobserve(): void {} + disconnect = disconnect + takeRecords(): IntersectionObserverEntry[] { return [] } + notify(visible: boolean): void { + const rect = new DOMRect(0, 0, 260, 100) + this.callback([{ + target: this.target, isIntersecting: visible, intersectionRatio: visible ? 1 : 0, + time: 0, boundingClientRect: rect, intersectionRect: rect, rootBounds: null, + }], this) + } +} let visibility: 'visible' | 'hidden' = 'visible' /** Frame callbacks the card scheduled, in order. */ let frames: (() => void)[] = [] @@ -23,7 +44,10 @@ function setVisibility(value: 'visible' | 'hidden'): void { beforeEach(() => { visibility = 'visible' + intersecting = true + observers.length = 0 frames = [] + vi.stubGlobal('IntersectionObserver', VisibilityObserver) Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }) // jsdom drives requestAnimationFrame from its own clock, so the test presents frames explicitly. vi.stubGlobal('requestAnimationFrame', (callback: () => void) => { frames.push(callback); return frames.length }) @@ -32,15 +56,13 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); vi.restoreAllMocks(); disconnect.mockClear() }) function mount(id: string, onShown = vi.fn(), onDismiss = vi.fn()) { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() + const onCtaClicked = vi.fn() const view = render(<> -
- + {}} + notices={[notification(id, { displayUntil: '2099-01-01T00:00:00Z' })]} + onShown={onShown} onCtaClicked={onCtaClicked} onDismiss={onDismiss} /> ) - return { view, onShown, onDismiss } + return { view, onShown, onCtaClicked, onDismiss } } /** @@ -89,12 +111,13 @@ it('waits for another visible frame when the document hides before the follow-up expect(onShown).toHaveBeenCalledExactlyOnceWith('order-1') }) -it('reports dismissal so closing the card counts as seen', async () => { - const { onShown, onDismiss } = mount('order-1') +it('reports dismissal without a CTA click when the close icon is clicked', async () => { + const { onShown, onCtaClicked, onDismiss } = mount('order-1') await presentFrames() fireEvent.click(screen.getByRole('button', { name: 'Close' })) expect(onDismiss).toHaveBeenCalledWith('order-1') expect(onShown).toHaveBeenCalledOnce() + expect(onCtaClicked).not.toHaveBeenCalled() }) it('reports neither display nor dismissal when unmounted before its frame', async () => { @@ -140,17 +163,14 @@ it.each([true, false])('cancels the presentation task when the card unmounts fir }) it('keeps back cards mounted but inaccessible and reports them only after promotion', async () => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() const onShown = vi.fn() const onDismiss = vi.fn() - const notices = ['first', 'second', 'third'].map(id => ({ - orderId: id as AccountBonusOrderId, title: id, message: `${id} copy`, expiresAt: '', + const notices = ['first', 'second', 'third'].map(id => notification(id, { + title: id, body: `${id} copy`, actions: [{ label: 'Dismiss', style: 'secondary', target: { type: 'dismiss' } }], })) const tree = (remaining: typeof notices) => <> -
- + {}} + onShown={onShown} onCtaClicked={vi.fn()} onDismiss={onDismiss} /> const view = render(tree(notices)) const second = screen.getByText('second copy').closest('aside') @@ -170,12 +190,84 @@ it('keeps back cards mounted but inaccessible and reports them only after promot expect(onShown).toHaveBeenCalledTimes(2) }) -it('does not acknowledge a notice before an anchor is mounted', async () => { - const onShown = vi.fn() - render(()} title="News" closeLabel="Close" - notices={[{ orderId: 'notice' as AccountBonusOrderId, message: 'News', expiresAt: '' }]} - onShown={onShown} onDismiss={vi.fn()} />) +it('keeps sidebar cards mounted without reporting until they enter the viewport', async () => { + intersecting = false + const { view, onShown, onDismiss } = mount('notice') + const card = view.container.querySelector('aside') + expect(card).not.toBeNull() + expect(view.container.contains(screen.getByRole('status'))).toBe(true) await presentFrames() expect(onShown).not.toHaveBeenCalled() - expect(screen.queryByRole('status')).toBeNull() + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + act(() => { observers[0]!.notify(false); observers[0]!.notify(true) }) + await presentFrames() + expect(view.container.querySelector('aside')).toBe(card) + expect(onShown).toHaveBeenCalledOnce() + expect(onDismiss).not.toHaveBeenCalled() +}) + +it.each(['hidden', 'inert'])('does not report when its sidebar becomes %s before the presentation task', async (attribute) => { + const { view, onShown } = mount('notice') + await presentFrames(() => { view.container.setAttribute(attribute, '') }) + expect(onShown).not.toHaveBeenCalled() + view.container.removeAttribute(attribute) + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') +}) + +it('does not report when the card leaves the viewport before the presentation task', async () => { + const { onShown } = mount('notice') + await presentFrames(() => { observers[0]!.notify(false) }) + expect(onShown).not.toHaveBeenCalled() +}) + +it.each(['primary', 'secondary'] as const)('reports non-dismiss %s actions and keeps focus while localized content changes', async (style) => { + const onShown = vi.fn() + const onDismiss = vi.fn() + const onOpenAccount = vi.fn() + const onCtaClicked = vi.fn() + const content = (chinese: boolean) => notification('notice', { + title: chinese ? '产品公告' : 'Product news', body: chinese ? '新功能已上线' : 'New features', + actions: [ + { label: chinese ? '查看余额' : 'View balance', style, target: { type: 'app_route', name: 'account' } }, + { label: chinese ? '知道了' : 'Got it', style, target: { type: 'dismiss' } }, + ], + }) + const tree = (chinese: boolean) => <> + + + const view = render(tree(false)) + await presentFrames() + const button = screen.getByRole('button', { name: 'View balance' }) + button.focus() + fireEvent.click(button) + expect(onOpenAccount).toHaveBeenCalledOnce() + expect(onCtaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(onDismiss).not.toHaveBeenCalled() + view.rerender(tree(true)) + expect(screen.getByRole('button', { name: '查看余额' })).toBe(button) + expect(document.activeElement).toBe(button) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + fireEvent.click(screen.getByRole('button', { name: '知道了' })) + expect(onDismiss).toHaveBeenCalledExactlyOnceWith('notice') + expect(onCtaClicked).toHaveBeenCalledOnce() +}) + +it('renders separate buttons for repeated action targets', () => { + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + render(<> + {}} + onShown={vi.fn()} onCtaClicked={vi.fn()} onDismiss={vi.fn()} notices={[notification('notice', { actions: [ + { label: 'Got it', style: 'primary', target: { type: 'dismiss' } }, + { label: 'Later', style: 'secondary', target: { type: 'dismiss' } }, + ] })]} /> + ) + expect(screen.getByRole('button', { name: 'Got it' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Later' })).toBeTruthy() + expect(output).not.toHaveBeenCalled() }) diff --git a/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts new file mode 100644 index 0000000000..211f8e58cd --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts @@ -0,0 +1,822 @@ +// @vitest-environment jsdom +/** + * Notification lifecycle: account activation and Settings entry replace polling + * with an immediate query. Display reports follow a presented frame. + * Each event is attempted once; nothing + * about a notice survives sign-out or unload. + */ +import { afterEach, expect, it, vi } from 'vitest' +import type { AccountNotificationBatch, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' +import { createNotificationController, type AccountNotice, type NotificationController } from '../src/client/notification-controller.ts' +import { notification } from './notification-fixture.ts' + +const TIMING = { pollIntervalMs: 600_000 } +const controllers = new Set() + +/** + * @param id - notification identifier. + * @param displayUntil - server expiration. + * @returns one unconsumed notification as the Host projects it. + */ +function batch(id: string, displayUntil: string | null = '2099-01-01T00:00:00Z'): AccountNotificationBatch { + return { + nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: [notification(id, { displayUntil })], + } +} + +function setup() { + const read = vi.fn(async (): Promise => null) + const readContent = vi.fn(async (): Promise => null) + const displayed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const dismissed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const clicked = vi.fn(async (_id: AccountNotificationId): Promise => true) + const stacks: (readonly AccountNotice[])[] = [] + const published: (AccountNotice | null)[] = [] + const controller = createNotificationController({ + ...TIMING, locale: 'en', read, readContent, + reportEvent: (id, event) => ({ displayed: displayed, cta_clicked: clicked, dismissed })[event](id), + publish: (notices) => { stacks.push(notices); published.push(notices[0] ?? null) }, + }) + controllers.add(controller) + /** @returns the most recently published notice. */ + const latest = (): AccountNotice | null | undefined => published.at(-1) + return { controller, read, readContent, displayed, clicked, dismissed, published, latest, stacks } +} + +afterEach(() => { + for (const controller of controllers) controller.end() + controllers.clear() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it('reads immediately and starts the next delay only after the current request settles', async () => { + vi.useFakeTimers() + const { controller, read } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + controller.begin() + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 3) + expect(read).toHaveBeenCalledTimes(1) + finish(null) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + controller.end() +}) + +it.each(['begin', 'refresh'] as const)('restarts polling immediately on %s and cancels the previous delay', async (trigger) => { + vi.useFakeTimers() + const { controller, read } = setup() + controller.begin() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + if (trigger === 'begin') controller.begin() + else await controller.refresh() + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + controller.end() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('discards a superseded request without publishing or resuming its poll', async () => { + vi.useFakeTimers() + const { controller, read, latest } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + read.mockResolvedValue(batch('new')) + controller.begin() + await controller.refresh() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + finish(batch('old')) + await vi.advanceTimersByTimeAsync(0) + expect(latest()?.id).toBe('new') + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('does not report or reschedule an obsolete request failure', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + let reject!: (error: Error) => void + read.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail })) + controller.begin() + controller.end() + reject(new Error('offline')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(1) + expect(log).not.toHaveBeenCalled() +}) + +it('does not resume polling after sign-out while a list reply is refreshing language content', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + const content = Promise.withResolvers() + read.mockReturnValueOnce(response.promise) + readContent.mockReturnValueOnce(content.promise) + controller.begin() + await controller.setLocale('zh') + response.resolve(batch('first')) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledWith('first', 'zh') + controller.end() + content.resolve(notification('first')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(latest()).toBeNull() + expect(read).toHaveBeenCalledOnce() +}) + +it('retains the shown card on failure and polls again after the configured delay', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read, latest, displayed } = setup() + read.mockResolvedValueOnce(batch('first')).mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue(batch('second')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(latest()?.id).toBe('first') + expect(log).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(read).toHaveBeenCalledTimes(3) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledOnce() +}) + +it('uses each server delay in seconds, retains it after failure, and resets it when polling restarts', async () => { + vi.useFakeTimers() + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + read.mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 2 }) + .mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 5 }) + .mockRejectedValueOnce(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(1_999) + expect(read).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(4) + await controller.refresh() + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(6) +}) + +it('publishes the server copy for the first unconsumed notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + controller.end() +}) + +it('reports display only after a presented frame and keeps the card until it is closed', async () => { + const { controller, read, displayed, published, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + expect(displayed).not.toHaveBeenCalled() + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + // A refresh still offering the notification must not republish the open card. + const publishedBefore = published.length + await controller.refresh() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(2) }) + expect(published.length).toBe(publishedBefore) + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + expect(latest()).toBeNull() + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it.each(['aborted', 'null'] as const)("does not adopt the replaced credential's in-flight read when it answers %s", async (answer) => { + vi.useFakeTimers() + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockRejectedValue(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + // Account A's next signed-in frame starts a read the Host abandons when the + // credential is replaced by B. B's frame must not inherit it: A's answer names + // the replaced account, so adopting it would leave B with no read of its own. + const abandoned = Promise.withResolvers() + read.mockReturnValueOnce(abandoned.promise) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + expect(read).toHaveBeenCalledTimes(3) + expect(latest()).toMatchObject({ id: 'notice-2' }) + if (answer === 'aborted') abandoned.reject(new Error('aborted')) + else abandoned.resolve(null) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + // The abandoned answer cannot restore the previous account's card. + expect(latest()).toMatchObject({ id: 'notice-2' }) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('refreshes the copy of the notification already on screen when a read offers it again', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + // The same notification arrives with new copy: its card updates in place instead of being replaced. + read.mockResolvedValue({ ...batch('notice-1'), notifications: [{ ...batch('notice-1').notifications[0]!, title: 'Updated title', body: 'Updated copy' }] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1', title: 'Updated title', body: 'Updated copy' }) + controller.end() +}) + +it('withdraws a card the user never saw when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // The card never reported a presented frame, so an empty read withdraws it. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it.each(['omitted', 'reordered'] as const)('keeps the displayed card in front when the next read leaves it %s', async (placement) => { + vi.useFakeTimers() + const { controller, read, displayed, stacks } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const next = ['second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: placement === 'reordered' ? [...next, ...batch('first', null).notifications] : next }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['first', 'second', 'third']) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second', 'third']) + controller.shown('second' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(2) + expect(displayed).toHaveBeenLastCalledWith('second') + } finally { + controller.end() + } +}) + +it.each(['elapsed', 'updated'] as const)('removes a displayed card whose expiration %s before the next read', async (expiration) => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-10-27T00:00:00Z')) + const { controller, read, stacks } = setup() + try { + read.mockResolvedValue(batch('first', '2026-10-28T00:00:00Z')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + if (expiration === 'elapsed') vi.setSystemTime(new Date('2026-10-28T00:00:00Z')) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...expiration === 'updated' ? batch('first', '2026-10-27T00:00:00Z').notifications : [], + ...batch('second', null).notifications, + ] }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second']) + } finally { + controller.end() + } +}) + +it('ignores a dismissal that names a notification the card does not show', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.dismiss('notice-2' as AccountNotificationId) + // The other notification's dismissal neither withdraws this card nor reports its display. + expect(latest()).toMatchObject({ id: 'notice-1' }) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays a notification offered again after a previous sign-in reported it', async () => { + const first = setup() + first.read.mockResolvedValue(batch('notice-1')) + first.controller.begin() + await vi.waitFor(() => { expect(first.latest()).toMatchObject({ id: 'notice-1' }) }) + first.controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(first.displayed).toHaveBeenCalledTimes(1) }) + first.controller.end() + // Nothing is remembered, so the same notification the server still offers displays again. + const second = setup() + second.read.mockResolvedValue(batch('notice-1')) + second.controller.begin() + await vi.waitFor(() => { expect(second.latest()).toMatchObject({ id: 'notice-1' }) }) + second.controller.end() +}) + +it('discards the previous account card when a credential is replaced without a signed-out frame', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockResolvedValue(false) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledOnce() }) + // The credential is replaced in place: another signed-in frame arrives, the read + // names the other account, and no signed-out frame ever describes the switch. + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('reports each new display of a notification offered again after dismissal', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + // Closing the card withdraws it; the next read of the same notification is a new card. + controller.dismiss('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + await controller.refresh() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(2) }) + controller.end() +}) + +it('keeps the visible card when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // A card the user has already seen keeps its place. + controller.shown('notice-1' as AccountNotificationId) + // A Settings entry whose read returns nothing must not pull the card out from under the user. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it('withdraws the displayed card when the signed-in account changes', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('never reports display after the plugin unloads', async () => { + vi.useFakeTimers() + const { controller, read, displayed } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(displayed).not.toHaveBeenCalled() +}) + +it('suppresses a notification that expired before its first presented frame', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1', '2000-01-01T00:00:00Z')) + controller.begin() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(1) }) + expect(latest()).toBeUndefined() + controller.end() +}) + +it('does not record a display when the award expired before the card could render', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + // The card refuses to render an expired award, so no display is reported. + controller.shown('notice-1' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays and reports a notice without expiration', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', displayUntil: null }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + controller.end() +}) + +it('publishes every live notice and reports display only for the foreground card', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + const notifications = ['first', 'second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toEqual(notifications) }) + controller.shown('second' as AccountNotificationId) + controller.dismiss('third' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + expect(stacks.at(-1)).toEqual(notifications) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledExactlyOnceWith('first') }) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(1)) + expect(displayed).toHaveBeenCalledTimes(1) + controller.shown('second' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenLastCalledWith('second') }) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(2)) + controller.dismiss('third' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed.mock.calls).toEqual([['first'], ['second'], ['third']]) + controller.end() +}) + +it('drops queued notices that expire before promotion without reporting display', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', null).notifications, + ...batch('expired', '2099-01-01T00:00:00Z').notifications, + ...batch('last', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(3) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['last']) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + controller.end() +}) + +it('publishes a title-only refresh without reporting the same display twice', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()?.id).toBe('first') }) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: batch('first', null).notifications.map(notice => ({ ...notice, title: 'Updated title' })) }) + await controller.refresh() + expect(latest()?.title).toBe('Updated title') + controller.shown('first' as AccountNotificationId) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('does not read or report display outside an active account lifecycle', async () => { + const { controller, read, displayed } = setup() + await controller.refresh() + expect(read).not.toHaveBeenCalled() + expect(displayed).not.toHaveBeenCalled() +}) + +it('closes the visible notice when the preceding card expires before its display callback', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', '2099-01-01T00:00:00Z').notifications, + ...batch('second', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(2) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('second') + controller.end() +}) + +it('refreshes a consumed card in place on language changes without another list or display report', async () => { + vi.useFakeTimers() + const { controller, read, readContent, displayed, latest } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const actions = [{ label: '知道了', style: 'secondary', target: { type: 'dismiss' } }] as const + readContent.mockResolvedValue(notification('first', { title: '通知', body: '新的中文内容', actions })) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()).toMatchObject({ id: 'first', title: '通知', body: '新的中文内容', actions }) + expect(read).toHaveBeenCalledTimes(1) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledTimes(1) + } finally { controller.end() } +}) + +it('ignores an earlier language response after a later language change', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const first = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(first.promise) + const changing = controller.setLocale('zh') + readContent.mockResolvedValueOnce(notification('first', { body: 'Latest English content' })) + await controller.setLocale('en') + first.resolve(notification('first', { body: '过时的中文内容' })) + await changing + expect(latest()?.body).toBe('Latest English content') + } finally { first.resolve(null); controller.end() } +}) + +it.each(['dismiss', 'sign-out', 'account-change'] as const)('does not restore content after %s', async (change) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(response.promise) + const changing = controller.setLocale('zh') + if (change === 'dismiss') controller.dismiss('first' as AccountNotificationId) + else if (change === 'sign-out') controller.end() + else { + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await Promise.resolve() + } + response.resolve(notification('first', { body: '迟到的内容' })) + await changing + expect(latest()?.id ?? null).toBe(change === 'account-change' ? 'second' : null) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['failure', 'absent'] as const)('retains the current content when localization returns %s', async (outcome) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (outcome === 'failure') readContent.mockRejectedValueOnce(new Error('private-detail')) + await controller.setLocale('zh') + expect(latest()?.body).toBe('Server copy 5.00') + expect(JSON.stringify(output.mock.calls)).not.toContain('private-detail') + expect(output).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + } finally { controller.end() } +}) + +it('localizes notifications returned by a list request started before the language changed', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockReturnValueOnce(response.promise) + controller.begin() + await controller.setLocale('zh') + expect(readContent).not.toHaveBeenCalled() + readContent.mockResolvedValueOnce(notification('first', { body: '当前语言内容' })) + response.resolve(batch('first', null)) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()?.body).toBe('当前语言内容') + } finally { response.resolve(null); controller.end() } +}) + +it('keeps localized copy while an older list response refreshes other notification fields', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest, published } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValueOnce(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + read.mockReturnValueOnce(response.promise) + const refreshing = controller.refresh() + readContent.mockResolvedValue(notification('first', { body: '新的中文内容' })) + await controller.setLocale('zh') + const count = published.length + response.resolve(batch('first', null)) + await refreshing + expect(latest()?.body).toBe('新的中文内容') + expect(published.slice(count).every(notice => notice?.body === '新的中文内容')).toBe(true) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['shown', 'before-frame'] as const)('reports an explicit dismissal once when closed %s', async (presentation) => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (presentation === 'shown') { + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() + } + controller.dismiss('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(presentation === 'shown' ? 1 : 0) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') +}) + +it.each(['expiry', 'account-change', 'sign-out', 'unload'] as const)('does not report dismissal on %s cleanup or from a stale callback', async (cleanup) => { + vi.useFakeTimers() + const { controller, read, dismissed } = setup() + const deadline = new Date(Date.now() + 100).toISOString() + read.mockResolvedValue(batch('first', cleanup === 'expiry' ? deadline : null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + if (cleanup === 'expiry') await vi.advanceTimersByTimeAsync(100) + else if (cleanup === 'account-change') { + controller.end() + read.mockResolvedValue(batch('second')) + controller.begin() + await Promise.resolve() + } else controller.end() + controller.dismiss('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('attempts each display and dismissal once after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + for (const report of [displayed, dismissed]) { + if (outcome === 'failure') report.mockRejectedValue(new Error('private-detail')) + else report.mockResolvedValue(outcome === 'success') + } + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + controller.begin() + await controller.refresh() + controller.shown('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(60_000) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 2 : 0) + expect(JSON.stringify(log.mock.calls)).not.toContain('private-detail') +}) + +it('reports the next card and dismissal without waiting for an earlier display report', async () => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue({ ...batch('first', null), notifications: [notification('first'), notification('second')] }) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + controller.shown('second' as AccountNotificationId) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + } finally { + pending.resolve(true) + await pending.promise + controller.end() + } +}) + +it.each(['success', 'failure'] as const)('ignores a late event %s after changing credentials', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('second' as AccountNotificationId) + if (outcome === 'success') pending.resolve(true) + else pending.reject(new Error('obsolete')) + await vi.advanceTimersByTimeAsync(60_000) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(log).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('reports a CTA click once without dismissing or retrying after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, clicked, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + if (outcome === 'failure') clicked.mockRejectedValue(new Error('offline')) + else clicked.mockResolvedValue(outcome === 'success') + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(60_000) + expect(clicked).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + controller.ctaClicked('first' as AccountNotificationId) + expect(clicked).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(0) +}) + +it('keeps dismissal available while a CTA-click report is pending', async () => { + vi.useFakeTimers() + const { controller, read, clicked, dismissed, latest } = setup() + const pending = Promise.withResolvers() + clicked.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + controller.dismiss('first' as AccountNotificationId) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(latest()).toBeNull() + } finally { + pending.resolve(true) + await pending.promise + } +}) + +it.each(['back-card', 'expired', 'signed-out'] as const)('ignores a CTA click from a %s notification', async (state) => { + vi.useFakeTimers() + const { controller, read, clicked } = setup() + read.mockResolvedValue({ ...batch('first', null), notifications: [ + notification('first', { displayUntil: '2099-01-01T00:00:00Z' }), notification('second'), + ] }) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (state === 'signed-out') controller.end() + else if (state === 'expired') vi.setSystemTime(new Date('2100-01-01T00:00:00Z')) + controller.ctaClicked((state === 'back-card' ? 'second' : 'first') as AccountNotificationId) + expect(clicked).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/notification-fixture.ts b/packages/client/ui-account-notifications/tests/notification-fixture.ts new file mode 100644 index 0000000000..d60b0da8dc --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-fixture.ts @@ -0,0 +1,15 @@ +/** Complete account notification values shared by presentation tests. */ +import type { AccountNotification, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' + +/** + * Create one notification without wire parsing or account lifecycle effects. + * @param id - stable notification identity. + * @param fields - scenario-specific notification fields. + * @returns localized display content with no actions or deadline unless supplied. + */ +export function notification(id: string, fields: Partial> = {}): AccountNotification { + return { + id: id as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Bonus credited', body: 'Server copy 5.00', actions: [], ...fields, + } +} diff --git a/packages/client/ui-account-notifications/tests/view.client.spec.tsx b/packages/client/ui-account-notifications/tests/view.client.spec.tsx new file mode 100644 index 0000000000..ff9d91438c --- /dev/null +++ b/packages/client/ui-account-notifications/tests/view.client.spec.tsx @@ -0,0 +1,36 @@ +// @vitest-environment jsdom +/** The menu extension preserves notifications while onboarding hides their presentation. */ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' +import { AccountNotifications, type AccountNotificationsProps } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' + +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) + +it('shows retained cards inside the menu and opens account settings without dismissing them', () => { + vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} }) + const notices = [notification('notice', { actions: [ + { label: 'View account', style: 'primary', target: { type: 'app_route', name: 'account' } }, + ] })] + const openAccount = vi.fn() + const dismiss = vi.fn() + const ctaClicked = vi.fn() + const props: AccountNotificationsProps = { + ...({} as GlobalStandardProps), active: false, openAccount, ctaClicked, dismiss, shown: vi.fn(), + useNotices: select => select(notices), t: () => 'Close', + } + const view = render() + expect(screen.queryByRole('status')).toBeNull() + view.rerender() + fireEvent.click(screen.getByRole('button', { name: 'View account' })) + expect(openAccount).toHaveBeenCalledOnce() + expect(ctaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(screen.getByRole('status')).toBeTruthy() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.queryByRole('status')).toBeNull() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.getByRole('button', { name: 'View account' })).toBeTruthy() +}) diff --git a/packages/client/ui-account-notifications/tsconfig.json b/packages/client/ui-account-notifications/tsconfig.json new file mode 100644 index 0000000000..3d18f2dc37 --- /dev/null +++ b/packages/client/ui-account-notifications/tsconfig.json @@ -0,0 +1,42 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-settings-account" + }, + { + "path": "../../credentials/deepseek-account" + }, + { + "path": "../../host/webserver" + }, + { + "path": "../ui-renderer" + } + ] +} diff --git a/packages/client/ui-account-notifications/tsdown.config.ts b/packages/client/ui-account-notifications/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-account-notifications/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index d92283aad2..d193002324 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -11,6 +11,7 @@ export const guideEn = { guideStandardExplanation: [ '### How it works', 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, and context compaction.', + 'For questions about DSH and plugin or preset work you request, the dsh-doc skill guides the agent to the installed documentation and source. Its instructions load only when requested or relevant; loading it does not change files, tools, or the profile.', '### When to choose it', 'Start here for everyday coding, file work, and research. Standard mode can also write scripts and process files in batches. PTC changes how tool calls are organized; it is not required for batch tasks.', ].join('\n\n'), @@ -54,7 +55,7 @@ export const guideEn = { guideCordisIntro: 'Choose Creator mode for a new task. Describe the capability you want, where it should appear, and how you will verify it.', guideCordisExplanation: [ '### What you can create', - 'Creator mode includes the standard task tools plus runtime inspection and guidance for authoring Cordis plugins and agent presets. It can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', + 'Creator mode includes the standard task tools and adds runtime inspection. Standard and Creator share the dsh-doc guidance for plugin and preset development. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', '### Plugins and modes', 'A plugin adds capabilities to DSH, such as a tool, a service connection, or a UI entry. A mode is an agent preset that selects tools and defines how the agent works in a task. A plugin can be included in a custom preset.', '### How the result takes effect', @@ -89,6 +90,7 @@ export const guideZh: Record = { guideStandardExplanation: [ '### 工作方式', 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理和上下文压缩等能力。', + '对于 DSH 相关问题以及你要求的插件或预设工作,dsh-doc skill 引导 Agent 查阅已安装的文档和源码。其指令仅在被要求加载或与当前任务相关时加载;加载该 skill 不会改变文件、工具或 profile。', '### 什么时候选', '日常编程、文件处理和资料整理可以从这里开始。标准模式也能编写脚本、批量处理文件;PTC 改变的是工具调用方式,批量任务并不必须使用 PTC。', ].join('\n\n'), @@ -132,7 +134,7 @@ export const guideZh: Record = { guideCordisIntro: '新建任务时选择「创造模式」,说明希望增加什么能力、从哪里使用,以及怎样验证效果。', guideCordisExplanation: [ '### 可以创造什么', - '创造模式具备标准任务工具,并增加运行时检查,以及 Cordis 插件和 Agent 预设的开发指引。可以编写插件来添加功能或界面,也可以组合工具和提示词,创建适合特定任务的模式。', + '创造模式包含标准任务工具,并增加了运行时检查。标准模式和创造模式共用 dsh-doc 指引,用于插件和预设开发。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', '### 插件与模式的关系', '插件为 DSH 增加能力,例如工具、服务连接或界面入口。模式是一份 Agent 预设,用来选择任务可用的工具,并约定 Agent 的工作方式。自定义模式中也可以使用自己开发的插件。', '### 怎样让成果生效', diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 2e047aefad..6ce0a71af9 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -33,11 +33,11 @@ en: 7cc6692b879aa500 zh: e924733c88b526c9 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: e2b02942a55fb669 - zh: a38bbee0cc69ae4e + en: f6d8bbae13a1a8f8 + zh: 96c8f400c215e33d /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: dd4e69828096c3a0 - zh: 2a9bc370f44efcd7 + en: 1b12aa6c505dde3b + zh: 88e1654dd63816d7 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 @@ -45,8 +45,8 @@ en: 15a7151ff9268f15 zh: 6eae68c718be579b /deepseek-ai-dsh-client-ui-chat/known-limitations-and-deferred-work: - en: 811787a5d2feaa90 - zh: 3f1697bbc1fc7691 + en: b3b03e8e2fe371a1 + zh: c5eb8b7205e0e880 /deepseek-ai-dsh-client-ui-chat/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 562ed7ebef..1a1869e4bd 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -127,7 +127,7 @@ Live tool deltas share reasoning's frame-batched publication; durable calls and The process group uses a stable `div` layout box, a scroll body, and an uncapped content box that reports growth inside the body. Business styles must adapt spacing within and across groups, including hidden or empty members and the answer-spacing exception. The `conversation.chat.flow` slot adds a `display: contents` DOM anchor; row selectors match that anchor directly, without repeating its column ancestry. The running status shares the rows' parent, so its divider uses the same visible-sibling rules. The anchor contributes no spacing of its own. The earlier-history control directly precedes the flow anchor; their sibling relationship supplies the leading gap. CSS variables do not belong in the Group Definition. -Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Ordinary flow rows sit 4px apart. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px from their input and from a directly following visible row. A reply that follows the control after folded rows keeps the 12px reply gap, so folding never changes its spacing. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it. +Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Ordinary flow rows sit 4px apart, including adjacent reasoning rows of one Assistant message. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px from their input and from a directly following visible row. A reply that follows the control after folded rows keeps the 12px reply gap, so folding never changes its spacing. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it. The running status shows a whale whose APNG mask inherits the text color. CSS selects the static SVG when reduced motion or forced colors are active, or alpha masks are unsupported. The APNG is a [package asset](../AGENTS.md#dependency-declaration) referenced by the plugin stylesheet; React does not pass image data through DOM styles. @@ -184,7 +184,9 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatViewport` owns turn-aware DOM reads, clamped writes, native events, and one retained paging anchor. For Load older, Node and Group seats mark eligible anchors from their existing disclosure state. The viewport selects the first nonempty, unhidden marker in transcript order without hit testing or geometry-based search, then measures that element and its scroll containers. It compensates the anchor's capped group first, then gives the remaining displacement to the transcript scrollport. An inner compensation write cancels that group's animation through its bound controller and pauses following; reader scrolling back to the bottom resumes it. Commits and later content resizes reuse that anchor; a remounted row is resolved by the same semantic key. Compensation stays within the actual scroll ranges without adding bottom space. -`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it; while a page is still loading, `scrollend` captures the reader's new position. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. +`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it. A deferred history request captures its anchor at consumption rather than at request time. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. + +History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and actual inner scrolling retain automatic intent before motion blockers are evaluated, then recheck after release; other active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Loading and processing buttons remain clickable, joining the current request without duplication. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation; once a page is available they bypass automatic blockers, use the first paging anchor at the top or the current reading anchor elsewhere with a paging fallback, and consume through existing preservation without waiting for animation completion. If no anchor is available, manual consumption still proceeds without a position guarantee. Automatic stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. For automatic consumption at scrollTop ≤ 0.5, the first paging anchor uses the same captured-screen-position restoration as persistent preservation, once, then releases immediately; it does not add scroll-position deltas that native anchoring may already have applied. The one-shot record is settled on history consumption completion even when the visible Node order stays unchanged; view closure or history failure discards it without application. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. @@ -211,6 +213,8 @@ None; Chat presentation does not assemble or mutate provider requests. +- **Manual paging during an active gesture** — manual consumption captures a persistent anchor when its page arrives, even if a touch gesture is already in progress. Subsequent movement can be restored to that anchor, constraining the gesture or its momentum until a new reading input releases it. The automatic touch deferral does not protect this explicit manual path. + - **Running-icon resolution** — the animated whale uses a 28×28 image at a default 14×14 CSS size. Larger content fonts or device pixel ratios above 2 can soften the raster stroke; the static fallback remains vector-based. Browser image caching owns the animation clock, so remounting does not guarantee playback restarts at the first frame. - **Tool-change presentation** — The `developer-message` Definition shares context presentation with `input-message`. Tool-only developer messages name a single added or removed tool inline without expansion. Multiple changes show added/removed counts and expand to comma-separated tool lists, one line per change kind. Mixed content uses the generic context presentation. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 7696d53951..8f2648fd2d 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -127,7 +127,7 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的 过程组使用稳定的 `div` 布局盒子、滚动正文及不限高的内容盒子,后者报告正文内部的内容增长。业务样式必须适配组内及组边界间距,处理隐藏或空成员以及回答前的间距特例。`conversation.chat.flow` 插槽添加一个 `display: contents` DOM 锚点;行选择器直接匹配该锚点,不重复匹配其正文容器祖先。运行状态与各行共享父级,使分隔线使用同一套可见兄弟节点规则。锚点自身不产生间距。更早历史控件紧邻流锚点之前,两者的兄弟关系决定首行间距。CSS 变量不属于 Group Definition。 -运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。普通流程行之间相隔 4px;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件与其输入、以及紧随其后的可见行之间保留 16px。控件与回复之间隔着已收起的行时,回复保持 12px 回复间距,因此折叠不会改变它的间距。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。 +运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。普通流程行之间相隔 4px,同一条 Assistant 消息里相邻的推理行也是如此;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件与其输入、以及紧随其后的可见行之间保留 16px。控件与回复之间隔着已收起的行时,回复保持 12px 回复间距,因此折叠不会改变它的间距。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。 运行状态显示一只鲸鱼,其 APNG 遮罩继承文字颜色。启用减少动态效果或强制颜色模式、或浏览器不支持 alpha 遮罩时,CSS 选择静态 SVG。APNG 是插件样式表引用的[包资源](../AGENTS.md#dependency-declaration);React 不通过 DOM 样式传递图片数据。 @@ -184,7 +184,9 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatViewport` 负责识别轮次的 DOM 读取、限制范围后的写入、原生事件及一个持续保留的分页锚点。加载更早时,Node 与 Group 容器根据已有开合状态标记可选锚点。视口按正文顺序选择第一个非空、未隐藏的标记,不做命中测试或按几何位置搜索,再测量该元素及其滚动容器。先补偿锚点所在的限高组,再把剩余位移交给整段文本的滚动区域。内层补偿写入通过该组绑定的控制器取消动画并暂停跟随,读者滚回底部后恢复。提交和后续内容尺寸变化复用该锚点;消息行重挂载时按同一语义 key 重新定位。补偿限于实际可滚动范围,不增加底部空白。 -`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点;分页仍在加载时,`scrollend` 会记录读者的新位置。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 +`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点。延迟消费的历史请求在消费时采集锚点,不在发请求时采集。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 + +历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和实际内层滚动优先于动画阻塞判断保留自动意图,释放后重查;其余动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。加载和处理状态的按钮仍可点击,加入当前请求而不重复请求。明确点击保留意图,直到消费、到头、失败或被新导航取代;页面可用后绕过自动阻塞,在顶部使用首条分页锚点,其他位置使用当前阅读锚点并以分页锚点兜底,通过既有保位消费,不等待动画结束。没有可用锚点时手动消费仍继续,但不保证位置稳定。自动静止消费使用保位,普通外层滚动使用浏览器锚定;自动消费在 scrollTop ≤ 0.5 时,首条分页锚点与持续保位共用采集屏幕位置的恢复公式,只应用一次便立即释放;不再叠加可能已由原生锚定产生的滚动位置增量。历史消费完成时,即使可见 Node 顺序未变化,也会结算一次补偿记录;视图关闭或历史失败时丢弃记录,不应用补偿。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 @@ -211,6 +213,8 @@ Markdown 文件、链接、图片、引用 chip 和工具文件控件将明确 +- **进行中手势遇到手动分页**——手动消费在页面到达时采集持续保位锚点,即使触摸手势已经开始。随后移动可能被恢复到该锚点,约束手势或其惯性,直到新的阅读输入释放锚点。自动路径的触摸延迟不保护这一明确的手动路径。 + - **运行图标分辨率**——动态鲸鱼使用 28×28 图片,默认 CSS 尺寸为 14×14。较大的正文字号或大于 2 的设备像素比可能使位图描边变模糊;静态回退图标仍为矢量图。浏览器图片缓存管理动画时钟,因此重新挂载不保证从第一帧重新播放。 - **工具变更展示** — `developer-message` Definition 与 `input-message` 共用上下文展示。仅包含工具变更的 developer 消息在单个工具新增或移除时直接显示工具名,不提供展开操作。多个变更显示新增、移除数量,展开后按变更类型分别以逗号分隔显示一行工具列表。混合内容使用通用上下文展示。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 084e45e414..7e4a3a5f01 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -287,7 +287,8 @@ export function apply(ctx: Context): void { window.open(url, '_blank', 'noopener,noreferrer') } }, - loadOlder: () => { void session.loadOlder() }, + loadOlder: () => { void session.loadOlder({ deferConsumption: true }) }, + consumeOlder: () => session.consumeOlder(), loadThrough: seq => session.loadThrough(seq), loadImage: Object.assign( (attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment), diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css index 990aa985f6..6441ce20c6 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css @@ -15,9 +15,17 @@ } .body { + --dsh-assistant-block-gap: 16px; display: flex; flex-direction: column; - gap: 16px; + gap: var(--dsh-assistant-block-gap); +} + +/* A step-group reasoning part (its Chat seat carries data-chat-group-part) + holds only reasoning rows, which are process rows: they sit 4px apart, like + rows of different steps. */ +:global([data-chat-group-part="reasoning"]) .body { + --dsh-assistant-block-gap: 4px; } /* Wide markdown tables (the renderer's ≥4-column md-table-wide hook) span @@ -50,11 +58,13 @@ z-index: 1; } -/* hidden="until-found" keeps a zero-height reasoning box in flex layout. - Cancel the one gap that box would otherwise leave before the visible reply; - visible Assistant blocks retain the ordinary 16px rhythm. */ -.body > [data-turn-process-inline][hidden] { - margin-bottom: -16px; +/* hidden="until-found" keeps a zero-height reasoning box in flex layout, and + so does the class-less wrapper of a reasoning block whose row renders + nothing (signature-only reasoning has no display text). Cancel the one gap + each box would otherwise leave. */ +.body > [data-turn-process-inline][hidden], +.body > :empty:not([class]) { + margin-bottom: calc(-1 * var(--dsh-assistant-block-gap)); } /* Interrupted-turn terminal marker: quiet inline tag, no animation. Fixed diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 9929770b35..1f84e97842 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -37,6 +37,11 @@ container-type: inline-size; } +.scroll, +:global([data-conversation-scroll]):has(.root) { + overscroll-behavior-y: none; +} + .root[data-chat-following-tail] .scroll, :global([data-conversation-scroll]):has(.root[data-chat-following-tail]) { overflow-anchor: none; @@ -318,11 +323,15 @@ } .older { + overflow-anchor: none; display: flex; justify-content: center; } .older button { + display: grid; + line-height: 18px; + white-space: nowrap; border: none; border-radius: var(--dsw-radius-sm); padding: 4px 12px; @@ -332,6 +341,14 @@ cursor: pointer; } +.older button > span { + grid-area: 1 / 1; +} + +.historyHidden { + visibility: hidden; +} + .older button:disabled { cursor: default; opacity: 0.6; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 48e081bfa8..c9143248a1 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -63,7 +63,7 @@ const MOTION_TAIL_MS = 800 export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu, - loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, + loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag, }: ChatViewSlotProps) { const { getTriggerProps } = useContextMenu() @@ -136,6 +136,8 @@ export function ChatView({ const openError = useSession(s => s.openError) const hasMore = useSession(s => s.hasMore) const loadingOlder = useSession(s => s.loadingOlder) + const historyLoadStatus = useSession(s => s.historyLoadStatus) + const historyWasPartial = useSession(s => s.historyWasPartial) const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null) const [fileOpenBusy, setFileOpenBusy] = useState(false) // Close/retry must ignore a settlement that started before the latest @@ -211,8 +213,9 @@ export function ChatView({ const steeringId = latestSteering?.source.kind === 'user' && 'rpcId' in latestSteering.source ? latestSteering.source.rpcId : latestSteering?.id ?? null const scroll = useChatScroll({ - ready: openState === 'open', - order, firstSeq, lastKey, running, loadingOlder, hasMore, chatScroll, loadOlder, loadThrough, deferCompletedTurns, + isOpen: openState === 'open', + order, firstSeq, lastKey, running, loadingOlder, historyLoadStatus, hasMore, chatScroll, + loadOlder, consumeOlder, loadThrough, deferCompletedTurns, lastIsUser: lastKey !== null && nodeStore.get(lastKey)?.kind === 'user', steeringId, submissionId: visibleSubmissions.at(-1)?.requestId ?? null, @@ -247,10 +250,24 @@ export function ChatView({ {t('chat.loadError', { message: openError.message, code: openError.code })}
)} - {hasMore && ( -
-
)} diff --git a/packages/client/ui-chat/src/client/chat/flow-motion.ts b/packages/client/ui-chat/src/client/chat/flow-motion.ts index b34c1f2645..7deddd0e9a 100644 --- a/packages/client/ui-chat/src/client/chat/flow-motion.ts +++ b/packages/client/ui-chat/src/client/chat/flow-motion.ts @@ -72,6 +72,8 @@ export interface InputFoldDriver { /** Animation lifetime and fold coordination for one viewport. */ export interface FlowMotion extends FlowMotionRows { + /** @returns whether owned transitions or a scheduled, running, or settling batch remain active. */ + active(): boolean /** @returns whether a row owned by this viewport is closing. */ foldActive(): boolean /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */ @@ -494,6 +496,7 @@ export function createFlowMotion( return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, cancelInput, resumeInput, clear, hideNow, + active: () => running.size > 0 || batchScheduled || batch || settling, inputActive: () => batch || (batchScheduled && [...boxes.values()].some(box => box.closing && batchMember(box))), } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts index 84e2b3ec77..f2c9aaeada 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts @@ -1,5 +1,6 @@ /** Turn jumps and history-prepend anchoring, independent of DOM measurement. */ import { useLayoutEffect, useState } from 'react' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionSeq } from '@deepseek-ai/dsh-session/types' import type { ChatNode } from '../contract/chat-nodes.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -8,10 +9,12 @@ import type { ChatReading, ReadingSample } from './use-chat-reading.ts' import type { ChatViewport } from './use-chat-viewport.ts' /** History availability and loading operations for the committed Chat window. */ -export interface ChatNavigationInput extends Pick { +export interface ChatNavigationInput extends Pick { readonly firstSeq: ChatNode['anchorSeq'] | null readonly hasMore: boolean readonly loadingOlder: boolean + readonly historyLoadStatus: SessionSnapshot['historyLoadStatus'] + readonly isOpen: boolean } interface TurnJump { @@ -22,23 +25,33 @@ interface TurnJump { repageHead: ChatNavigationInput['firstSeq'] } +type HistoryIntent = 'none' | 'auto' | 'manual' + /** Owns one replaceable turn jump and the anchor retained while history loads. */ export class ChatNavigation { private jump: TurnJump | null = null private settleFrame: number | null = null + private historyFrame: number | null = null + private historyIntent: HistoryIntent = 'none' + private historyRequested = false constructor( private readonly viewport: ChatViewport, private readonly reading: ChatReading, private input: ChatNavigationInput, private readonly onBusyTurn: (turn: number | null) => void, + private readonly onHistoryIntent: (intent: HistoryIntent) => void = () => {}, ) {} /** * Adopt committed history availability without starting a request. * @param input - history state from the latest committed render. */ - setInput(input: ChatNavigationInput): void { this.input = input } + setInput(input: ChatNavigationInput): void { + this.input = input + this.historyRequested = false + if (!input.isOpen || input.historyLoadStatus === 'error' || !input.hasMore) this.setHistoryIntent('none') + } /** Cancel navigation when opening a Chat view. */ reset(): void { @@ -48,10 +61,19 @@ export class ChatNavigation { /** Cancel local callbacks; late history completions cannot revive a task. */ dispose(): void { this.clearTask() + if (this.historyFrame !== null) cancelAnimationFrame(this.historyFrame) + this.historyFrame = null } /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */ cancel(): void { + this.setHistoryIntent('none') + this.clearTask() + this.onBusyTurn(null) + } + + /** Release a jump after reader input without cancelling an accepted history click. */ + readerInteracted(): void { this.clearTask() this.onBusyTurn(null) } @@ -60,6 +82,7 @@ export class ChatNavigation { this.cancelFrame() this.jump = null this.viewport.stopPreserving() + this.viewport.cancelHistoryPrepend() } /** @@ -90,12 +113,98 @@ export class ChatNavigation { this.request(jump) } - /** Request one older page while retaining the current semantic position. */ + /** Request and consume one page, retaining the click until success, exhaustion, or failure. */ readonly loadEarlier = (): void => { this.cancel() - this.viewport.beginPaging() + this.setHistoryIntent('manual') this.reading.pauseFollowing() - this.input.loadOlder() + if (this.input.historyLoadStatus === 'error') { + this.historyRequested = true + this.input.loadOlder() + } else this.requestHistoryCheck() + } + + private setHistoryIntent(intent: HistoryIntent): void { + if (intent === this.historyIntent) return + this.historyIntent = intent + this.onHistoryIntent(intent) + } + + /** Coalesce event-driven checks; waiting never schedules its own next frame. */ + requestHistoryCheck(): void { + if (!this.input.isOpen || this.input.historyLoadStatus === 'error') return + if (this.historyIntent === 'none' && (this.input.historyLoadStatus !== 'idle' + || !this.input.hasMore || this.reading.followingTail)) return + if (this.historyFrame !== null || typeof requestAnimationFrame !== 'function') return + this.historyFrame = requestAnimationFrame(() => { + this.historyFrame = null + this.checkHistory() + }) + } + + private checkHistory(): void { + const input = this.input + if (!input.isOpen || this.jump !== null || this.historyRequested || input.loadingOlder) return + if (input.historyLoadStatus === 'error') return + if (input.historyLoadStatus === 'pendingConsumption') { + if (this.historyIntent === 'none') return + if (this.reading.followingTail && this.historyIntent === 'auto') { + this.setHistoryIntent('none') + return + } + if (this.historyIntent === 'manual') { + this.viewport.beginManualPaging() + this.reading.pauseFollowing() + this.consumeHistory('preserve') + return + } + const mode = this.viewport.historyConsumption() + switch (mode) { + case 'touch': + case 'inner-scroll': + return + case 'motion': + case 'pointer': + case 'unavailable': + this.setHistoryIntent('none') + return + case 'prepend': + if (!this.viewport.beginHistoryPrepend() && input.firstSeq !== null) { + this.setHistoryIntent('none') + return + } + break + case 'preserve': + case 'native': + break + } + if (mode === 'preserve') { + this.viewport.beginPreserving() + if (!this.viewport.preserving) this.viewport.beginPaging() + if (!this.viewport.preserving && input.firstSeq !== null) { + this.setHistoryIntent('none') + return + } + this.reading.pauseFollowing() + } + this.consumeHistory(mode) + return + } + if (!input.hasMore || this.historyIntent !== 'manual' && (this.reading.followingTail + || !this.viewport.confirmHistoryStart())) return + if (this.historyIntent === 'none') this.setHistoryIntent('auto') + this.historyRequested = true + input.loadOlder() + } + + private consumeHistory(mode: 'native' | 'preserve' | 'prepend'): void { + this.historyRequested = true + if (this.input.consumeOlder()) this.setHistoryIntent('none') + else { + this.historyRequested = false + if (mode === 'preserve') this.viewport.stopPreserving() + if (mode === 'prepend') this.viewport.cancelHistoryPrepend() + } } /** @@ -120,13 +229,6 @@ export class ChatNavigation { return true } - /** Retarget a still-loading page only after inner or outer reader scrolling ends. */ - readerSettled(): void { - if (this.input.loadingOlder && this.jump === null && !this.viewport.preserving && !this.reading.followingTail) { - this.viewport.beginPreserving() - } - } - /** Land, retry, or complete the current jump against the committed window. */ reconcile(): void { const jump = this.jump @@ -197,10 +299,11 @@ export class ChatNavigation { */ export function useChatNavigation( viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput, -): { navigation: ChatNavigation; busyTurn: number | null } { +): { navigation: ChatNavigation; busyTurn: number | null; historyPending: boolean; historyProcessing: boolean } { const [busyTurn, setBusyTurn] = useState(null) - const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn)) + const [historyIntent, setHistoryIntent] = useState('none') + const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn, setHistoryIntent)) useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input]) useLayoutEffect(() => () => { navigation.dispose() }, [navigation]) - return { navigation, busyTurn } + return { navigation, busyTurn, historyPending: historyIntent === 'manual', historyProcessing: historyIntent !== 'none' } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts index 7924a33e3f..211b3cbd9b 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts @@ -1,5 +1,5 @@ /** Composes viewport operations, reading policy, and history navigation for Chat. */ -import { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react' +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react' import type { TranscriptViewMode } from '../../chat-settings.ts' import type { ChatSnapshot } from '../contract/snapshot.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -11,7 +11,6 @@ import type { FlowMotionRows } from './flow-motion.ts' /** Committed content and Session operations used to reconcile scroll ownership. */ export interface ChatScrollInput extends ChatNavigationInput { readonly chatScroll: ChatViewSlotProps['chatScroll'] - readonly ready: boolean readonly order: readonly string[] readonly lastKey: string | null readonly lastIsUser: boolean @@ -33,12 +32,16 @@ interface ChatScrollState extends ChatReadingState { readonly busyTurn: number | null readonly navigateToTurn: ChatNavigation['navigateToTurn'] readonly loadEarlier: ChatNavigation['loadEarlier'] + readonly historyInputHeld: boolean + readonly historyProcessing: boolean + readonly historyPending: boolean + readonly historyEdgeRef: (element: HTMLDivElement | null) => void readonly returnToBottom: () => void readonly motion: FlowMotionRows } /** - * Coordinate scroll policy after Chat content commits. Initial history must be ready + * Coordinate scroll policy after Chat content commits. Initial history must be available * before automatic scroll or resize handling can initialize reading state and fold motion. * New submitted input supersedes pending reader sampling. * @param input - current Chat content, scroll memory, and history operations. @@ -46,15 +49,17 @@ interface ChatScrollState extends ChatReadingState { */ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const { - ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, - deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough, transcriptView, + isOpen, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, + deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, historyLoadStatus, + loadOlder, consumeOlder, loadThrough, transcriptView, } = input const { viewport, listRef, columnRef } = useChatViewport() + const [historyInputHeld, setHistoryInputHeld] = useState(false) const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null) const navigationInput = useMemo(() => ({ - firstSeq, loadingOlder, hasMore, loadOlder, loadThrough, - }), [firstSeq, loadingOlder, hasMore, loadOlder, loadThrough]) - const { navigation, busyTurn } = useChatNavigation(viewport, reading, navigationInput) + firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough, + }), [firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough]) + const { navigation, busyTurn, historyPending, historyProcessing } = useChatNavigation(viewport, reading, navigationInput) const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({ input, applied: null, opened: false, }) @@ -64,7 +69,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const processContent = useCallback(() => { const current = content.current.input - if (!current.ready && !content.current.opened) return + if (!current.isOpen && !content.current.opened) return const previous = content.current.applied const steeringInput = current.steeringId !== null && current.steeringId !== previous?.steeringId && current.steeringId !== previous?.submissionId @@ -73,7 +78,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey) || steeringInput || submissionInput if (reading.pending && !ownInput) return content.current.applied = current - if (current.ready && !content.current.opened) { + if (current.isOpen && !content.current.opened) { content.current.opened = true navigation.reset() reading.restore() @@ -92,7 +97,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { navigation.reconcile() return } - const tipChanged = previous === null || current.ready !== previous.ready + const tipChanged = previous === null || current.isOpen !== previous.isOpen || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey || current.order.length !== previous.order.length || current.running !== previous.running || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId @@ -112,12 +117,17 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { }, scrollEnd: (outer) => { reading.onScrollEnd(outer) - navigation.readerSettled() + navigation.requestHistoryCheck() + }, + interact: () => { navigation.readerInteracted() }, + history: () => { + setHistoryInputHeld(viewport.historyInputHeld) + if (content.current.opened) navigation.requestHistoryCheck() }, - interact: () => { navigation.cancel() }, intent: () => { cancelPendingFollow(); reading.interruptFollow() }, resize: () => { if (!content.current.opened) return + navigation.requestHistoryCheck() if (navigation.contentCommitted()) { navigation.reconcile() return @@ -129,6 +139,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const disconnectReading = reading.connect((sample) => { navigation.readerSampled(sample) processContent() + navigation.requestHistoryCheck() }) return () => { disconnectViewport() @@ -141,7 +152,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { useLayoutEffect(() => { const previous = content.current.input content.current.input = { - ready, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, + order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, ...navigationInput, } if (!deferCompletedTurns) { @@ -149,13 +160,20 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { reading.interruptFollow() } viewport.updateTurns(loadedTurns) - const layoutChanged = previous.order !== order || previous.ready !== ready + const layoutChanged = previous.order !== order || previous.isOpen !== isOpen + const historyConsumed = previous.historyLoadStatus === 'pendingConsumption' && historyLoadStatus === 'idle' + if (!isOpen || historyLoadStatus === 'error') viewport.cancelHistoryPrepend() + else if (layoutChanged || historyConsumed) { + const landing = viewport.finishHistoryPrepend() + if (landing !== null) reading.preservePosition(landing) + } if (layoutChanged) viewport.invalidate() viewport.reclaimBelow() processContent() if (layoutChanged && content.current.opened) reading.refreshActiveTurn() + if (content.current.opened) navigation.requestHistoryCheck() }, [ - viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser, + viewport, reading, processContent, navigationInput, isOpen, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, cancelPendingFollow, ]) @@ -182,6 +200,10 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { listRef, columnRef, ...state, busyTurn, motion: viewport.motion, navigateToTurn: navigation.navigateToTurn, loadEarlier: navigation.loadEarlier, + historyPending, + historyProcessing, + historyInputHeld, + historyEdgeRef: viewport.setHistoryEdge, returnToBottom, } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index b0dbf7528a..afc071ae22 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -26,6 +26,8 @@ interface ViewportEvents { interact: () => void /** Any reading gesture, before paging ownership is consulted. */ intent?: () => void + /** Recheck a prepared history page after an input or transition settles. */ + history?: () => void } interface ViewportElements { @@ -79,7 +81,13 @@ export class ChatViewport { private turns: ReturnType = [] private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null } private paging: PagingPosition | null = null + private historyPrepend: PagingPosition | null = null private reader: FoldReader | null = null + private historyEdge: HTMLElement | null = null + private historyHeight = 0 + private historyScrolling = new Set() + private historyPointer = false + private historyTouch = false /** Rows measured before an instant close; see {@link ChatViewport.keepAboveClosing}. */ private closing: ClosingLayout | null = null /** Discards a closing measurement that no size observation consumed by the end of its frame. */ @@ -114,18 +122,26 @@ export class ChatViewport { const elements = { list, column, scroller, composer, spacer } this.elements = elements if (spacer !== null) spacer.style.height = '' + scroller.addEventListener('scroll', this.onHistoryScroll, { passive: true, capture: true }) + scroller.addEventListener('pointerdown', this.onHistoryPointerDown, { passive: true, capture: true }) + scroller.addEventListener('touchstart', this.onHistoryTouch, { passive: true, capture: true }) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller.ownerDocument.addEventListener(type, this.onHistoryRelease, true) + } scroller.addEventListener('scroll', this.onScroll, { passive: true }) scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true }) for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true }) if (typeof ResizeObserver !== 'undefined') { - this.observer = new ResizeObserver(() => { + this.observer = new ResizeObserver((entries) => { if (this.elements !== elements) return // Read while layout is still clean, before this callback writes room or scroll positions. Those writes // leave the content height unchanged, so it is also the content this frame paints. + if (entries.some(entry => entry.target === elements.scroller)) this.historyHeight = elements.scroller.clientHeight this.settledContent = elements.scroller.scrollHeight - this.spacerHeight() this.keepAboveClosing() this.reclaimBelow() this.invalidate() + this.pruneHistoryScrolling() this.events?.resize() }) this.observer.observe(column) @@ -136,10 +152,22 @@ export class ChatViewport { /** Disconnect DOM resources and clear observations for the detached view. */ detach(): void { + this.historyPrepend = null this.stopPreserving() this.motion.clear() if (this.elements !== null) this.elements.scroller.style.overflowAnchor = '' this.dropClosing() + const scroller = this.elements?.scroller + scroller?.removeEventListener('scroll', this.onHistoryScroll, true) + scroller?.removeEventListener('pointerdown', this.onHistoryPointerDown, true) + scroller?.removeEventListener('touchstart', this.onHistoryTouch, true) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller?.ownerDocument.removeEventListener(type, this.onHistoryRelease, true) + } + this.historyHeight = 0 + this.historyScrolling.clear() + this.historyPointer = false + this.historyTouch = false this.elements?.scroller.removeEventListener('scroll', this.onScroll) this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true) for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true) @@ -769,13 +797,27 @@ export class ChatViewport { return metrics === null ? null : this.write(position.scrollTop, metrics, null) } + /** Capture a manual paging anchor without consulting automatic-consumption blockers. */ + beginManualPaging(): void { + if (this.elements === null) return + if (this.elements.scroller.scrollTop <= 0.5) this.beginPaging() + else { + this.beginPreserving() + if (!this.preserving) this.beginPaging() + } + } + /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */ beginPaging(): void { this.stopPreserving() - const row = this.elements?.list.querySelector( + const row = this.pagingAnchor() + if (row !== null) this.retain(row) + } + + private pagingAnchor(): HTMLElement | null { + return this.elements?.list.querySelector( '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)', - ) - if (row != null) this.retain(row) + ) ?? null } /** @@ -790,18 +832,16 @@ export class ChatViewport { this.retain(row, position) } - private retain(row: HTMLElement, position?: ChatScrollPosition, groupTop?: number): PagingPosition | null { + private measurePaging(row: HTMLElement, position?: ChatScrollPosition, previousGroup?: PagingPosition['group']): PagingPosition | null { const elements = this.elements const key = row.dataset.chatAnchorKey if (elements === null || key === undefined) return null - const previous = this.paging?.group - if (previous != null) this.observer?.unobserve(previous.content) const top = row.getBoundingClientRect().top const body = row.closest('[data-step-process-body]') const content = body?.querySelector('[data-step-process-content]') const group = body === null || content == null ? null - : { body, content, top: groupTop ?? top - body.getBoundingClientRect().top } - this.paging = { + : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top } + return { row, group, position: position ?? { anchorKey: key, @@ -809,8 +849,19 @@ export class ChatViewport { scrollTop: elements.scroller.scrollTop, }, } - if (group !== null) this.observer?.observe(group.content) - return this.paging + } + + private retain(row: HTMLElement, position?: ChatScrollPosition): PagingPosition | null { + const paging = this.measurePaging(row, position) + if (paging === null) return null + this.retainPaging(paging) + return paging + } + + private retainPaging(paging: PagingPosition): void { + this.stopPreserving() + this.paging = paging + if (paging.group !== null) this.observer?.observe(paging.group.content) } /** Release paging ownership and its content-size observation. */ @@ -832,24 +883,33 @@ export class ChatViewport { * @returns the actual landing, or null when no visible retained row remains. */ preserve(): ViewportLanding | null { - let paging = this.paging + const paging = this.resolvePaging(this.paging) + if (paging === null) { + this.stopPreserving() + return null + } + if (paging !== this.paging) this.retainPaging(paging) + return this.applyPaging(paging) + } + + private resolvePaging(paging: PagingPosition | null): PagingPosition | null { const elements = this.elements if (paging === null || elements === null) return null if (!elements.list.contains(paging.row)) { // Segmentation can remount the same semantic row under another group. const replacement = this.anchor(paging.position.anchorKey) - if (replacement === null) { - this.stopPreserving() - return null - } - paging = this.retain(replacement, paging.position, paging.group?.top) + if (replacement === null) return null + paging = this.measurePaging(replacement, paging.position, paging.group) if (paging === null) return null } + return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging + } + + /** Restore the captured screen position; native anchoring already applied to this change needs no further correction. */ + private applyPaging(paging: PagingPosition): ViewportLanding | null { + const elements = this.elements + if (elements === null) return null const { row, group, position } = paging - if (row.closest('[hidden]') !== null || row.matches(':empty')) { - this.stopPreserving() - return null - } if (group !== null && group.body.contains(row)) { const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top const metrics = scrollMetrics(group.body) @@ -919,6 +979,103 @@ export class ChatViewport { return landing } + /** + * Track the history control for request-distance checks. + * @param element - stable history control, or null when its view unmounts. + */ + readonly setHistoryEdge = (element: HTMLDivElement | null): void => { + this.historyEdge = element + } + + private pruneHistoryScrolling(): void { + for (const target of this.historyScrolling) { + if (!(target instanceof HTMLElement) || this.elements?.scroller.contains(target) !== true) { + this.historyScrolling.delete(target) + } + } + } + + /** + * Confirm the actual history distance immediately before an automatic request. + * @returns whether the control is within two viewport heights. + */ + confirmHistoryStart(): boolean { + const scroller = this.elements?.scroller + if (scroller === undefined || this.historyEdge === null || this.historyHeight <= 0) return false + const distance = scroller.getBoundingClientRect().top - this.historyEdge.getBoundingClientRect().bottom + return distance <= this.historyHeight * 2 + } + + /** + * Expose held input to history status copy. + * @returns whether a touch or pointer remains down. + */ + get historyInputHeld(): boolean { return this.historyTouch || this.historyPointer } + + /** + * Select consumption behavior from current input and motion state. + * @returns the blocker or positioning path for a prepared page. + */ + historyConsumption(): 'motion' | 'touch' | 'pointer' | 'inner-scroll' | 'unavailable' | 'native' | 'preserve' | 'prepend' { + const elements = this.elements + if (elements === null) return 'unavailable' + if (this.historyTouch) return 'touch' + if (this.historyScrolling.size > 0 + && (this.historyScrolling.size !== 1 || !this.historyScrolling.has(elements.scroller))) return 'inner-scroll' + if (this.motion.active() || this.reader?.follow.animating) return 'motion' + if (this.historyPointer) return 'pointer' + if (this.historyScrolling.size === 0) return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'preserve' + if (this.preserving || typeof CSS === 'undefined' || !CSS.supports('overflow-anchor', 'auto')) return 'unavailable' + return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'native' + } + + /** + * Capture one top-edge prepend anchor without acquiring continuous scroll ownership. + * @returns whether an old paging row was captured. + */ + beginHistoryPrepend(): boolean { + const row = this.pagingAnchor() + this.historyPrepend = row === null ? null : this.measurePaging(row) + return this.historyPrepend !== null + } + + /** Clear an unapplied one-shot correction when its page was not consumed. */ + cancelHistoryPrepend(): void { this.historyPrepend = null } + + /** + * Correct a committed prepend once, then release positioning ownership. + * @returns the compensated landing for reading memory, or null when no anchor remains. + */ + finishHistoryPrepend(): ViewportLanding | null { + const pending = this.historyPrepend + this.historyPrepend = null + const paging = this.resolvePaging(pending) + return paging === null ? null : this.applyPaging(paging) + } + + private readonly onHistoryScroll = (event: Event): void => { + if (event.target === this.elements?.scroller || event.target instanceof HTMLElement + && event.target.hasAttribute('data-step-process-body')) { + this.historyScrolling.add(event.target) + } + } + + private readonly onHistoryPointerDown = (): void => { + this.historyPointer = true + this.events?.history?.() + } + private readonly onHistoryTouch = (): void => { + this.historyTouch = true + this.events?.history?.() + } + private readonly onHistoryRelease = (event: Event): void => { + if (event.type === 'pointerup' || event.type === 'pointercancel') this.historyPointer = false + if (event.type === 'touchend' || event.type === 'touchcancel') { + this.historyTouch = typeof TouchEvent !== 'undefined' && event instanceof TouchEvent && event.touches.length > 0 + } + this.events?.history?.() + } + private readonly onScroll = (event: Event): void => { if (this.elements === null || event.target !== this.elements.scroller) return if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return @@ -932,6 +1089,8 @@ export class ChatViewport { } private readonly onScrollEnd = (event: Event): void => { + if (event.target !== null) this.historyScrolling.delete(event.target) + this.events?.history?.() if (event.target === this.elements?.scroller) { this.events?.scrollEnd(true) this.reclaimBelow() diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index ed89452f50..676bb3fb2d 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -347,7 +347,10 @@ export interface ChatViewInjected { /** Open one HTTP(S) message link at the selected destination, using an external tab if Sidebar Browser is unavailable. */ openExternalLink: (url: string) => void openFile: (path: string, options?: OpenFileOptions) => Promise + /** Prepare one older page without publishing it. */ loadOlder: () => void + /** Consume the prepared page synchronously; false when none is ready. */ + consumeOlder: () => boolean /** Jump loader: page history back through seq; resolves when the window covers it. */ loadThrough: (seq: SessionSeq) => Promise loadImage: MessageImageLoader diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 0b2bc2151d..4d22cff80e 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -92,6 +92,10 @@ export const zh = { 'chat.loadingHistory': '载入历史…', 'chat.loadError': '历史加载失败:{message}({code})', 'chat.loadOlder': '加载更早', + 'chat.loadingOlder': '正在加载', + 'chat.processingOlder': '正在处理', + 'chat.retryOlder': '重新加载', + 'chat.historyStart': '已到会话开头', 'chat.toBottom': '回到底部', 'chat.deepDiving': '深度求索中', 'chat.deepDivingFor': '深度求索中,用时 {duration} ···', @@ -302,6 +306,10 @@ export const en = { 'chat.loadingHistory': 'Loading history…', 'chat.loadError': 'Failed to load history: {message} ({code})', 'chat.loadOlder': 'Load earlier', + 'chat.loadingOlder': 'Loading earlier', + 'chat.processingOlder': 'Processing', + 'chat.retryOlder': 'Retry loading', + 'chat.historyStart': 'Start of conversation', 'chat.toBottom': 'Back to bottom', 'chat.deepDiving': 'Deep diving', 'chat.deepDivingFor': 'Deep diving for {duration} ···', @@ -509,6 +517,10 @@ export const ja = { 'chat.loadingHistory': '履歴を読み込み中…', 'chat.loadError': '履歴の読み込みに失敗しました: {message}({code})', 'chat.loadOlder': '以前を読み込む', + 'chat.loadingOlder': '読み込み中', + 'chat.processingOlder': '処理中', + 'chat.retryOlder': '再読み込み', + 'chat.historyStart': '会話の先頭です', 'chat.toBottom': '最下部へ戻る', 'chat.deepDiving': '深掘り中', 'chat.deepDivingFor': '{duration} の間深く分析中 ···', @@ -716,6 +728,10 @@ export const es = { 'chat.loadingHistory': 'Cargando historial…', 'chat.loadError': 'No se pudo cargar el historial: {message} ({code})', 'chat.loadOlder': 'Cargar antes', + 'chat.loadingOlder': 'Cargando anteriores', + 'chat.processingOlder': 'Procesando', + 'chat.retryOlder': 'Reintentar carga', + 'chat.historyStart': 'Inicio de la conversación', 'chat.toBottom': 'Volver al fondo', 'chat.deepDiving': 'Razonamiento profundo', 'chat.deepDivingFor': 'Razonando a fondo durante {duration} ···', @@ -923,6 +939,10 @@ export const fr = { 'chat.loadingHistory': "Chargement de l'historique…", 'chat.loadError': "Échec du chargement de l'historique : {message} ({code})", 'chat.loadOlder': 'Charger plus tôt', + 'chat.loadingOlder': 'Chargement en cours', + 'chat.processingOlder': 'Traitement en cours', + 'chat.retryOlder': 'Réessayer', + 'chat.historyStart': 'Début de la conversation', 'chat.toBottom': 'Retour en bas', 'chat.deepDiving': 'Réflexion approfondie', 'chat.deepDivingFor': 'Réflexion approfondie depuis {duration} ···', @@ -1130,6 +1150,10 @@ export const de = { 'chat.loadingHistory': 'Verlauf wird geladen…', 'chat.loadError': 'Fehler beim Laden des Verlaufs: {message} ({code})', 'chat.loadOlder': 'Früher laden', + 'chat.loadingOlder': 'Wird geladen', + 'chat.processingOlder': 'Wird verarbeitet', + 'chat.retryOlder': 'Erneut laden', + 'chat.historyStart': 'Anfang der Unterhaltung', 'chat.toBottom': 'Zurück nach unten', 'chat.deepDiving': 'Gründliches Nachdenken', 'chat.deepDivingFor': 'Gründliches Nachdenken seit {duration} ···', @@ -1337,6 +1361,10 @@ export const ru = { 'chat.loadingHistory': 'Загрузка истории…', 'chat.loadError': 'Не удалось загрузить историю: {message} ({code})', 'chat.loadOlder': 'Загрузить раньше', + 'chat.loadingOlder': 'Загрузка истории', + 'chat.processingOlder': 'Обработка', + 'chat.retryOlder': 'Повторить загрузку', + 'chat.historyStart': 'Начало разговора', 'chat.toBottom': 'Вернуться к низу', 'chat.deepDiving': 'Глубокое размышление', 'chat.deepDivingFor': 'Глубокое размышление в течение {duration} ···', @@ -1544,6 +1572,10 @@ export const pt = { 'chat.loadingHistory': 'Carregando histórico…', 'chat.loadError': 'Falha ao carregar o histórico: {message} ({code})', 'chat.loadOlder': 'Carregar mais cedo', + 'chat.loadingOlder': 'Carregando anteriores', + 'chat.processingOlder': 'Processando', + 'chat.retryOlder': 'Tentar novamente', + 'chat.historyStart': 'Início da conversa', 'chat.toBottom': 'De volta ao fundo', 'chat.deepDiving': 'Raciocínio profundo', 'chat.deepDivingFor': 'Raciocínio profundo há {duration} ···', diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 8ee48b8f65..352e5d5042 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -253,7 +253,7 @@ describe('Chat inject API', () => { const b = await bench() const { injected } = b.chatViewApi(b.rootReference) injected.loadOlder() - expect(b.session.loadOlder).toHaveBeenCalledOnce() + expect(b.session.loadOlder).toHaveBeenCalledExactlyOnceWith({ deferConsumption: true }) void injected.loadThrough(SessionSeq(42)) expect(b.session.loadThrough).toHaveBeenCalledWith(42) diff --git a/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts new file mode 100644 index 0000000000..16b2bf1da5 --- /dev/null +++ b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts @@ -0,0 +1,130 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SessionSeq } from '@deepseek-ai/dsh-session/types' +import { ChatNavigation, type ChatNavigationInput } from '../src/client/chat/use-chat-navigation.ts' +import { ChatReading } from '../src/client/chat/use-chat-reading.ts' +import { ChatViewport } from '../src/client/chat/use-chat-viewport.ts' +import { ScrollFollow } from '../src/client/chat/use-scroll-follow.ts' + +function fixture() { + const viewport = new ChatViewport() + vi.spyOn(viewport, 'confirmHistoryStart').mockReturnValue(true) + const mode = vi.spyOn(viewport, 'historyConsumption').mockReturnValue('native') + const reading = new ChatReading(viewport, { read: () => null, save: () => {} }, { + initialized: true, followingTail: false, activeTurn: 1, + }, () => {}, new ScrollFollow(false, 24)) + const loadOlder = vi.fn() + const consumeOlder = vi.fn(() => true) + const onIntent = vi.fn() + let input: ChatNavigationInput = { + isOpen: true, firstSeq: SessionSeq(20), hasMore: true, loadingOlder: false, + historyLoadStatus: 'idle', loadOlder, consumeOlder, loadThrough: async () => {}, + } + const navigation = new ChatNavigation(viewport, reading, input, () => {}, onIntent) + const check = () => { + navigation.requestHistoryCheck() + vi.advanceTimersByTime(20) + } + const ready = () => { + input = { ...input, historyLoadStatus: 'pendingConsumption' } + navigation.setInput(input) + } + return { viewport, navigation, reading, mode, loadOlder, consumeOlder, onIntent, check, ready } +} + +beforeEach(() => { vi.useFakeTimers() }) +afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() }) + +describe('history consumption intent', () => { + it.each(['motion', 'pointer', 'unavailable'] as const)('leaves an automatic page for a click after %s', (blocker) => { + const h = fixture() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.mode.mockReturnValue('native') + h.ready() + h.check() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it.each(['touch', 'inner-scroll'] as const)('continues automatic consumption after %s ends', (blocker) => { + const h = fixture() + h.check() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('auto') + expect(h.consumeOlder).not.toHaveBeenCalled() + h.mode.mockReturnValue('native') + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it.each(['motion', 'touch', 'pointer', 'inner-scroll', 'unavailable'] as const)( + 'uses baseline manual paging for a cached page without consulting the automatic %s gate', (blocker) => { + const h = fixture() + h.ready() + h.mode.mockReturnValue(blocker) + const begin = vi.spyOn(h.viewport, 'beginManualPaging') + h.navigation.loadEarlier() + h.check() + expect(h.mode).not.toHaveBeenCalled() + expect(begin).toHaveBeenCalledOnce() + expect(h.loadOlder).not.toHaveBeenCalled() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.navigation.dispose() + }, + ) + + it('joins a pending automatic request when clicked and consumes once after it returns', () => { + const h = fixture() + h.check() + h.navigation.loadEarlier() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.navigation.dispose() + }) + + it.each(['touch', 'inner-scroll'] as const)('keeps %s ahead of an active motion blocker', (input) => { + const viewport = new ChatViewport() + const root = document.createElement('div') + const inner = document.createElement('div') + inner.dataset.stepProcessBody = '' + root.append(inner) + document.body.append(root) + viewport.attach(root, root) + vi.spyOn(viewport.motion, 'active').mockReturnValue(true) + if (input === 'touch') root.dispatchEvent(new Event('touchstart', { bubbles: true })) + else inner.dispatchEvent(new Event('scroll')) + expect(viewport.historyConsumption()).toBe(input) + viewport.detach() + root.remove() + }) + + it('does not consume a cached page on a fresh view until clicked', () => { + const h = fixture() + h.ready() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) +}) diff --git a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx index f0555f7fff..885b16e72c 100644 --- a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx @@ -36,7 +36,7 @@ function ScrollHarness({ input, onMotion }: { function mountScroll(deferCompletedTurns = true, initial: Partial = {}) { let input: ChatScrollInput = { - ready: true, + isOpen: true, order: [], firstSeq: null, lastKey: null, @@ -49,7 +49,7 @@ function mountScroll(deferCompletedTurns = true, initial: Partial false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, @@ -116,9 +116,9 @@ function mountRows(heights: readonly number[]) { } vi.stubGlobal('ResizeObserver', Observer) const input: ChatScrollInput = { - ready: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: false, - transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } const view = render( { callbacks.motion = motion }} @@ -287,9 +287,9 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea let motion: FlowMotionRows | undefined const onMotion = (value: FlowMotionRows): void => { motion = value } let input: ChatScrollInput = { - ready: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: true, - transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) @@ -328,7 +328,7 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea offsetHeight: { get: contentHeight }, getBoundingClientRect: { value: () => ({ top: -top, bottom: contentHeight() - top, height: contentHeight() }) }, }) - input = { ...input, ready: true } + input = { ...input, isOpen: true } view.rerender() top = test.top scrollTo.mockClear() @@ -495,7 +495,7 @@ it('keeps one active fold when the local echo becomes its durable input', async describe('Chat scroll collapse timing', () => { it.each(['resize', 'scroll', 'history', 'input', 'preference'] as const)( 'waits for initial history before initializing a running view after %s', (change) => { - const h = mountScroll(true, { ready: false, running: true }) + const h = mountScroll(true, { isOpen: false, running: true }) expect(h.scroller.dataset.initialized).toBe('false') if (change === 'resize') h.resize() else if (change === 'scroll') fireEvent.scroll(h.scroller) @@ -506,7 +506,7 @@ describe('Chat scroll collapse timing', () => { expect(h.scroller.scrollTop).toBe(0) expect(h.scrollTo).not.toHaveBeenCalled() - h.update({ ready: true }) + h.update({ isOpen: true }) expect(h.scroller.dataset.initialized).toBe('true') expect(h.scroller.scrollTop).toBe(600) expect(h.scrollTo).not.toHaveBeenCalled() diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 37011ab8bb..4cd6d1bb24 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' +import { ChatViewport } from '../src/client/chat/use-chat-viewport.ts' import type { ProcessGroupData } from '../src/client/contract/process-groups.ts' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import { MessageId } from '@deepseek-ai/dsh-llm/brand' @@ -107,6 +108,8 @@ function sessionSnapshot(overrides: Partial = {}): TestSess openError: null, hasMore: false, loadingOlder: false, + historyLoadStatus: 'idle', + historyWasPartial: overrides.hasMore ?? false, promptError: null, blank: false, subagent: null, @@ -421,7 +424,22 @@ function makeHarness( const openFile = vi.fn<(path: string) => Promise>().mockResolvedValue(undefined) const openUserFile = vi.fn<(path: string) => void>() const renderUserContent = createUserContentFixture({ openFile: openUserFile }) - const loadOlder = vi.fn() + let preparedOlder: (() => void) | null = null + const loadOlder = vi.fn(() => { + session.set({ loadingOlder: true, historyLoadStatus: 'loading' }) + }) + const consumeOlder = vi.fn(() => { + if (preparedOlder === null) return false + const consume = preparedOlder + preparedOlder = null + consume() + session.set({ loadingOlder: false, historyLoadStatus: 'idle' }) + return true + }) + const prepareOlder = (consume: () => void) => { + preparedOlder = consume + session.set({ loadingOlder: false, historyLoadStatus: 'pendingConsumption' }) + } const loadThrough = vi.fn<(seq: number) => Promise>().mockResolvedValue(undefined) // Mutable outline holder: tests swap the value and drive a re-render via set(). let outlineValue: unknown @@ -555,6 +573,7 @@ function makeHarness( openFile, openExternalLink: vi.fn(), loadOlder, + consumeOlder, loadThrough, loadImage: vi.fn(() => Promise.reject(new Error('not used'))), chatScroll, @@ -584,7 +603,7 @@ function makeHarness( return { set, setSession: session.set, setChat: chatSource.set, ChatView, props, setConnection: (state: ConnectionState) => { connection.set(state) }, - openFile, openUserFile, loadOlder, loadThrough, openView, + openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, fenceCalls, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, @@ -643,6 +662,11 @@ function readerScroll(element: HTMLElement, top: number): void { fireEvent(element, new Event('scrollend')) } +/** Let the public history scheduler run one frame, including React's commit of its updates. */ +async function historyFrame(): Promise { + await act(async () => { await new Promise(resolve => requestAnimationFrame(() => { resolve() })) }) +} + function turnProcessControl(container: HTMLElement): HTMLButtonElement | null { return container.querySelector('[data-turn-process]') } @@ -1537,6 +1561,19 @@ describe('ChatView', () => { await act(async () => { releaseJump?.() }) }) + it('keeps the history start marker across remounts from the Session fact', () => { + const h = makeHarness({ nodes: [user(1, 'prompt'), assistant(2, 'answer')] }, { + hasMore: false, historyWasPartial: true, + }) + const first = render() + expect(first.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + first.unmount() + const second = render() + expect(second.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + act(() => { h.setSession({ historyWasPartial: false }) }) + expect(second.queryByRole('button', { name: '已到会话开头' })).toBeNull() + }) + it('holds a jump issued while a plain pull owns the pager and resumes it when the pull settles', async () => { const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)] const h = makeHarness({ nodes: later }, { hasMore: true, loadingOlder: true }) @@ -1642,7 +1679,7 @@ describe('ChatView', () => { expect(h.toolOwners[0]).toMatchObject({ callId: 'w1', toolName: '' }) }) - it('prepend keeps the reader\'s latest pending-request scroll position anchored', () => { + it('prepend keeps the reader\'s latest pending-request scroll position anchored', async () => { const h = makeHarness( { nodes: [user(9, 'first visible'), user(10, 'next visible')] }, { hasMore: true }, @@ -1666,17 +1703,19 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) - act(() => { h.set({ loadingOlder: true }) }) + await historyFrame() // The reader moves after the request starts; this, not the click-time // row, is the intent the arriving page must preserve. firstTop = -200 nextTop = 60 readerScroll(scroller, 90) - Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) - nextTop = 560 - act(() => { - h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')], loadingOlder: false }) - }) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) + nextTop = 560 + h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(590) // latest 90 + the anchored row's 500px prepend shift }) @@ -1685,7 +1724,7 @@ describe('ChatView', () => { { mode: 'detailed', anchor: 'group' }, { mode: 'compact', anchor: 'node' }, { mode: 'standard', anchor: 'node' }, { mode: 'detailed', anchor: 'node' }, ] as const)( - 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', ({ mode, anchor }) => { + 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', async ({ mode, anchor }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [tool(4, 'retained'), assistant(6, 'answer', 1, 2)], turnEnds: new Map([[1, 7]]) } let source = chatSnapshotFixture(initial) @@ -1726,14 +1765,17 @@ describe('ChatView', () => { expect(pinned.hasAttribute('data-chat-paging-anchor')).toBe(true) expect(controlSeat.hasAttribute('data-chat-paging-anchor')).toBe(false) expect(group.hasAttribute('data-chat-paging-anchor')).toBe(anchor !== 'node') - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { paged = true source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier'), steering(2, 'historical direction', 1), tool(3, 'before-retained'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(pinned.getBoundingClientRect().top).toBe(expectedTop) expect(scroller.scrollTop).toBe(expectedScroll) @@ -1757,7 +1799,7 @@ describe('ChatView', () => { { mode: 'compact', hasProcess: false, hasSteering: true }, { mode: 'standard', hasProcess: false, hasSteering: true }, { mode: 'detailed', hasProcess: false, hasSteering: true }, - ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', ({ mode, hasProcess, hasSteering }) => { + ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', async ({ mode, hasProcess, hasSteering }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [ @@ -1801,13 +1843,16 @@ describe('ChatView', () => { expect(control.hasAttribute('data-chat-paging-anchor')).toBe(false) fireEvent.click(view.getByText('加载更早')) - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier-work'), steering(2, 'earlier direction', 1), tool(3, 'following-work'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() const steer = view.container.querySelector('[data-chat-node-key="fixture:steering:2"]')! const rows = visibleRows() @@ -1854,7 +1899,7 @@ describe('ChatView', () => { } }) - it('anchors the first transcript row for paging regardless of the viewport reading line', () => { + it('anchors the first transcript row for a prepared page consumed at the top without reading hit tests', async () => { const originalHitTest = Object.getOwnPropertyDescriptor(document, 'elementsFromPoint') const nodes = Array.from({ length: 16 }, (_, index) => user(20 + index, `row ${String(index)}`)) const h = makeHarness( @@ -1873,13 +1918,13 @@ describe('ChatView', () => { vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => { rowRectCalls += 1 const shift = prepended ? (index === 8 ? 400 : 500) : 0 - const top = 20 + (index - 8) * 60 + shift + const top = 20 + index * 60 + shift - scroller.scrollTop return { top, bottom: top + 40 } as DOMRect }) }) Object.defineProperty(scroller, 'scrollHeight', { value: 800, writable: true }) Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) - readerScroll(scroller, 50) + readerScroll(scroller, 0) const hitTest = vi.fn((_x: number, _y: number): Element[] => []) Object.defineProperty(document, 'elementsFromPoint', { @@ -1890,14 +1935,19 @@ describe('ChatView', () => { rowRectCalls = 0 fireEvent.click(view.getByText('加载更早')) expect(hitTest).not.toHaveBeenCalled() - expect(rowRectCalls).toBe(1) - - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - prepended = true - act(() => { + expect(rowRectCalls).toBe(0) + await historyFrame() + act(() => { h.prepareOlder(() => { + expect(hitTest).not.toHaveBeenCalled() + expect(rowRectCalls).toBe(1) + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + prepended = true h.setChat({ nodes: [assistant(2, 'older'), ...nodes] }) - }) - expect(scroller.scrollTop).toBe(550) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(scroller.scrollTop).toBe(500) + expect(rows[0]!.getBoundingClientRect().top).toBe(20) expect(h.chatScroll.read()?.anchorKey).toBe('fixture:user:20') } finally { if (originalHitTest !== undefined) { @@ -4060,7 +4110,7 @@ describe('ChatView', () => { expect(screen.queryByRole('dialog')).toBeNull() }) - it('prepend preserves a semantic row; a trailing user node force-scrolls', () => { + it('prepend preserves a semantic row; a trailing user node force-scrolls', async () => { const h = makeHarness( { nodes: [user(5, 'later'), assistant(6, 'a')] }, { hasMore: true }, @@ -4076,13 +4126,15 @@ describe('ChatView', () => { () => ({ top: anchoredTop, bottom: anchoredTop + 40 } as DOMRect), ) readerScroll(scroller, 80) - // Arm the paging anchor, then deliver an older page (head seq decreases). fireEvent.click(view.getByText('加载更早')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) - anchoredTop = 700 - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) + anchoredTop = 700 h.setChat({ nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a')] }) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(680) // reader offset 80 + the anchored row's 600px shift // A new trailing user bubble (own words) force-scrolls to the bottom. act(() => { @@ -4093,7 +4145,75 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(1200) }) - it('back-to-bottom cancels an in-flight paging anchor', () => { + it('restores a one-shot prepend landing after immediate remount before scroll delivery', async () => { + const host = document.createElement('div') + host.dataset.conversationScroll = '' + document.body.append(host) + let paged = false + Object.defineProperties(host, { + clientHeight: { value: 200 }, + scrollHeight: { get: () => paged ? 1200 : 200 }, + }) + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this === host) return new DOMRect(0, 0, 500, 200) + const offset = this.dataset.chatAnchorKey === 'fixture:user:5' ? 20 + (paged ? 200 : 0) : 0 + return new DOMRect(0, offset - host.scrollTop, 500, 40) + }) + try { + const h = makeHarness({ nodes: [user(5, 'retained prompt'), assistant(6, 'answer')] }, { hasMore: true }) + const view = render(, { container: host }) + expect(host.scrollTop).toBe(0) + expect(h.chatScroll.read()).toBeNull() + fireEvent.click(view.getByRole('button', { name: '加载更早' })) + await historyFrame() + act(() => { h.prepareOlder(() => { + paged = true + h.setChat({ nodes: [user(1, 'earlier'), assistant(2, 'old answer'), user(5, 'retained prompt'), assistant(6, 'answer')] }) + }) }) + await historyFrame() + expect(host.scrollTop).toBe(200) + // A navigation can remove the view before the browser delivers the scroll caused by compensation. + view.rerender(
) + host.scrollTop = 0 + view.rerender() + expect(host.scrollTop).toBe(200) + expect(h.chatScroll.read()).toMatchObject({ anchorKey: 'fixture:user:5', anchorTop: 20, scrollTop: 200 }) + } finally { + host.remove() + } + }) + + it('settles a top prepend with unchanged node order before a later unrelated append', async () => { + const h = makeHarness({ nodes: [user(5, 'retained'), assistant(6, 'answer')] }, { hasMore: true }) + h.chatScroll.save({ anchorKey: 'fixture:user:5', anchorTop: 0, scrollTop: 0 }) + vi.spyOn(ChatViewport.prototype, 'confirmHistoryStart').mockReturnValue(true) + const begin = vi.spyOn(ChatViewport.prototype, 'beginHistoryPrepend') + const view = render() + const scroller = view.container.querySelector('[data-chat-flow]')!.parentElement as HTMLDivElement + Object.defineProperties(scroller, { + scrollHeight: { configurable: true, value: 1500 }, + clientHeight: { configurable: true, value: 200 }, + }) + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this === scroller) return new DOMRect(0, 0, 500, 200) + const offset = this.dataset.chatAnchorKey === 'fixture:user:5' ? 0 : 400 + return new DOMRect(0, offset - scroller.scrollTop, 500, 40) + }) + readerScroll(scroller, 300) + await historyFrame() + readerScroll(scroller, 0) + act(() => { h.prepareOlder(() => { h.setSession({ hasMore: false }) }) }) + await historyFrame() + expect(begin).toHaveBeenCalledOnce() + expect(h.consumeOlder).toHaveBeenCalledOnce() + readerScroll(scroller, 300) + const write = vi.spyOn(scroller, 'scrollTop', 'set') + act(() => { h.setChat({ nodes: [user(5, 'retained'), assistant(6, 'answer'), assistant(7, 'later reply')] }) }) + expect(scroller.scrollTop).toBe(300) + expect(write).not.toHaveBeenCalled() + }) + + it('back-to-bottom cancels pending history consumption without reviving it when the page arrives', async () => { const h = makeHarness({ nodes: [user(9, 'late')] }, { hasMore: true }) const view = render() const scroller = view.container.querySelector('[data-chat-flow]')!.parentElement as HTMLDivElement @@ -4101,10 +4221,16 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) + await historyFrame() fireEvent.click(view.getByLabelText('回到底部')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - act(() => { h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) }) - expect(scroller.scrollTop).toBe(1_100) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(scroller.scrollTop).toBe(600) + expect(view.queryByText('older')).toBeNull() expect(h.chatScroll.read()).toBeNull() }) @@ -4598,13 +4724,19 @@ describe('ChatView', () => { } }) - it('paging button loads older and shows its busy label', () => { + it('paging button schedules an older request and shows its loading label', async () => { const h = makeHarness({ nodes: [user(5, 'later')] }, { hasMore: true }) const view = render() fireEvent.click(view.getByText('加载更早')) + expect(h.loadOlder).not.toHaveBeenCalled() + expect(view.getByRole('button', { name: '正在处理' }).hasAttribute('disabled')).toBe(false) + await historyFrame() + expect(h.loadOlder).toHaveBeenCalledTimes(1) + const loading = view.getByRole('button', { name: '正在加载' }) + expect(loading.hasAttribute('disabled')).toBe(false) + fireEvent.click(loading) + await historyFrame() expect(h.loadOlder).toHaveBeenCalledTimes(1) - act(() => { h.setSession({ loadingOlder: true }) }) - expect(view.getByText('加载中…')).toBeTruthy() }) it('shows open error and loading states', () => { diff --git a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts index def772efb8..e3ed867df9 100644 --- a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts @@ -48,6 +48,100 @@ function fixture() { return { column, viewport, group, row, prepend: (height: number) => { prependedHeight += height } } } +it('updates history distance only from scrollport size observations before layout writes', () => { + let resize: ResizeObserverCallback | undefined + class Observer implements ResizeObserver { + constructor(callback: ResizeObserverCallback) { resize = callback } + observe(): void {} + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', Observer) + onTestFinished(() => { vi.unstubAllGlobals() }) + const h = fixture() + const edge = document.createElement('div') + h.column.prepend(edge) + const height = vi.fn(() => 300) + Object.defineProperty(h.column, 'clientHeight', { configurable: true, get: height }) + h.viewport.setHistoryEdge(edge) + expect(height).not.toHaveBeenCalled() + let afterWrite = false + vi.spyOn(h.viewport, 'reclaimBelow').mockImplementation(() => { afterWrite = true }) + height.mockImplementation(() => { + if (afterWrite) throw new Error('height read after a layout writer') + return 300 + }) + const entry: ResizeObserverEntry = { target: h.column, contentRect: new DOMRect(), + borderBoxSize: [], contentBoxSize: [], devicePixelContentBoxSize: [] } + const notify = resize + const observer = new Observer(() => {}) + notify?.([entry], observer) + height.mockClear() + notify?.([], observer) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -600, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(true) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -700, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(false) + expect(height).not.toHaveBeenCalled() +}) + +it('uses the first paging anchor for one-shot history prepending without reading-position lookup', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + const scrollerRect = vi.spyOn(h.column, 'getBoundingClientRect') + const capture = vi.spyOn(h.viewport, 'capturePosition') + const query = vi.spyOn(h.column, 'querySelector') + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(capture).not.toHaveBeenCalled() + expect(query).toHaveBeenCalledTimes(1) + expect(scrollerRect).toHaveBeenCalledTimes(1) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(row.getBoundingClientRect().top).toBe(0) + h.prepend(30) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) +}) + +it('uses a collapsed group paging anchor when no ordinary content row is visible', () => { + const h = fixture() + const group = h.row(h.column, 'group', 0) + group.dataset.chatGroupKey = 'group' + const body = document.createElement('div') + body.hidden = true + group.append(body) + h.row(body, 'hidden-member', 20) + expect(h.viewport.capturePosition()).toBeNull() + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(group.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('restores the captured screen position once without retaining paging ownership', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(row.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('does not prepare a correction when no paging anchor exists', () => { + const h = fixture() + expect(h.viewport.beginHistoryPrepend()).toBe(false) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(0) +}) + it.each([ { count: 64, slot: false }, { count: 4096, slot: false }, { count: 64, slot: true }, { count: 4096, slot: true }, @@ -440,6 +534,71 @@ it.each([ expect(h.row.getBoundingClientRect().top).toBe(top) }) +it('restores the captured inner and outer screen position once without subscribing', () => { + const h = nestedFixture(600, 400) + h.scroller.scrollTop = 80 + h.body.scrollTop = 40 + const screenTop = h.row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + expect(h.observed.has(h.content)).toBe(false) + h.body.scrollTop = 60 + h.scroller.scrollTop = 90 + h.prepend(200) + h.viewport.finishHistoryPrepend() + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(80) + expect(h.row.getBoundingClientRect().top).toBe(screenTop) + expect(h.observed.has(h.content)).toBe(false) + h.prepend(20) + h.resize() + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(80) +}) + +it('resolves a remounted one-shot anchor without entering retained paging', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + row.remove() + const replacement = h.row(h.column, 'old', 0) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(replacement.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('does not repeat native outer anchoring during a near-zero one-shot prepend', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + h.column.scrollTop = 0.5 + const top = row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(120) + // Model the browser's adjustment before the layout effect reads the new geometry. + h.column.scrollTop = 120.5 + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120.5) + expect(row.getBoundingClientRect().top).toBe(top) +}) + +it('does not repeat native inner anchoring when the outer scroller is at zero', () => { + const h = nestedFixture(600, 400) + h.body.scrollTop = 40 + const top = h.row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(200) + // Same ordering as the Chromium regression: native inner adjustment precedes our correction. + h.body.scrollTop = 240 + h.viewport.finishHistoryPrepend() + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(0) + expect(h.row.getBoundingClientRect().top).toBe(top) + expect(h.viewport.preserving).toBe(false) +}) + it('gives paging compensation priority over an active inner follow animation', () => { const h = nestedFixture(600, 400) const follow = new ScrollFollow(true, 1) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index c88fda7554..52e160a17b 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -18,11 +18,11 @@ en: ef43c4f149195939 zh: 49fc6c83fd3a05ce /deepseek-ai-dsh-client-ui-conversation/sent-user-text: - en: cc4dafd1aae02468 - zh: be6b67724b7ac4a3 + en: 4a094cd97426ad18 + zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: bd2a85b9012fa3c3 - zh: e88d7e682e316a0e + en: 7c45c9c9767b3184 + zh: 290037aa8a71b1df /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: b3f74c35f88ab2fa - zh: 8492b314debd130c + en: c8323c1986c1be46 + zh: 6151492c67d4cb88 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 041aa0d5d4..32c07ecabc 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -61,7 +61,7 @@ Queue previews enable whitespace collapsing and document-edge trimming, retain e [Message quotes](../../session/message-quotes/README.md) registers quote matching and rendering through the same UserText extension points. Each user-text container and draft editor owns an independent hover-card group, so its quote previews replace one another immediately. -The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinate spans beside references. Storage accepts earlier string and reference-only drafts; Session switching and Workspace transfer preserve atomic quotes through the existing editor runtime, and a failed send leaves them in the editor. `inputActions.insertQuote(text)` inserts a nonblank selection only while the composer is in plain mode. Submission emits ordinary Markdown text; pending echoes, queue rows, steering rows, and durable messages use the same text matcher. +The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinate spans beside references. Storage accepts earlier string and reference-only drafts; Session switching and Workspace transfer preserve atomic quotes through the existing editor runtime, and a failed send leaves them in the editor. `inputActions.insertQuote(text, summary?)` inserts a nonblank selection only while the composer is in plain mode; an optional `QuoteSummary` replaces the text in the composer display and is stored with the draft, while the sent message still carries the text. Submission emits ordinary Markdown text; pending echoes, queue rows, steering rows, and durable messages use the same text matcher. `UiConversation.interactions` owns plugin registrations for selected-text and context-menu gestures. A registration supplies a synchronous handler whose ID selects its keyed Slot component; plugins use the Slot injection mechanism for rendering. Handlers call `open()` to display and call `preventDefault()` separately when replacing a browser default. Chat supplies DOM selections and local layout; original source data and Markdown offsets are not inferred from DOM positions. @@ -132,6 +132,8 @@ Each composer attempt carries its original occurrence time, gesture, delivery in A default send waits for the Host: Enter captures the draft text, its reference chips, and its attachments in the attempt, and the composer enters `sending`, with the editor and attachment rail read-only and Send showing progress, until the Host accepts the prompt, as its receipt or an Inbox row carrying its request id shows, whichever arrives first. Only then do the draft, its attachments, the occurrence table, and the undo history clear in one transaction, before the echo renders; a refusal or failure returns the composer to `plain` with the draft and attachments unchanged, so one message is in flight at a time. When a read-only input phase ends with focus on the document body, desktop returns focus to the editor and mobile moves it to the composer card without reopening the keyboard. A control the user focused during that phase keeps focus. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order; Session publishes it in `pendingSubmissions` once the Host accepts the prompt and derives the placement from that mode and its running state at registration, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Command submissions keep the frozen `submitting` phase. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards; an accepted prompt whose echo retires unobserved releases its attachments, and Session scope disposal releases the attachments of a message the Host has not accepted. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`. +Every mounted composer, including a subagent conversation open in the right Sidebar, joins one document-level paste route. A paste whose clipboard carries files, while focus is outside any input, text area, or editable element, enters the composer that most recently held focus, or the main Conversation's composer before any other composer has held focus or while the focused one cannot accept files; a paste inside a focused editor stays with that editor, and clipboard text without files is never inserted this way. A composer in a hidden or inert subtree, such as a collapsed Sidebar or an unselected tab, is never addressed, and while a modal dialog or menu is open only a composer inside it can be. When no addressable composer can accept files, the paste keeps the browser's default handling. + Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A refused or failed submission publishes no echo and leaves the draft in the composer with an error notice. A refusal from the Agent admission stage (`session/prompt-rejected`) shows its own text, unless `presented` says the refusing plugin explains it in its own interface, in which case the composer adds no notice. Disabled Send and Stop buttons suppress their tooltips, including a Stop button that becomes a disabled Send button when the turn ends. While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. While a message waits for the Host, the seat shows its progress, and a separate Stop stays beside it. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label. Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions and accept pasted or dropped images, but expose no File row; creator availability does not disable input, and Host admission failures use the ordinary prompt error feedback ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../subagent/subagent/README.md)). @@ -221,6 +223,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 0ac0d779d1..f7e349e84d 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -61,7 +61,7 @@ Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CS [Message quotes](../../session/message-quotes/README.zh.md) 通过相同的 UserText 扩展点注册引用匹配与渲染。 每个用户文本容器和草稿编辑器各自拥有独立的悬停卡片分组,其中的 quote 原文弹层会立即互相替换。 -现有语义 `DraftSnapshot` 在 references 旁保留 quote 文本及 clipboard 坐标范围。存储接受较早的字符串和仅含 reference 的草稿;Session 切换和 Workspace 转移通过现有编辑器 runtime 保留原子 quote,发送失败时它们留在编辑器中。`inputActions.insertQuote(text)` 仅在输入框处于 plain 模式时插入非空选区。提交产出普通 Markdown 文本;待发送回显、队列行、steering 行和持久消息使用同一文本匹配器。 +现有语义 `DraftSnapshot` 在 references 旁保留 quote 文本及 clipboard 坐标范围。存储接受较早的字符串和仅含 reference 的草稿;Session 切换和 Workspace 转移通过现有编辑器 runtime 保留原子 quote,发送失败时它们留在编辑器中。`inputActions.insertQuote(text, summary?)` 仅在输入框处于 plain 模式时插入非空选区;可选的 `QuoteSummary` 在输入框中替代文本显示并随草稿保存,发送的消息仍携带该文本。提交产出普通 Markdown 文本;待发送回显、队列行、steering 行和持久消息使用同一文本匹配器。 `UiConversation.interactions` 拥有插件对文本选择和右键手势的注册。每个注册项提供同步处理函数,其 ID 选择对应的 keyed Slot 组件;插件通过 Slot injection 机制渲染。处理函数调用 `open()` 展示,需要替代浏览器默认行为时单独调用 `preventDefault()`。Chat 提供 DOM 选区和区域内布局;机制不从 DOM 位置推断原始来源数据或 Markdown 偏移。 @@ -132,6 +132,8 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 默认发送等待 Host 接收:Enter 把草稿文字、引用胶囊和附件一起记入本次 attempt,composer 进入 `sending`,编辑器和附件栏只读,Send 显示发送中,直到 Host 接收该提示词(以回执或带有该请求 id 的 Inbox 行为准,先到者生效)。之后才在回显渲染之前、在同一事务里清空草稿、其附件、occurrence 表和撤销历史;被拒绝或失败时 composer 回到 `plain`,草稿和附件保持不变,因此同一时刻只有一条消息在途。只读输入阶段结束时,如果焦点停在页面 body 上,桌面端将焦点恢复到编辑器,移动端则将焦点移到输入卡片,避免重新弹出键盘。用户在此期间聚焦的其他控件会保留焦点。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),保留图片与文件的选择顺序;Host 接收提示词后,Session 才在 `pendingSubmissions` 中公开它,并按注册时的模式与运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。命令提交保持冻结的 `submitting` 阶段。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡;已被接收但回显未被观察到就退休的提示词会释放其附件,Session scope 销毁时会释放尚未被 Host 接收的消息的附件。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。 +每个已挂载的 composer(包括在右侧栏打开的子代理对话)都加入同一条文档级粘贴路由。焦点不在任何输入框、文本区域或可编辑元素内时,剪贴板带有文件的粘贴会进入最近一次获得焦点的 composer;在其他 composer 获得焦点之前,或最近聚焦的 composer 当前无法接收文件时,则进入主 Conversation 的 composer。已聚焦编辑器内的粘贴仍由该编辑器处理,不含文件的剪贴板文字不会经此插入。位于隐藏或 inert 子树中的 composer(例如折叠的侧栏或未选中的标签页)不会成为目标;打开模态对话框或菜单时,只有其中的 composer 可以成为目标。没有可作为目标的 composer 能接收文件时,粘贴保留浏览器的默认处理。 + 排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到提示词确认不会启用队列操作。被拒绝或失败的提交不会公开回显,草稿留在 composer 中并显示错误提示。Agent 接纳阶段的拒绝(`session/prompt-rejected`)显示它自带的文字;若 `presented` 表明拒绝它的插件会在自己的界面里说明,composer 不再提示。 Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切换成禁用 Send 的按钮也遵循此规则。普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。消息等待 Host 接收期间,该位置显示发送进度,旁边另有独立的 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,允许粘贴或拖入图片,但不提供「文件」菜单项;创建者的在线状态不禁用输入,Host 接收失败使用普通提示词错误反馈([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../subagent/subagent/README.zh.md))。 @@ -221,6 +223,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index aae71928be..37420f7fc2 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -33,6 +33,7 @@ import type { IConversation } from './service.ts' import { ComposerBlockRegistry } from './input/blocks.ts' import type { ComposerBlock } from './contract/composer-blocks.ts' import { InputHub } from './input/hub.ts' +import { createComposerFileIntake } from './input/file-intake.ts' import { ComposerSubmissionPolicy } from './input/submission-policy.ts' import { queueDockEntry } from './queue/QueueDock.tsx' import { EnterBehaviorRow } from './settings/EnterBehaviorRow.tsx' @@ -460,6 +461,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { }), }, ConversationSessionHeader) + const fileIntake = createComposerFileIntake() const registerComposerBar = () => slots.register({ name: 'conversation.composer.bar', locale: NS, @@ -477,6 +479,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { inject: (sessionId: SessionId | undefined): ComposerBarInjected => { if (sessionId === undefined) { return { + registerFileIntake: fileIntake, keyboard: undefined, addFiles: undefined, removeAttachment: undefined, @@ -500,6 +503,7 @@ export function apply(ctx: Context, config: Config = Config({})): void { const inputTriggers = inputHub.inputTriggers(sessionId) const bridge = hostPathBridge() return { + registerFileIntake: fileIntake, keyboard: shell, addFiles: (files, directories = new Set()) => { if (sessions.binding(sessionId) === undefined) return t('file.sessionUnavailable') diff --git a/packages/client/ui-conversation/src/client/contract/draft-editor.ts b/packages/client/ui-conversation/src/client/contract/draft-editor.ts index b305bb3a3c..86592a82db 100644 --- a/packages/client/ui-conversation/src/client/contract/draft-editor.ts +++ b/packages/client/ui-conversation/src/client/contract/draft-editor.ts @@ -1,5 +1,6 @@ /** Editor-facing ranges, reference projections, and the composer keyboard interface. */ import type { LexicalEditor } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { InputState } from './input.ts' import type { InputSubmitMode } from './composer-submission.ts' @@ -28,6 +29,8 @@ export interface DraftQuote { readonly length: number /** Selected text before Markdown quote prefixes are added. */ readonly text: string + /** Readable display the inserting owner supplied; the draft text and the sent message still carry `text`. */ + readonly summary?: QuoteSummary | undefined } /** diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 6f6b0f1436..3d8ebd6d6a 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -11,6 +11,7 @@ import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/cli import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { Branded } from '@deepseek-ai/dsh-brand' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { ArbitrateKey, ArbitrateOutcome, DraftQuote, Occurrence, ReferenceInsert, TokenSpan } from './draft-editor.ts' import type { InputSubmitMode, MessageSubmission } from './composer-submission.ts' @@ -182,8 +183,13 @@ export interface InputTarget { /** Per-session input facade owned by the conversation wiring layer. */ export interface SessionInput extends InputTarget { - /** Insert selected transcript text as an atomic quote. @param text - nonblank selection. @returns whether editing accepted it. */ - insertQuote(text: string): boolean + /** + * Insert text as an atomic quote. + * @param text - nonblank selection; the sent message carries it as a Markdown blockquote. + * @param summary - readable display shown in the composer instead of `text`. + * @returns whether editing accepted it. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean /** Replace the whole draft with plain text, removing inline reference chips. */ setDraft(text: string): void @@ -256,8 +262,13 @@ export type DraftInitializationResult = 'applied' | 'preserved' | 'blocked' * paste/…) stay InputBar-private and never ride this face. */ export interface InputActions { - /** Insert one nonblank transcript quote. @param text - selected text. @returns whether editing accepted it. */ - insertQuote(text: string): boolean + /** + * Insert one nonblank quote. + * @param text - selected text; the sent message carries it as a Markdown blockquote. + * @param summary - readable display shown in the composer instead of `text`. + * @returns whether editing accepted it. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean /** @returns a revision-guarded copy of the current editor selection. */ captureInsertion(): TokenSpan /** diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index e7ae7285ab..f8bbf67c5b 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -545,6 +545,8 @@ export interface ConversationSessionHeaderInjected { export interface ComposerBarOwnerProps { /** Hero uses centered placement; composer uses the active bottom placement. */ variant: 'hero' | 'composer' + /** Conversation content occurrence rendering this composer; an unaddressed document paste reaches the main one. */ + occurrence: ConversationContentInputProps['variant'] /** A feature-owned reason that makes message input inert while leaving model selection live. */ blocked?: { readonly reason: string } /** Lock all message actions while preserving the resident composer surface. */ @@ -558,8 +560,33 @@ export interface ComposerBarOwnerProps { accessory?: ReactNode } +/** One composer's entry in the document-level paste route. */ +export interface ComposerFileIntakeTarget { + /** Composer card containing every control of this composer. */ + readonly card: HTMLElement + /** Conversation content occurrence rendering the composer. */ + readonly occurrence: ConversationContentInputProps['variant'] + /** Whether a routed paste may enter now; a refusing composer is skipped, and when no composer accepts the browser keeps the event. */ + readonly accepts: () => boolean + /** + * Add one routed paste through the composer's intake validation. + * @param files - pasted browser files in clipboard order. + * @param directories - members of `files` the clipboard entry API identified as directories. + */ + readonly add: (files: readonly File[], directories?: ReadonlySet) => void +} + +/** + * Join the document-level paste route shared by every composer of the plugin instance. + * @param target - the registering composer. + * @returns the disposer leaving the route; the last disposer removes the route's document listeners. + */ +export type ComposerFileIntake = (target: ComposerFileIntakeTarget) => () => void + /** Package-private operations injected into the resident composer bar. */ export interface ComposerBarInjected { + /** Document paste routing across mounted composers. */ + registerFileIntake: ComposerFileIntake keyboard: ComposerKeyboard | undefined /** * Register one picked batch; resolves to the rejection copy or null. Where diff --git a/packages/client/ui-conversation/src/client/draft.ts b/packages/client/ui-conversation/src/client/draft.ts index e4cee855b2..c5e96539de 100644 --- a/packages/client/ui-conversation/src/client/draft.ts +++ b/packages/client/ui-conversation/src/client/draft.ts @@ -1,6 +1,7 @@ /** Semantic draft snapshots shared by storage, programmatic input, and editor restoration. */ import { z } from 'zod' import { formatQuoteText } from '@deepseek-ai/dsh-client-ui-primitives' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { DraftInput, DraftQuote, DraftReference, DraftSnapshot, Occurrence } from './contract/draft-editor.ts' const referenceSchema = z.object({ @@ -18,10 +19,16 @@ const commandSchema = z.object({ token: z.string(), }) +// Lists every QuoteSummary field: parsing strips unknown keys, so a field missing here is dropped from restored drafts. +const quoteSummarySchema: z.ZodType = z.object({ + label: z.string(), title: z.string(), detail: z.string().optional(), body: z.string(), +}) + const quoteSchema = z.object({ offset: z.number().int().nonnegative(), length: z.number().int().positive(), text: z.string().refine(text => text.trim() !== ''), + summary: quoteSummarySchema.optional(), }) const snapshotSchema = z.object({ diff --git a/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx b/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx index ecd42af89d..78a2d379c9 100644 --- a/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx +++ b/packages/client/ui-conversation/src/client/input/editor/QuoteNode.tsx @@ -3,6 +3,7 @@ import type { JSX } from 'react' import { QuotePreview } from '@deepseek-ai/dsh-client-ui-primitives' import { formatQuoteText } from '@deepseek-ai/dsh-client-ui-primitives' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { EditorConfig, LexicalEditor, LexicalNode, NodeKey, SerializedLexicalNode, Spread, } from 'lexical' @@ -18,21 +19,24 @@ const EMPTY_LABELS: QuoteNodeLabels = { remove: '' } /** JSON form used only by Lexical's editor-state APIs, not browser persistence. */ export type SerializedQuoteNode = Spread<{ text: string + summary?: QuoteSummary }, SerializedLexicalNode> /** Remove one quote occurrence by its Lexical identity. */ export const REMOVE_QUOTE_COMMAND = createCommand('REMOVE_QUOTE_COMMAND') /** Pure React face of one quote node. */ -export function QuoteNodeView({ editor, nodeKey, text, labels }: { +export function QuoteNodeView({ editor, nodeKey, text, summary, labels }: { readonly editor: LexicalEditor readonly nodeKey: NodeKey readonly text: string + readonly summary?: QuoteSummary | undefined readonly labels: QuoteNodeLabels }) { return ( { editor.dispatchCommand(REMOVE_QUOTE_COMMAND, nodeKey) }, @@ -44,6 +48,7 @@ export function QuoteNodeView({ editor, nodeKey, text, labels }: { /** One selected transcript range represented as an atomic inline decorator. */ export class QuoteNode extends DecoratorNode { __text: string + __summary: QuoteSummary | undefined __labels: QuoteNodeLabels /** Lexical node registry type tag. */ @@ -56,27 +61,31 @@ export class QuoteNode extends DecoratorNode { return new QuoteNode( node.__text, node.__labels, + node.__summary, node.__key, ) } /** @param json - serialized editor node. @returns a fresh node with default runtime labels. */ static override importJSON(json: SerializedQuoteNode): QuoteNode { - return new QuoteNode(json.text) + return new QuoteNode(json.text, EMPTY_LABELS, json.summary) } /** * @param text - selected text. * @param labels - runtime-only localized labels. + * @param summary - readable display shown instead of the text. * @param key - Lexical clone-path key; absent for fresh nodes. */ constructor( text: string, labels: QuoteNodeLabels = EMPTY_LABELS, + summary?: QuoteSummary, key?: NodeKey, ) { super(key) this.__text = text + this.__summary = summary this.__labels = labels } @@ -87,6 +96,7 @@ export class QuoteNode extends DecoratorNode { type: 'quote', version: 1, text: this.__text, + ...(this.__summary === undefined ? {} : { summary: this.__summary }), } } @@ -123,6 +133,11 @@ export class QuoteNode extends DecoratorNode { return this.getLatest().__text } + /** Readable display the inserting owner supplied, if any. */ + getQuoteSummary(): QuoteSummary | undefined { + return this.getLatest().__summary + } + /** Update the localized remove label without changing persisted quote data. */ setLabels(labels: QuoteNodeLabels): void { if (this.getLatest().__labels.remove !== labels.remove) this.getWritable().__labels = labels @@ -135,15 +150,21 @@ export class QuoteNode extends DecoratorNode { editor={editor} nodeKey={this.__key} text={this.__text} + summary={this.__summary} labels={this.__labels} /> ) } } -/** @param text - selected quote text. @param labels - runtime labels. @returns a fresh node. */ -export function $createQuoteNode(text: string, labels: QuoteNodeLabels): QuoteNode { - return new QuoteNode(text, labels) +/** + * @param text - selected quote text. + * @param labels - runtime labels. + * @param summary - readable display shown instead of the text. + * @returns a fresh node. + */ +export function $createQuoteNode(text: string, labels: QuoteNodeLabels, summary?: QuoteSummary): QuoteNode { + return new QuoteNode(text, labels, summary) } /** @param node - possible Lexical node. @returns whether it is a QuoteNode. */ diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index a2573fdefc..e2ac87b660 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -23,6 +23,7 @@ import { } from 'lexical' import { mergeRegister } from '@lexical/utils' import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/draft-editor.ts' +import { clipboardFiles } from '../file-intake.ts' import { $isQuoteNode } from './QuoteNode.tsx' /** The bar-supplied behavior behind each intercepted gesture. */ @@ -283,17 +284,7 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer // deliver clipboardData on plain events. const clipboardData = (event as ClipboardEvent).clipboardData ?? null if (clipboardData === null) return false - const files: File[] = [] - const directories = new Set() - for (const item of clipboardData.items) { - if (item.kind !== 'file') continue - const file = item.getAsFile() - if (file === null) continue - files.push(file) - if (typeof item.webkitGetAsEntry === 'function' && item.webkitGetAsEntry()?.isDirectory === true) { - directories.add(file) - } - } + const { files, directories } = clipboardFiles(clipboardData) if (files.length > 0) handlers.intakeFiles(files, directories.size === 0 ? undefined : directories) const text = clipboardData.getData('text/plain') if (text === '') { diff --git a/packages/client/ui-conversation/src/client/input/editor/projection.ts b/packages/client/ui-conversation/src/client/input/editor/projection.ts index dacc465d3b..4c3b246254 100644 --- a/packages/client/ui-conversation/src/client/input/editor/projection.ts +++ b/packages/client/ui-conversation/src/client/input/editor/projection.ts @@ -207,7 +207,11 @@ export function $projectComposer(idOf: (key: NodeKey) => number): EditorProjecti for (const segment of layout.segments) { if (segment.kind !== 'chip') continue if ($isQuoteNode(segment.node)) { - quotes.push({ offset: segment.clipboardStart, length: segment.clipboardLength, text: segment.node.getQuoteText() }) + const summary = segment.node.getQuoteSummary() + quotes.push({ + offset: segment.clipboardStart, length: segment.clipboardLength, text: segment.node.getQuoteText(), + ...(summary === undefined ? {} : { summary }), + }) continue } if (!$isReferenceChipNode(segment.node)) continue diff --git a/packages/client/ui-conversation/src/client/input/editor/runtime.ts b/packages/client/ui-conversation/src/client/input/editor/runtime.ts index f162943b6f..bed9912426 100644 --- a/packages/client/ui-conversation/src/client/input/editor/runtime.ts +++ b/packages/client/ui-conversation/src/client/input/editor/runtime.ts @@ -1,6 +1,7 @@ /** The Composer model's private Lexical editor, projections, and node operations. */ import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { LexicalEditor, NodeKey } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import { $addUpdateTag, $createParagraphNode, $createTextNode, $getAdjacentNode, $isTextNode, $getRoot, $getSelection, $getNodeByKey, $isRangeSelection, @@ -348,14 +349,15 @@ export class DraftEditorRuntime { * Insert one quote after the retained draft selection as an independent undo edit. * @param text - nonblank selected transcript text. * @param labels - current localized editor controls. + * @param summary - readable display shown instead of the text. * @returns whether the insertion position accepted the node. */ - insertQuote(text: string, labels: QuoteNodeLabels): boolean { + insertQuote(text: string, labels: QuoteNodeLabels, summary?: QuoteSummary): boolean { let applied = false this.applyEdit(() => { const projection = $projectComposer(key => this.occurrenceIdOf(key)) const at = projection.selection?.end ?? projection.detectText.length - applied = $replaceDetectSpanWithNodes({ start: at, end: at }, [$createQuoteNode(text, labels), $createTextNode(' ')]) + applied = $replaceDetectSpanWithNodes({ start: at, end: at }, [$createQuoteNode(text, labels, summary), $createTextNode(' ')]) }, PASTE_TAG) return applied } @@ -451,7 +453,7 @@ export class DraftEditorRuntime { const occurrence = span.value appendText(draft.slice(cursor, occurrence.offset)) if (span.kind === 'quote') { - paragraph.append($createQuoteNode(span.value.text, labels)) + paragraph.append($createQuoteNode(span.value.text, labels, span.value.summary)) cursor = occurrence.offset + occurrence.length continue } diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index cb8472f746..1fd208b6f7 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -14,6 +14,7 @@ import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' import type { LexicalEditor } from 'lexical' +import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import type { CommandClaim, ConsumeTokenRequest, DraftAttachmentId, DraftInitializationOptions, DraftInitializationResult, InputActions, InputEffect, InputNotice, InputState, InputTriggerController, PickOutcome, @@ -100,12 +101,17 @@ function frozen(phase: InputState['phase']): boolean { } /** Whether two projections differ in content (selection and caret excluded). */ +function sameSummary(left: QuoteSummary | undefined, right: QuoteSummary | undefined): boolean { + return left === right || (left !== undefined && right !== undefined && left.label === right.label + && left.title === right.title && left.detail === right.detail && left.body === right.body) +} + function projectionContentChanged(prev: EditorProjection, next: EditorProjection): boolean { if (prev.clipboardText !== next.clipboardText || prev.detectText !== next.detectText) return true if (prev.command !== next.command) return true if (prev.quotes.length !== next.quotes.length || prev.quotes.some((quote, i) => { const old = next.quotes[i] - return old?.text !== quote.text || old.offset !== quote.offset + return old?.text !== quote.text || old.offset !== quote.offset || !sameSummary(old.summary, quote.summary) })) return true if (prev.occurrences.length !== next.occurrences.length) return true return next.occurrences.some((occ, i) => { @@ -140,7 +146,7 @@ export class SessionInputShell implements SessionInput { } /** The public provide-channel action face (one stable identity per session). */ readonly actions: InputActions = { - insertQuote: text => this.insertQuote(text), + insertQuote: (text, summary) => this.insertQuote(text, summary), captureInsertion: () => ({ ...this.caretSpan(), draftRev: this.rev }), insertText: (text, span) => { if (frozen(this.snapshot.phase) || this.disposed) return false @@ -230,10 +236,14 @@ export class SessionInputShell implements SessionInput { this.restoreCommand() } - /** @param text - selected transcript text. @returns whether the editable draft accepted the quote. */ - insertQuote(text: string): boolean { + /** + * @param text - selected transcript text. + * @param summary - readable composer display of the quote. + * @returns whether the editable draft accepted the quote. + */ + insertQuote(text: string, summary?: QuoteSummary): boolean { if (this.disposed || this.snapshot.phase !== 'plain' || this.deps.quoteInsertionAllowed?.() === false || text.trim() === '') return false - const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }) + const inserted = this.draftEditor.insertQuote(text.replace(/\r\n?/gu, '\n'), { remove: this.deps.quoteRemoveLabel?.() ?? '' }, summary) if (inserted) this.focus() return inserted } diff --git a/packages/client/ui-conversation/src/client/input/file-intake.ts b/packages/client/ui-conversation/src/client/input/file-intake.ts new file mode 100644 index 0000000000..a46e9145a7 --- /dev/null +++ b/packages/client/ui-conversation/src/client/input/file-intake.ts @@ -0,0 +1,99 @@ +/** + * Document-level paste routing across every mounted composer. + * + * A file paste outside an editable control addresses at most one composer: + * the one that most recently held focus while it can accept files, otherwise + * the main Conversation's composer while it can. A composer inside a hidden or + * inert subtree, or behind the foreground modal dialog or menu, is never + * addressed. + */ +import { modalSelector } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ComposerFileIntake, ComposerFileIntakeTarget } from '../contract/slots.ts' + +/** Controls that own their own paste; the document-level route never takes it from them. */ +const EDITABLE = 'input, textarea, select, [contenteditable]:not([contenteditable="false"])' + +/** + * Clipboard files in clipboard order, with members the entry API reports as directories. + * @param transfer - clipboard payload of one paste event. + * @returns the pasted files and their directory members; empty when the payload has no file item. + */ +export function clipboardFiles(transfer: DataTransfer): { files: File[]; directories: Set } { + const files: File[] = [] + const directories = new Set() + for (const item of transfer.items) { + if (item.kind !== 'file') continue + const file = item.getAsFile() + if (file === null) continue + files.push(file) + if (typeof item.webkitGetAsEntry === 'function' && item.webkitGetAsEntry()?.isDirectory === true) { + directories.add(file) + } + } + return { files, directories } +} + +/** + * Create the paste router shared by the composers of one plugin instance. + * Its document listeners exist only while at least one composer is registered. + * @returns the registration callback injected into each composer. + */ +export function createComposerFileIntake(): ComposerFileIntake { + const targets = new Set() + let focused: ComposerFileIntakeTarget | undefined + let uninstall: (() => void) | undefined + + const addressable = (document: Document): ComposerFileIntakeTarget[] => { + const foreground = [...document.querySelectorAll(modalSelector)].at(-1) + return [...targets].filter(target => target.card.isConnected + && target.card.closest('[inert], [hidden]') === null + && (foreground === undefined || foreground.contains(target.card))) + } + const pasteTarget = (document: Document): ComposerFileIntakeTarget | undefined => { + const candidates = addressable(document).filter(target => target.accepts()) + if (focused !== undefined && candidates.includes(focused)) return focused + return candidates.find(target => target.occurrence === 'main') + } + + const install = (document: Document): () => void => { + const focusin = (event: FocusEvent): void => { + // Document focusin events always target a node of this document. + const node = event.target as Node + const target = [...targets].find(candidate => candidate.card.contains(node)) + if (target !== undefined) focused = target + } + const paste = (event: ClipboardEvent): void => { + // A focused composer editor consumes its own paste before bubbling here. + if (event.defaultPrevented || event.clipboardData === null) return + // The first path element sees through shadow roots, which retarget event.target to their host. + const origin = event.composedPath().find(value => value instanceof Element) + if (origin instanceof Element && origin.closest(EDITABLE) !== null) return + const { files, directories } = clipboardFiles(event.clipboardData) + if (files.length === 0) return + const target = pasteTarget(document) + if (target === undefined) return + event.preventDefault() + target.add(files, directories.size === 0 ? undefined : directories) + } + document.addEventListener('focusin', focusin, true) + document.addEventListener('paste', paste) + return () => { + document.removeEventListener('focusin', focusin, true) + document.removeEventListener('paste', paste) + } + } + + return (target) => { + targets.add(target) + const document = target.card.ownerDocument + if (target.card.contains(document.activeElement)) focused = target + uninstall ??= install(document) + return () => { + targets.delete(target) + if (focused === target) focused = undefined + if (targets.size > 0) return + uninstall?.() + uninstall = undefined + } + } +} diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css index d80240c6b2..1783694789 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css @@ -206,7 +206,7 @@ display: flex; flex: none; align-items: center; - gap: 10px; + gap: 8px; } .status { diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 4c6b8e6578..5c5d1149f8 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -146,6 +146,7 @@ export function ConversationContent(props: ConversationContentProps) { const blocked = !inert && composerBlock !== undefined const inputBar = renderSlot('conversation.composer.bar', { variant: hero ? 'hero' : 'composer', + occurrence: props.variant, ...(inert ? { disabled: true, diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 5b6407242d..f7957393d3 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -45,11 +45,11 @@ export type InputBarProps = ComposerBarProps export const InputBar = memo(function InputBar({ useSession, useInput, inputActions, keyboard, addFiles, removeAttachment, resolveDraftAttachments, - retryFileUpload, + retryFileUpload, registerFileIntake, toggleCommandMenu, stop, retry, t, renderSlot, useBusyEnter, useFileUploads, useNotices, useLexicon, useMenuLauncher, useStopShortcut, useAccess, - useProjection, sessionId, variant, disabled: inert = false, blocked, + useProjection, sessionId, variant, occurrence, disabled: inert = false, blocked, workspacePickerOpen = false, onRequestWorkspace, placeholder, accessory, }: InputBarProps) { @@ -310,6 +310,17 @@ export const InputBar = memo(function InputBar({ return installDraftKeyboardDismissal(editor, cardRef) }, [editor]) + // A document paste outside an editable control addresses at most one + // mounted composer; the shared route elects it from focus and the main + // occurrence. + useEffect(() => registerFileIntake({ + // The card is an unconditional descendant attached before this effect. + card: cardRef.current as HTMLDivElement, + occurrence, + accepts: () => gate.current.canAcceptDrop, + add: (files, directories) => { gate.current.intakeFiles(files, directories) }, + }), [registerFileIntake, occurrence]) + // Button presses steal focus from the editor; suppress at mousedown so // typing continues seamlessly. Lexical's focus() carries preventScroll and // restores the previous selection, so no reveal is needed: the caret has diff --git a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts index 9a53949566..9685b65f12 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -39,7 +39,7 @@ function sessionSnapshot(): SessionSnapshot { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: true, lastAgentError: null, @@ -62,6 +62,7 @@ function fakeSession(): SessionFace { cancel: () => Promise.reject(new Error('unused fake Session operation')), rename: () => Promise.reject(new Error('unused fake Session operation')), loadOlder: () => Promise.reject(new Error('unused fake Session operation')), + consumeOlder: () => { throw new Error('unused fake Session operation') }, loadThrough: () => Promise.reject(new Error('unused fake Session operation')), command: () => Promise.reject(new Error('unused fake Session operation')), } diff --git a/packages/client/ui-conversation/tests/file-intake.client.spec.ts b/packages/client/ui-conversation/tests/file-intake.client.spec.ts new file mode 100644 index 0000000000..260005dc41 --- /dev/null +++ b/packages/client/ui-conversation/tests/file-intake.client.spec.ts @@ -0,0 +1,203 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { fireEvent } from '@testing-library/react' +import type { ComposerFileIntakeTarget } from '../src/client/contract/slots.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' + +/** One mounted Conversation: content region, transcript, and composer card. */ +function conversation(occurrence: 'main' | 'embedded', parent: HTMLElement = document.body) { + const content = document.createElement('div') + content.dataset.conversationContent = '' + const transcript = document.createElement('p') + const card = document.createElement('div') + card.dataset.composerCard = '' + const button = document.createElement('button') + card.append(button) + content.append(transcript, card) + parent.append(content) + const add = vi.fn() + let accepting = true + const target: ComposerFileIntakeTarget = { card, occurrence, accepts: () => accepting, add } + return { content, transcript, card, button, add, target, refuse: () => { accepting = false } } +} + +function filePayload(...files: File[]) { + return { + items: files.map(file => ({ kind: 'file', getAsFile: () => file })), + getData: () => '', + } +} + +const image = new File([Uint8Array.of(1)], 'shot.png', { type: 'image/png' }) + +const registrations: (() => void)[] = [] + +/** A fresh route whose registrations the suite releases after each case. */ +function createRoute(): ReturnType { + const register = createComposerFileIntake() + return (target) => { + const leave = register(target) + registrations.push(leave) + return leave + } +} + +afterEach(() => { + for (const leave of registrations.splice(0)) leave() + document.body.replaceChildren() +}) + +describe('composer paste route', () => { + it('routes an unaddressed paste to the main composer until another composer takes focus', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + const leaveMain = register(main.target) + const leaveSide = register(side.target) + + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(false) + expect(main.add).toHaveBeenCalledWith([image], undefined) + expect(side.add).not.toHaveBeenCalled() + + side.button.focus() + main.transcript.tabIndex = -1 + main.transcript.focus() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(side.add).toHaveBeenCalledTimes(1) + expect(main.add).toHaveBeenCalledTimes(1) + + leaveSide() + leaveSide() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(2) + leaveMain() + }) + + it('reports directory members and adopts a composer already holding focus at registration', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + side.button.focus() + register(main.target) + register(side.target) + const folder = new File([], 'folder') + const payload = { + items: [ + { kind: 'string', getAsFile: () => null }, + { kind: 'file', getAsFile: () => null }, + { kind: 'file', getAsFile: () => folder, webkitGetAsEntry: () => ({ isDirectory: true }) }, + { kind: 'file', getAsFile: () => image, webkitGetAsEntry: () => null }, + ], + getData: () => '', + } + fireEvent.paste(document.body, { clipboardData: payload }) + expect(side.add).toHaveBeenCalledWith([folder, image], new Set([folder])) + expect(main.add).not.toHaveBeenCalled() + }) + + it('leaves a paste to its editable control, an earlier handler, or the browser', () => { + const register = createRoute() + const main = conversation('main') + register(main.target) + const field = document.createElement('input') + const editable = document.createElement('div') + editable.setAttribute('contenteditable', 'true') + document.body.append(field, editable) + + expect(fireEvent.paste(field, { clipboardData: filePayload(image) })).toBe(true) + expect(fireEvent.paste(editable, { clipboardData: filePayload(image) })).toBe(true) + expect(fireEvent.paste(document.body, { clipboardData: { items: [], getData: () => 'text' } })).toBe(true) + expect(fireEvent.paste(document.body, { clipboardData: null })).toBe(true) + const handled = (event: Event): void => { event.preventDefault() } + document.body.addEventListener('paste', handled) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + document.body.removeEventListener('paste', handled) + expect(main.add).not.toHaveBeenCalled() + + main.refuse() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).not.toHaveBeenCalled() + }) + + it('never addresses a hidden, inert, detached, or modal-covered composer', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + register(main.target) + register(side.target) + side.button.focus() + + side.content.setAttribute('inert', '') + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(1) + side.content.removeAttribute('inert') + + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + document.body.append(menu) + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + menu.remove() + + const dialog = document.createElement('div') + dialog.setAttribute('role', 'dialog') + dialog.setAttribute('aria-modal', 'true') + const inside = conversation('embedded', dialog) + document.body.append(dialog) + register(inside.target) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(inside.add).not.toHaveBeenCalled() + inside.button.focus() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(inside.add).toHaveBeenCalledTimes(1) + dialog.remove() + + main.content.hidden = true + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + main.content.remove() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).toHaveBeenCalledTimes(1) + expect(side.add).not.toHaveBeenCalled() + }) + + it('skips a composer that cannot accept files for the main composer, and leaves the paste when none can', () => { + const register = createRoute() + const main = conversation('main') + const side = conversation('embedded') + register(main.target) + register(side.target) + side.button.focus() + side.refuse() + + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(false) + expect(main.add).toHaveBeenCalledTimes(1) + expect(side.add).not.toHaveBeenCalled() + main.refuse() + expect(fireEvent.paste(document.body, { clipboardData: filePayload(image) })).toBe(true) + expect(main.add).toHaveBeenCalledTimes(1) + }) + + it('leaves a paste to an editable control inside a shadow root', () => { + const register = createRoute() + const main = conversation('main') + register(main.target) + const host = document.createElement('div') + document.body.append(host) + const field = document.createElement('textarea') + host.attachShadow({ mode: 'open' }).append(field) + + expect(fireEvent.paste(field, { composed: true, clipboardData: filePayload(image) })).toBe(true) + expect(main.add).not.toHaveBeenCalled() + }) + + it('removes its document listeners with the last registration', () => { + const register = createRoute() + const main = conversation('main') + register(main.target)() + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).not.toHaveBeenCalled() + const again = register(main.target) + fireEvent.paste(document.body, { clipboardData: filePayload(image) }) + expect(main.add).toHaveBeenCalledTimes(1) + again() + }) +}) diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index 69499cdff4..630ad9e2cd 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -31,12 +31,13 @@ import type { SubmitOutcome } from '../src/client/contract/input.ts' import { SessionInputShell } from '../src/client/input/facade.ts' import { $replaceDetectSpanWithText, $selectDetectSpan } from '../src/client/input/editor/span-map.ts' import type { - ComposerAttachment, ComposerAttachmentsOwnerProps, DraftFileUploads, InputActivityOwnerProps, + ComposerAttachment, ComposerAttachmentsOwnerProps, ComposerFileIntake, DraftFileUploads, InputActivityOwnerProps, } from '../src/client/contract/slots.ts' import type { DraftAttachmentId } from '../src/client/contract/input.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { en, zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -95,6 +96,8 @@ interface BenchOptions { /** The hub's steer-all face (empty-draft accelerated Enter). */ steerQueue?: () => void variant?: 'hero' | 'composer' + occurrence?: 'main' | 'embedded' + registerFileIntake?: ComposerFileIntake placeholder?: string t?: InputBarProps['t'] accessory?: React.ReactNode @@ -213,6 +216,7 @@ function bench(over?: BenchOptions) { addFiles: over?.addFiles ?? (() => null), useFileUploads: bindSnapshotSelector(createSnapshotStore(over?.fileUploads ?? {})), retryFileUpload: undefined, + registerFileIntake: over?.registerFileIntake ?? createComposerFileIntake(), removeAttachment, resolveDraftAttachments: ids => ids.flatMap((id) => { const attachment = over?.attachments?.find(candidate => candidate.id === id) @@ -230,6 +234,7 @@ function bench(over?: BenchOptions) { t: over?.t ?? makeTranslate(zh, commonZh), renderSlot, variant: over?.variant ?? 'composer', + occurrence: over?.occurrence ?? 'main', ...(over?.inert === true ? { disabled: true } : {}), ...(over?.blocked !== undefined ? { blocked: over.blocked } : {}), ...(over?.workspacePickerOpen !== undefined ? { workspacePickerOpen: over.workspacePickerOpen } : {}), @@ -636,6 +641,31 @@ describe('image draft rail', () => { expect(within.view.queryByRole('alert')).toBeNull() }) + it('joins the paste route with its card and occurrence and routes pastes through its own intake', () => { + const leave = vi.fn() + const register = vi.fn(() => leave) + const addFiles = vi.fn(() => null) + const result = bench({ addFiles, registerFileIntake: register, occurrence: 'embedded' }) + expect(register).toHaveBeenCalledTimes(1) + const target = register.mock.calls[0]![0] + expect(target.card).toBe(result.view.container.querySelector('[data-composer-card]')) + expect(target.occurrence).toBe('embedded') + expect(target.accepts()).toBe(true) + const pasted = new File([Uint8Array.of(1)], 'pasted.png', { type: 'image/png' }) + act(() => { target.add([pasted]) }) + expect(addFiles).toHaveBeenCalledWith([pasted], undefined) + + // Acceptance follows live bar state without re-registering. + result.view.rerender( false} />) + expect(target.accepts()).toBe(false) + expect(register).toHaveBeenCalledTimes(1) + result.view.rerender() + expect(leave).toHaveBeenCalledTimes(1) + expect(register.mock.calls[1]![0].occurrence).toBe('main') + result.view.unmount() + expect(leave).toHaveBeenCalledTimes(2) + }) + it('announces the format problem before any limit when the batch holds a non-image', () => { const addFiles = vi.fn(() => '仅支持 PNG、JPG、WebP、GIF 格式的图片') const result = bench({ diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index a4963d15ac..dd7143f188 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -26,6 +26,7 @@ import { SessionInputShell } from '../src/client/input/facade.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -77,6 +78,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled addFiles: () => null, useFileUploads: bindSnapshotSelector(createSnapshotStore({})), retryFileUpload: undefined, + registerFileIntake: createComposerFileIntake(), removeAttachment: () => {}, // Every id resolves so the bar's registry prune never drops a test image. resolveDraftAttachments: ids => ids.map(id => ({ @@ -95,6 +97,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled stop: vi.fn(), t: makeTranslate(zh, commonZh), variant: 'composer', + occurrence: 'main', } return render() } diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 82c9ba4d56..aed6c05c2a 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -38,6 +38,7 @@ import { $replaceDetectSpanWithText } from '../src/client/input/editor/span-map. import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { zh } from '../src/client/locales.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -179,6 +180,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo addFiles: () => null, useFileUploads: bindSnapshotSelector(createSnapshotStore({})), retryFileUpload: undefined, + registerFileIntake: createComposerFileIntake(), removeAttachment: () => {}, // Every id resolves so the bar's registry prune never drops a test image. resolveDraftAttachments: ids => ids.map(id => ({ @@ -206,6 +208,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo useStopShortcut: bindSnapshotSelector(createSnapshotStore([])), t: makeTranslate(zh, commonZh), variant: 'composer', + occurrence: 'main', } const view = render() const textarea = view.container.querySelector('[data-composer-input]')! diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 8a116a9a15..713c74df88 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -56,7 +56,7 @@ interface TestSnapshot extends SessionSnapshot { function snapshotWith(queue: UserMessage[], nextStep: UserMessage[] = []): TestSnapshot { return { sessionId: SID, running: true, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, + hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, subagent: null, pendingSubmissions: [], lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false, testInbox: { 'next-turn': queue, 'next-step': nextStep }, diff --git a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx index d365852fc0..8582f67e55 100644 --- a/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-composer.client.spec.tsx @@ -93,6 +93,54 @@ describe('QuoteNode composer lifecycle', () => { }) }) + it('shows an owner summary in place of the text while drafts, editor state, and the sent message keep the text', async () => { + const summary = { label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' } + const { shell, sink } = bench() + const mirrored: DraftSnapshot[] = [] + shell.bindDraftPersistence((document) => { mirrored.push(document) }) + expect(shell.actions.insertQuote(quote, summary)).toBe(true) + const persisted = mirrored.at(-1) + expect(persisted).toEqual({ text: '> selected source text ', references: [], quotes: [{ offset: 0, length: 22, text: quote, summary }] }) + const view = render() + expect(view.container.querySelector('[data-quote-preview-text]')?.textContent).toBe('index.ts L78src/index.ts L78 rename this') + view.unmount() + + const restored = bench().shell + restored.setDraft(persisted as DraftSnapshot) + expect(restored.draftSnapshot).toEqual(persisted) + const reparsed = restored.editor.parseEditorState(restored.editor.getEditorState().toJSON()) + expect(reparsed.read(() => $nodesOfType(QuoteNode).map(node => [node.getQuoteText(), node.getQuoteSummary()]))) + .toEqual([[quote, summary]]) + const plain = bench().shell + plain.insertQuote(quote) + expect(plain.editor.parseEditorState(plain.editor.getEditorState().toJSON()) + .read(() => $nodesOfType(QuoteNode).map(node => node.getQuoteSummary()))).toEqual([undefined]) + + shell.submit('queue') + expect(sink).toHaveBeenCalledWith('> selected source text', [], 'queue', expect.any(AbortSignal), expect.any(Function)) + await vi.waitFor(() => { expect(shell.snapshot.draft).toBe('') }) + }) + + it('treats a summary added or changed at the same text and offset as a draft change', () => { + const summary = { label: 'index.ts L78', title: 'src/index.ts', detail: 'L78', body: 'rename this' } + const { shell } = bench() + const mirrored: DraftSnapshot[] = [] + shell.bindDraftPersistence((document) => { mirrored.push(document) }) + shell.insertQuote(quote) + const plain = shell.draftSnapshot + const revision = shell.snapshot.draftRev + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary }] }) + expect(shell.snapshot.draftRev).toBeGreaterThan(revision) + expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }]) + expect(mirrored.at(-1)?.quotes).toEqual([{ offset: 0, length: 22, text: quote, summary }]) + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] }) + expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this') + shell.setDraft({ ...plain, quotes: [{ offset: 0, length: 22, text: quote, summary: { ...summary, body: 'keep this' } }] }) + expect(shell.draftSnapshot.quotes?.[0]?.summary?.body).toBe('keep this') + shell.setDraft(plain) + expect(shell.draftSnapshot.quotes).toEqual([{ offset: 0, length: 22, text: quote }]) + }) + it('treats insert, close removal, Backspace, undo, and redo as whole-node operations', async () => { const direct = bench().shell direct.insertQuote(quote) diff --git a/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx b/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx index 1d88b71aee..0819ea3407 100644 --- a/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx +++ b/packages/client/ui-conversation/tests/quote-user-text.client.spec.tsx @@ -15,6 +15,17 @@ describe('quote draft spans', () => { expect(parseStoredDraft({ ...draft, quotes: [quote, quote] })).toBeUndefined() }) + it('restores a stored quote summary and leaves summary-less drafts without one', () => { + const summary = { label: 'a.ts R1', title: 'src/a.ts', detail: 'R1', body: 'why' } + const draft = { text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote', summary }] } + expect(parseStoredDraft(JSON.parse(JSON.stringify(draft)))).toEqual(draft) + const { detail: _detail, ...withoutDetail } = summary + const brief = { ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: withoutDetail }] } + expect(parseStoredDraft(JSON.parse(JSON.stringify(brief)))).toEqual(brief) + expect(parseStoredDraft({ text: '> quote', references: [], quotes: [{ offset: 0, length: 7, text: 'quote' }] })?.quotes?.[0]?.summary).toBeUndefined() + expect(parseStoredDraft({ ...draft, quotes: [{ offset: 0, length: 7, text: 'quote', summary: { label: 'a.ts' } }] })).toBeUndefined() + }) + it('serializes reference owners outside quotes into ordinary Markdown text', async () => { const serialize = vi.fn(() => Promise.resolve('@[Session](dsh-session:id)')) const quote = '/review @literal' diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 2a099a7d7b..6f599b2d22 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -36,6 +36,7 @@ import type { ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, } from '../src/client/contract/slots.ts' import type { ViewTab } from '../src/client/contract/views.ts' +import { createComposerFileIntake } from '../src/client/input/file-intake.ts' // Every session-scope fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource'] @@ -313,6 +314,7 @@ function mount( addFiles={() => null} useFileUploads={bindSnapshotSelector(createSnapshotStore({}))} retryFileUpload={undefined} + registerFileIntake={createComposerFileIntake()} removeAttachment={() => {}} resolveDraftAttachments={() => []} toggleCommandMenu={vi.fn()} diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 0043997b3b..0b9b722071 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -46,7 +46,15 @@ async function fixture() { ctx.provide('sandboxPolicy', { workspaceRoot: cwd } as never) await ctx.plugin({ inject: ['fs', 'sandboxPolicy'], - apply: (scope) => { new WorkspaceFiles(scope, { maxBytes: 1024, maxFileBytes: 1024, maxLines: 100, maxEntries: 100 }) }, + apply: (scope) => { + new WorkspaceFiles(scope, { + maxBytes: 1024, + maxFileBytes: 1024, + maxLines: 100, + maxEntries: 100, + search: { maxResults: 100, maxEntries: 1000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, + }) + }, }) const readEvent = vi.fn(async (_request: SessionEventReadRequest) => { throw new SessionQueryError('missing', 'SESSION_QUERY_EVENT_NOT_FOUND') diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index 6d6057d204..f3fc8a46dc 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -36,7 +36,15 @@ async function fixture() { ctx.provide('sandboxPolicy', { workspaceRoot: cwd } as never) await ctx.plugin({ inject: ['fs', 'sandboxPolicy'], - apply: (scope) => { new WorkspaceFiles(scope, { maxBytes: 1024, maxFileBytes: 1024, maxLines: 100, maxEntries: 100 }) }, + apply: (scope) => { + new WorkspaceFiles(scope, { + maxBytes: 1024, + maxFileBytes: 1024, + maxLines: 100, + maxEntries: 100, + search: { maxResults: 100, maxEntries: 1000, graceMs: 3000, timeoutMs: 30000, stderrMaxBytes: 65536 }, + }) + }, }) const resolveAgent = vi.fn(() => { throw new Error('Agent activation is unavailable') }) const readEvent = vi.fn(async (request: SessionEventReadRequest) => { diff --git a/packages/client/ui-goal/README.i18n.yaml b/packages/client/ui-goal/README.i18n.yaml index 815b11e50f..809bbef816 100644 --- a/packages/client/ui-goal/README.i18n.yaml +++ b/packages/client/ui-goal/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-goal/use-this-package: - en: 7f6620a84a087d07 - zh: 80071126cc64b3e5 + en: 796ed31dda615e5a + zh: b797d7bd3d3f34bc /deepseek-ai-dsh-client-ui-goal/use-this-package/the-command-input-bubble: en: 05f0360b6c6dd3e9 zh: d14c3f15dc4cea5b diff --git a/packages/client/ui-goal/README.md b/packages/client/ui-goal/README.md index 986e5c6811..cadad96470 100644 --- a/packages/client/ui-goal/README.md +++ b/packages/client/ui-goal/README.md @@ -25,7 +25,7 @@ The Web GUI goal surface shows both the durable goal state and its current proce ## Use this package -Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. An armed active goal offers pause; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. +Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. The strip orders its actions edit, clear, then pause or resume, matching the Queue rows' edit and remove positions. An armed active goal offers pause, shown disabled until its activation is known; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. ### The command-input bubble diff --git a/packages/client/ui-goal/README.zh.md b/packages/client/ui-goal/README.zh.md index 36e47153d9..9d96d3fa0b 100644 --- a/packages/client/ui-goal/README.zh.md +++ b/packages/client/ui-goal/README.zh.md @@ -25,7 +25,7 @@ Web GUI 的 goal 界面同时显示持久 goal 状态及当前的进程本地激 ## 使用本包 -与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。已 armed 的 active goal 提供暂停动作;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 +与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。条带的动作按编辑、清除、暂停或恢复的顺序排列,与 Queue 行的编辑和移除位置一致。已 armed 的 active goal 提供暂停动作,激活状态未知时暂停按钮显示为禁用;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 ### 指令输入气泡 diff --git a/packages/client/ui-goal/src/client/GoalBar.module.css b/packages/client/ui-goal/src/client/GoalBar.module.css index 798cd0d9f6..9d7c99716c 100644 --- a/packages/client/ui-goal/src/client/GoalBar.module.css +++ b/packages/client/ui-goal/src/client/GoalBar.module.css @@ -100,7 +100,7 @@ .actions { display: flex; align-items: center; - gap: 10px; + gap: 8px; flex: none; } diff --git a/packages/client/ui-goal/src/client/GoalBar.tsx b/packages/client/ui-goal/src/client/GoalBar.tsx index 120538c3c4..c6bb31711b 100644 --- a/packages/client/ui-goal/src/client/GoalBar.tsx +++ b/packages/client/ui-goal/src/client/GoalBar.tsx @@ -1,9 +1,10 @@ /** * GoalBar: the goal indicator docked above the message composer (input dock * strip). A present goal shows a goal glyph, a phase label, the truncated - * objective, and icon actions — resume when active-disarmed, paused, or - * blocked, edit (inline form in the same strip), and clear. Goal creation - * lives on the `/goal` command, not here: loading (undefined), no goal + * objective, and icon actions — edit (inline form in the same strip), clear, + * then pause when armed (disabled until activation is known) or resume when + * active-disarmed, paused, or blocked. + * Goal creation lives on the `/goal` command, not here: loading (undefined), no goal * (null), and complete goals render nothing. Durable state arrives as the projected whole snapshot; * process-local activation arrives through the injected activation hook. */ @@ -128,7 +129,8 @@ export function GoalBar({ goal, activation, onEdit, onPause, onResume, onClear, const title = goal.phase === 'blocked' ? goal.blockedReason?.message : undefined const label = goal.phase === 'active' ? activeLabel(activation, t) : t(PHASE_LABELS[goal.phase]) - const showResume = goal.phase !== 'active' || activation === 'disarmed' + const resume = goal.phase !== 'active' || activation === 'disarmed' + const toggleLabel = t(resume ? 'action.resume' : 'action.pause') return (
@@ -137,20 +139,6 @@ export function GoalBar({ goal, activation, onEdit, onPause, onResume, onClear, {goal.objective} {actionError !== null && {actionError}}
- {goal.phase === 'active' && activation === 'armed' && ( - - - - )} - {showResume && ( - - - - )} + {/* Until activation arrives, an active goal keeps a disabled pause so edit and clear stay in place. */} + + +
diff --git a/packages/client/ui-goal/tests/goalbar.client.spec.tsx b/packages/client/ui-goal/tests/goalbar.client.spec.tsx index cc9dda1c67..aa86379524 100644 --- a/packages/client/ui-goal/tests/goalbar.client.spec.tsx +++ b/packages/client/ui-goal/tests/goalbar.client.spec.tsx @@ -146,13 +146,21 @@ describe('GoalBar', () => { expect(screen.getByRole('textbox', { name: '目标内容' })).toBeTruthy() }) - it('active goal: the pause action pauses', () => { + it('active goal: the pause action follows edit and clear, and pauses', () => { const actions = makeActions() render() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '暂停目标']) fireEvent.click(screen.getByRole('button', { name: '暂停目标' })) expect(actions.onPause).toHaveBeenCalledTimes(1) }) + it('active goal with unknown activation: keeps a disabled pause after edit and clear', () => { + const actions = makeActions() + render() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '暂停目标']) + expect(screen.getByRole('button', { name: '暂停目标' }).hasAttribute('disabled')).toBe(true) + }) + it('active disarmed goal: "待继续的目标" with a resume action instead of pause', () => { const actions = makeActions() render() @@ -163,10 +171,11 @@ describe('GoalBar', () => { expect(screen.queryByRole('button', { name: '暂停目标' })).toBeNull() }) - it('paused goal: "已暂停的目标" with a resume action before edit', () => { + it('paused goal: "已暂停的目标" with a resume action after edit and clear', () => { const actions = makeActions() render() expect(screen.getByText('已暂停的目标')).toBeTruthy() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '恢复目标']) fireEvent.click(screen.getByRole('button', { name: '恢复目标' })) expect(actions.onResume).toHaveBeenCalledTimes(1) }) diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index cfc7291505..60b0cb137d 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: e07d3a607d54cb47 - zh: 9a7342f05b64db38 + en: c9022effccebd157 + zh: 54e76ec13b5c1029 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: 22da59203ca974e6 - zh: f288bd6a193bccef + en: 423b66c7f36f7c40 + zh: 9b891fb7c8a8d240 /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: 59c434b70679fc16 - zh: 7fe9e52b0bb82df1 + en: 31af13d29ff76a1c + zh: 6a08bd80d71c6434 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 9b0f75963b..5664376801 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -39,11 +39,11 @@ The **Open locally** shortcut captures the main Session’s directory and rememb File menus list the discovered associated applications without a separate “Open in default app” row. “Show file location” stays in a fixed footer separated from the scrolling applications. A successful query with only one available action renders a single button without a dropdown. Initial file-association loading uses a gray skeleton icon. When the Host identifies a default application the menu marks it “(default)” and the main button opens it; otherwise the first associated application takes that place, so the main button reveals the file only when no application is registered. Directory menus have no reveal row. Choosing a file application does not change the system default. An unpreviewable file uses the same menu in a 40px-high split button with an icon and action text; its label is “Open” or “Show file location” according to the default action. -Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. +Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A successful answer also replaces the page’s record for the file’s association class unless a later-started query has already answered it; the class is the final name extension, compared case-sensitively, or the whole path when the name has none. Mounted controls do not read that record and keep their own answer until their menu opens again, so the file header and a context menu can name different applications for one file meanwhile. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. -Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata before querying applications. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. +Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata, then name the application recorded for the file’s type without waiting for the Host. A type’s first opening on the page waits up to 300 ms for the Host’s answer; if none arrives by then, the row reads “Open in default application” and opens the file through its OS association. Each opening re-queries the Host in the background; a changed answer updates the open menu in place, and a failed query keeps the recorded answer. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. File menus copy absolute paths without line numbers; URL copying preserves query and fragment. Image files also expose image copy and original download, alongside the existing file actions. Successful downloads and saves show the shared Toast; picker cancellation is silent. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening or plugin unload cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot; when its own file type’s answer changes, it re-resolves synchronously from the path its opening verified, so the context-menu registry keeps the other rows while the application row changes. A type without a recorded answer holds the file contribution until its refresh settles, 300 ms pass, or the menu closes; the registry opens the menu once every contribution is ready, so the whole menu waits. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. @@ -93,6 +93,9 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. +- **File associations are cached by type for the page.** Files sharing a final name extension share one answer; extensions that differ only in case, such as `.PNG` and `.png`, are separate types. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu. Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect, and one file’s empty answer shows the row disabled for the type’s other files the same way. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. +- **A type’s first file menu can open late.** The whole menu waits up to 300 ms for that type’s first answer on the page, and a slower answer still changes the row after opening. +- **One background refresh at a time.** Opening another file menu cancels the previous menu’s unanswered query, so that type keeps its earlier answer, or none, until its next opening. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index 7bac1ae79f..69598cbc60 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -39,11 +39,11 @@ kind: "package-reference" 文件菜单列出已发现的关联应用,不单列“用默认应用打开”。“显示文件位置”固定在菜单底部,通过分隔线与滚动的应用列表分开。查询成功且只有一个可用操作时显示单按钮,不再显示下拉箭头。文件关联首次加载时使用灰色骨架图标。Host 识别出默认应用时,菜单将该项标注为“(默认)”,主按钮打开该应用;否则第一个关联应用占据该位置,只有在一个关联应用都没有时主按钮才执行文件定位。目录菜单不包含定位项。选择文件应用不修改系统默认应用。无法预览文件时,空态使用同一菜单,按钮增大到 40px 高并显示图标和动作文字;根据默认动作显示“打开”或“显示文件位置”。 -使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 +使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询成功后,结果还会替换本页面中该文件关联类别的记录,除非更晚发起的查询已经给出回答;类别按文件名的最后一个扩展名划分(区分大小写),没有扩展名的文件按完整路径划分。已挂载控件不读取这份记录,会保留自己的回答,直到再次打开其菜单,因此在此期间同一个文件在文件标题栏和右键菜单中可能显示不同的应用。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 -右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,再查询关联应用。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 +右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,然后直接显示该文件类型已记录的应用,不等待 Host。某个类型在本页面第一次打开菜单时,最多等待 Host 回答 300 毫秒;到时仍未回答,这一项显示“使用默认应用打开”,通过系统的文件关联打开文件。每次打开菜单都会在后台重新查询 Host;回答有变化时,已打开的菜单原地更新,查询失败则保留已记录的回答。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 文件菜单复制不含行号的绝对路径;网址复制保留查询参数与锚点。图片文件在既有文件操作之外,还提供复制图片与下载原图。下载和保存成功后显示共享 Toast,取消选择器时不提示。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单或插件卸载会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照;只有本文件类型的回答变化时,才基于本次打开时验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。尚无记录的类型会让文件菜单项等到这次刷新结束、满 300 毫秒或菜单关闭;注册表在所有菜单项都就绪后才打开菜单,所以整个菜单都会等待。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 @@ -93,6 +93,9 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 +- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答;只有大小写不同的扩展名(如 `.PNG` 和 `.png`)算作不同类型。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果;某个文件的空回答也会以同样的方式,让同类型其他文件的这一项先显示为禁用。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 +- **某个类型的第一次文件菜单可能打开得较慢。** 整个菜单最多等待该类型在本页面的第一个回答 300 毫秒;回答更慢时,菜单打开后这一项仍会原地变化。 +- **同一时间只有一次后台刷新。** 打开另一个文件的菜单会取消前一个菜单尚未返回的查询,该类型保留之前的回答(或仍没有回答),直到下次打开。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 5810a3aab7..aa69108391 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -3,18 +3,44 @@ import { useState } from 'react' import { IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { ContextMenuTargetMap, MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-api-workspace-files/remote' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppController } from './controller.ts' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' import type { OpenInAppToastSource } from './open-toast.tsx' +type Applications = readonly SessionWorkspacePathApplication[] +/** A file menu's verified Host path and the association answer its resolution showed. */ +interface Verification { readonly absolutePath: string; readonly shown: Applications | undefined } + +/** + * How long a file menu waits for the first association answer of its file type before opening with the + * unnamed default-application row; most first answers arrive sooner, so the row rarely changes after opening. + */ +const FIRST_ANSWER_WAIT_MS = 300 + +/** + * @param pending - settles without rejecting. + * @param ms - longest wait. + * @param signal - ends the wait early. + * @returns settles when `pending` settles, after `ms`, or on abort, whichever comes first; the timer never outlives it. + */ +function settleWithin(pending: Promise, ms: number, signal: AbortSignal): Promise { + return new Promise((settle) => { + const done = (): void => { clearTimeout(timer); signal.removeEventListener('abort', done); settle() } + const timer = setTimeout(done, ms) + signal.addEventListener('abort', done, { once: true }) + void pending.then(done) + }) +} + /** * Register native opening, original-path reveal, and URL actions. * @param ctx - declared plugin dependencies. @@ -76,40 +102,88 @@ export function registerContextMenus( ] }, }), 'open-in-app: directory context menu') + const fileMenu = (target: ContextMenuTargetMap['file'], absolutePath: string | undefined): MenuAction[] => { + const { sessionId, path, line } = target + const available = absolutePath !== undefined + const desktop = paths.desktop.getSnapshot() === true && available + // Undefined until the Host first answers for this file type; the row then opens through the association. + const apps = desktop ? paths.cachedApplications(absolutePath) : [] + const application = apps?.find(app => app.default) + const openApplication = absolutePath === undefined || !desktop ? undefined + : application !== undefined ? () => open(absolutePath, 'open', application.id) + : apps === undefined ? () => open(absolutePath, 'open') : undefined + // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. + const openIn = (destination: 'sidebar' | 'float') => () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { + destination, ...(line === undefined ? {} : { params: { line } }), + }) + } + return [ + { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, + { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, + { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, + ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, + { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), + icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, + disabled: openApplication === undefined, ...openApplication === undefined ? {} : { run: openApplication } }, + { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), + run: async () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) + ctx.contextMenus.notify(t('menu.copied'), true) + } }, + ] + } + // The Host path from each file target's latest successful stat and the answer its menu showed, shared by menus open + // on one target object at once. A stat clears it while running; answers arriving meanwhile need no re-resolution, as + // that stat's resolution reads the newest answers. + const verified = new WeakMap() + // The target whose changed association answer is being applied; only that re-resolution reuses the verified path, + // so every opening runs its own stat. The in-place update relies on the registry re-resolving synchronously from + // the notification, without which the menu stats again, and on a synchronous resolution replacing rows without + // clearing them first, without which the rows flicker. + let answering: ContextMenuTargetMap['file'] | undefined ctx.effect(() => ctx.contextMenus.register({ id: 'open-in-app.file', target: 'file', order: 100, - resolve: async (target, signal) => { - const { sessionId, path, line } = target - await paths.load() - const absolutePath = await resolvePath(sessionId, path, signal) - const available = absolutePath !== undefined - const desktop = paths.desktop.getSnapshot() === true && available - const apps = desktop ? await paths.applications(absolutePath, signal) : [] - signal.throwIfAborted() - const application = apps?.find(app => app.default) - // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. - const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { - destination, ...(line === undefined ? {} : { params: { line } }), + observe: target => [{ + getSnapshot: paths.associations.getSnapshot.bind(paths.associations), + subscribe: (listener: () => void) => { + // The answer this subscription last applied for a verification; answers for other file types leave it unchanged. + let applied: { readonly verification: Verification; readonly applications: Applications | undefined } | undefined + return paths.associations.subscribe(() => { + const verification = verified.get(target) + if (verification === undefined) return + const applications = paths.cachedApplications(verification.absolutePath) + const current = applied?.verification === verification ? applied.applications : verification.shown + if (applications === current) return + applied = { verification, applications } + answering = target + try { listener() } finally { answering = undefined } }) - } - return [ - { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, - { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, - { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, - ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, - { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), - icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, - disabled: application === undefined, - ...absolutePath === undefined || application === undefined ? {} : { run: () => open(absolutePath, 'open', application.id) } }, - { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), - run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) - ctx.contextMenus.notify(t('menu.copied'), true) - } }, - ] + }, + }], + resolve: (target, signal) => { + const reused = answering === target ? verified.get(target) : undefined + if (reused !== undefined) return fileMenu(target, reused.absolutePath) + verified.delete(target) + return (async () => { + await paths.load() + const absolutePath = await resolvePath(target.sessionId, target.path, signal) + signal.throwIfAborted() + if (absolutePath === undefined) return fileMenu(target, undefined) + if (paths.desktop.getSnapshot() === true) { + // Every opening re-queries so a changed association reaches this menu; a type's first opening waits for it briefly. + const unanswered = paths.cachedApplications(absolutePath) === undefined + const refreshed = paths.refreshApplications(absolutePath) + if (unanswered) { + await settleWithin(refreshed, FIRST_ANSWER_WAIT_MS, signal) + signal.throwIfAborted() + } + } + verified.set(target, { absolutePath, shown: paths.cachedApplications(absolutePath) }) + return fileMenu(target, absolutePath) + })() }, }), 'open-in-app: file context menu') ctx.effect(() => ctx.contextMenus.register({ diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index e706f9eb25..84bdc9168e 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -56,6 +56,7 @@ export function apply(ctx: ClientContext): void { const controller = new OpenInAppController() void controller.load() const paths = new OpenInAppPathController(ctx.remote) + ctx.effect(() => () => { paths.dispose() }, 'open-in-app: association refreshes') ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'open-in-app: dictionaries') const t = ctx.locale.bind(NS) // Keep operation feedback visible after its initiating panel closes. diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index 4484bb29b9..85ea703b5d 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -1,12 +1,38 @@ /** * Host desktop availability, file associations, and open/reveal actions over the Session Remote. - * The desktop answer is read once per page; a failed read renders no control. + * The desktop answer is read once per page; a failed read renders no control. Association answers + * are recorded per association class so menus can show them without waiting for the Host. */ -import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionOpenWorkspacePathRequest, SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppOutcome, OpenInAppPathFailure } from './outcome.ts' +type Applications = readonly SessionWorkspacePathApplication[] + +/** + * Name the association class of a Host path: desktops look handlers up by the final name extension, so + * files sharing it share one answer; a name without one (`Makefile`, `.env`) is its own class. + */ +function associationKey(path: string): string { + const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) + const dot = name.lastIndexOf('.') + return dot > 0 && dot < name.length - 1 ? `extension:${name.slice(dot)}` : `path:${path}` +} + +/** The compared application fields; a field added to the type fails to compile until it is listed here. */ +const APPLICATION_FIELDS = Object.keys({ + id: true, name: true, default: true, icon: true, +} satisfies Record) as readonly (keyof SessionWorkspacePathApplication)[] + +/** Equal answers keep the published snapshot, so observers re-resolve only when an answer changes. */ +function sameApplications(left: Applications, right: Applications): boolean { + return left.length === right.length && left.every((app, index) => { + const other = right[index] + return other !== undefined && APPLICATION_FIELDS.every(field => app[field] === other[field]) + }) +} + /** What a path gesture asks of the Host desktop: the default application, or the file manager showing the file. */ export type OpenInAppPathAction = 'open' | 'reveal' @@ -24,11 +50,25 @@ export interface OpenInAppPathRemote { } } -/** Page-lifetime desktop availability and the open/reveal carrier shared by every path control. */ +/** + * Page-lifetime desktop availability, association answers, and the open/reveal carrier shared by every path control. + * Answers are kept per association class for the page's life and grow with the classes queried. + */ export class OpenInAppPathController { /** Whether the Host desktop can open paths; null until the Host answered, false also after a failed read. */ readonly desktop: SnapshotStore = createSnapshotStore(null) + private readonly answers = createSnapshotStore>(new Map()) + /** Latest successful answer per association class; the snapshot keeps its identity until an answer changes. */ + readonly associations: ObservableSnapshot> = this.answers private loading: Promise | undefined + private readonly lifetime = new AbortController() + /** The latest background refresh; a newer refresh aborts it. */ + private refresh: AbortController | undefined + /** Start order of the query whose answer each class holds; an earlier query never replaces a later one. */ + private readonly answeredBy = new Map() + /** One icon string per application id, reused by every class that lists the application so its data URL is held once. */ + private readonly icons = new Map() + private queries = 0 /** * @param remote - the Session Remote namespace answering availability and running gestures. @@ -66,20 +106,70 @@ export class OpenInAppPathController { } /** - * Refresh the file's OS associations; failures remain distinct from an empty handler list. + * Query the file's current OS associations and record a successful answer for its association class. + * Failures remain distinct from an empty handler list and leave the recorded answer in place. * @param path - file path reported by the Host. - * @param signal - lifetime of the requesting preview. + * @param signal - lifetime of the requesting control. * @returns application metadata, or null when the query fails. */ - async applications(path: string, signal: AbortSignal): Promise { - let result: RemoteResult + async applications(path: string, signal: AbortSignal): Promise { + const order = ++this.queries + let result: RemoteResult try { result = await this.remote.session.workspacePathApplications({ path }, signal) } catch (_error) { // The control reports query failure and keeps file reveal available. return null } - return result.ok ? result.value : null + if (!result.ok) return null + this.record(associationKey(path), order, result.value) + return result.value + } + + /** + * Read the recorded answer of a file's association class without querying the Host. + * @param path - absolute Host path of the file. + * @returns the latest successful answer, or undefined before a query of this class succeeded. + */ + cachedApplications(path: string): Applications | undefined { + return this.answers.getSnapshot().get(associationKey(path)) + } + + /** + * Re-query a file's associations in the background. One refresh runs at a time: it outlives the + * requesting menu and ends with its answer, the next refresh, which cancels it, or {@link dispose}. + * @param path - absolute Host path of the file. + * @returns settles without rejecting when this refresh's query settles, after any answer is recorded; + * already settled after {@link dispose}. + */ + refreshApplications(path: string): Promise { + if (this.lifetime.signal.aborted) return Promise.resolve() + this.refresh?.abort() + const refresh = new AbortController() + this.refresh = refresh + return this.applications(path, AbortSignal.any([this.lifetime.signal, refresh.signal])).then(() => {}) + } + + /** Cancel background refreshes and refuse new ones; recorded answers stay readable. */ + dispose(): void { + this.lifetime.abort() + } + + private record(key: string, order: number, applications: Applications): void { + if ((this.answeredBy.get(key) ?? 0) > order) return + this.answeredBy.set(key, order) + const answers = this.answers.getSnapshot() + const previous = answers.get(key) + if (previous !== undefined && sameApplications(previous, applications)) return + const next = new Map(answers) + next.set(key, applications.map((app) => { + if (app.icon === null) return app + const icon = this.icons.get(app.id) + if (icon === app.icon) return { ...app, icon } + this.icons.set(app.id, app.icon) + return app + })) + this.answers.set(next) } private async run(): Promise { diff --git a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts index ca27f69e50..274d379207 100644 --- a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts @@ -49,10 +49,13 @@ afterEach(() => { /** The Session Remote slice the path controls call; answers a desktop and acknowledges every gesture. */ const remote = { session: { - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal) => ({ ok: true as const, value: [] })), canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: { opened: true as const } })), }, + workspaceFiles: { + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: `/w/${path}` } })), + }, } /** Boot the browser half over a real slot tree that declares the header list and the document-preview seats. */ @@ -335,6 +338,24 @@ describe('open-in-app browser half', () => { expect(ctx.slots.entries('deliverables.file.actions')).toHaveLength(0) }) + it('lets a file-menu association refresh outlive the menu and cancels it with the plugin', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) + const { ctx, fiber } = await bench() + let refresh: AbortSignal | undefined + remote.session.workspacePathApplications.mockImplementationOnce((_request, signal) => { + refresh = signal + return new Promise(() => {}) + }) + const menu = ctx.contextMenus.resolve({ kind: 'file', value: { sessionId: 'files' as SessionId, path: 'notes.txt' } }) + await menu.ready + expect(remote.workspaceFiles.stat).toHaveBeenCalledWith('files', 'notes.txt', expect.any(AbortSignal)) + expect(remote.session.workspacePathApplications).toHaveBeenCalledWith({ path: '/w/notes.txt' }, refresh) + menu.dispose() + expect(refresh?.aborted).toBe(false) + await fiber.dispose() + expect(refresh?.aborted).toBe(true) + }) + it('injects the announcement seat into the delivery entries and releases every entry with the fiber', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) const { ctx, fiber } = await bench() diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 10407f9f54..4a0e8963ae 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -7,6 +7,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { SessionId } from '@deepseek-ai/dsh-session' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import type { ContextMenus, ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { FileActionSource, FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/client' import { OpenInAppPathController } from '../src/client/open-path.ts' import { OpenInAppController } from '../src/client/controller.ts' @@ -15,6 +17,9 @@ import { registerContextMenus } from '../src/client/context-menus.tsx' import type { OpenInAppToastSource } from '../src/client/open-toast.tsx' const sessionId = SessionId('menu-actions') +type Applications = readonly SessionWorkspacePathApplication[] +/** Let settled Remote answers finish their queued continuations. */ +const settle = () => new Promise((resolve) => { setTimeout(resolve, 0) }) afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) async function boot() { @@ -27,13 +32,13 @@ async function boot() { const remote = { session: { canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [ - { id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }, - ] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal): Promise> => ({ + ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }], + })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: undefined })), }, workspaceFiles: { - stat: vi.fn(async () => ({ ok: true as const, value: { absolutePath: '/workspace/file.svg' } })), + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: path.startsWith('/') ? path : `/workspace/${path}` } })), readBytes: vi.fn(async () => ({ ok: true as const, value: { data: [...new TextEncoder().encode('')] } })), }, } @@ -82,14 +87,17 @@ it('routes file actions through an explicit host, the line, native association a const h = await boot() // A menu raised inside a floating panel names that panel; the open names a host instead, never a pane. const file = { kind: 'file', value: { sessionId, path: 'file.svg', paneId: 'float7' as never, line: 24 } } as const - const items = (await h.resolve(file)).source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) - expect(items.map(item => [item.id, item.label, item.icon?.key])).toEqual([ + const first = await h.resolve(file) + const items = () => first.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + await vi.waitFor(() => { expect(items().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(items().map(item => [item.id, item.label, item.icon?.key])).toEqual([ ['open-in-app.file/sidebar', 'menu.openInSidebar', 'open-in-app.sidebar'], ['open-in-app.file/float', 'menu.openInFloat', 'open-in-app.float'], ['open-in-app.file/reveal', 'menu.reveal', 'open-in-app.reveal'], ['open-in-app.file/open', 'open.title', 'open-in-app.application'], ['open-in-app.file/copyPath', 'menu.copyPath', 'open-in-app.copy'], ]) + first.dispose() await h.choose(file, 'open-in-app.file/sidebar') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(sessionId, expect.stringContaining('file.svg'), { destination: 'sidebar', params: { line: 24 } }) @@ -114,7 +122,8 @@ it('routes file actions through an explicit host, the line, native association a const simple = { kind: 'file', value: { sessionId: SessionId('absent'), path: '/file.unknown' } } as const h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const menu = await h.resolve(simple) - expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + // The Host's empty answer arrives within the first-answer wait, so the row opens disabled. + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) }) expect(menu.source.getSnapshot().some(item => item.id.endsWith('/copyImage'))).toBe(false) expect(menu.source.getSnapshot().filter(item => item.id.startsWith('file-actions.')).map(item => item.id)) .toEqual(['file-actions.file/saveAs']) @@ -122,10 +131,153 @@ it('routes file actions through an explicit host, the line, native association a expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'sidebar' }) h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const floating = await h.resolve(simple) + expect(floating.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) floating.select('open-in-app.file/float') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'float' }) }) +it('names the application when the first answer of a file type arrives within the wait', async () => { + const h = await boot() + // The answer arrives a macrotask later, after a resolution that did not wait would have published its rows. + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + setTimeout(() => { answer({ ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: null }] }) }, 10) + })) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + const labels: (string | undefined)[] = [] + const stop = menu.source.subscribe(() => { + labels.push(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label) + }) + await menu.ready + stop() + expect(labels.filter(label => label !== undefined)).toEqual(['open.title']) + menu.dispose() +}) + +it('waits for the first answer of a file type at most 300 ms, and a dismissal ends the wait', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + onTestFinished(() => { vi.useRealTimers() }) + const h = await boot() + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise(() => {})) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + let ready = false + void menu.ready.then(() => { ready = true }) + await vi.advanceTimersByTimeAsync(299) + expect(ready).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(ready).toBe(true) + expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.dispose() + const dismissed = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'todo.md' } }) + await vi.advanceTimersByTimeAsync(100) + expect(vi.getTimerCount()).toBe(1) + dismissed.dispose() + await dismissed.ready + expect(vi.getTimerCount()).toBe(0) + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens file menus after the first-answer wait and changes only the application row in place', async () => { + const h = await boot() + const answers: ((answer: RemoteResult) => void)[] = [] + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise((answer) => { answers.push(answer) })) + const file = { kind: 'file', value: { sessionId, path: 'notes.txt' } } as const + const menu = await h.resolve(file) + const rows = () => menu.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + const application = () => rows().find(item => item.id === 'open-in-app.file/open') + expect(answers).toHaveLength(1) + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + expect(application()?.icon).toEqual({ key: 'open-in-app.application' }) + const published: number[] = [] + const stop = menu.source.subscribe(() => { published.push(rows().length) }) + answers[0]!({ ok: true, value: [ + { id: '/Applications/TextEdit.app', name: 'TextEdit', default: false, icon: null }, + { id: '/Applications/Sublime Text.app', name: 'Sublime Text', default: true, icon: 'data:image/png;base64,c3Vi' }, + ] }) + await vi.waitFor(() => { expect(application()).toMatchObject({ label: 'open.title', icon: { src: 'data:image/png;base64,c3Vi' } }) }) + stop() + expect(published.length).toBeGreaterThan(0) + expect(published.every(count => count === 5)).toBe(true) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { + expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.txt', application: '/Applications/Sublime Text.app' }) + }) + // Another file of the same type shows the recorded answer at once and asks the Host again. + const other = await h.resolve({ kind: 'file', value: { sessionId, path: 'todo.txt' } }) + const otherApplication = () => other.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(otherApplication()?.label).toBe('open.title') + expect(answers).toHaveLength(2) + answers[1]!({ ok: true, value: [] }) + await vi.waitFor(() => { expect(otherApplication()).toMatchObject({ label: 'menu.defaultApp', disabled: true }) }) + other.dispose() + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens through the OS association until the Host first answers, including after failed queries', async () => { + const h = await boot() + let refuse = () => {} + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + refuse = () => { answer({ ok: false } as never) } + })) + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.md' } }) + const application = () => menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + refuse() + await settle() + expect(h.paths.cachedApplications('/workspace/notes.md')).toBeUndefined() + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.md' }) }) + await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'opened' }) }) +}) + +it('verifies a file menu once when answers for other files arrive during verification', async () => { + const h = await boot() + let release = () => {} + const verifying = new Promise((resolve) => { release = resolve }) + h.remote.workspaceFiles.stat.mockImplementation(async (_sessionId: SessionId, path: string) => { + await verifying + return { ok: true as const, value: { absolutePath: `/workspace/${path}` } } + }) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + release() + await menu.ready + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + menu.dispose() +}) + +it('verifies every opening of a file target, whatever order the registry observes and resolves in', async () => { + const register = vi.spyOn(MenuRegistry.prototype, 'register') + const h = await boot() + const contribution = register.mock.calls.map(([input]) => input).find(input => input.id === 'open-in-app.file')! + const target = { sessionId, path: 'notes.txt' } + // Resolving without observing first, as a registry that subscribes after its first resolution would. + await contribution.resolve(target, new AbortController().signal) + await contribution.resolve(target, new AbortController().signal) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) +}) + +it('re-resolves an open file menu only when its own file type answers differently', async () => { + const h = await boot() + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + const shown = menu.source.getSnapshot() + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + expect(menu.source.getSnapshot()).toBe(shown) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/todo.txt', new AbortController().signal) + const changed = menu.source.getSnapshot() + expect(changed.find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: true }) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(menu.source.getSnapshot()).toBe(changed) + menu.dispose() +}) + it('keeps copy-path available on failed metadata and reports native action failures', async () => { const h = await boot() const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const @@ -139,14 +291,25 @@ it('keeps copy-path available on failed metadata and reports native action failu h.remote.session.openWorkspacePath.mockResolvedValueOnce({ ok: false } as never) await h.choose(file, 'open-in-app.file/reveal') await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'failed', failure: 'revealError' }) }) + await vi.waitFor(() => { expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) }) + // A failed query keeps the recorded answer. h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: false } as never) - expect((await h.resolve(file)).source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + const kept = await h.resolve(file) + await vi.waitFor(() => { + expect(h.remote.session.workspacePathApplications.mock.settledResults.every(result => result.type !== 'incomplete')).toBe(true) + }) + await settle() + expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) + expect(kept.source.getSnapshot().find(item => item.id.endsWith('/open'))).toMatchObject({ label: 'open.title', disabled: false }) + kept.dispose() h.paths.desktop.set(false) h.fileActions.canSaveAs = false + const queried = h.remote.session.workspacePathApplications.mock.calls.length const web = await h.resolve(file) expect(web.source.getSnapshot().some(item => item.id.endsWith('/saveAs'))).toBe(false) expect(web.source.getSnapshot().filter(item => ['/open', '/reveal'].some(suffix => item.id.endsWith(suffix))) .every(item => item.disabled)).toBe(true) + expect(h.remote.session.workspacePathApplications).toHaveBeenCalledTimes(queried) }) it('opens links in the registered browser, externally, and on the clipboard', async () => { diff --git a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts index e542b9164c..3222bbb738 100644 --- a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts @@ -94,3 +94,91 @@ it('distinguishes failed association queries from an empty application list', as const rejecting = new OpenInAppPathController(remoteOf({ workspacePathApplications: async () => { throw new Error('disconnected') } })) expect(await rejecting.applications('/file.mp3', new AbortController().signal)).toBeNull() }) + +describe('OpenInAppPathController association answers', () => { + type Answer = Awaited> + const app = (name: string, icon: string | null = null) => ({ id: `/Applications/${name}.app`, name, default: true, icon }) + const answered = (...apps: ReturnType[]): Answer => ({ ok: true, value: apps }) + /** A Remote whose association queries settle when the test answers them, and reject once cancelled. */ + function deferredRemote() { + const queries: { path: string; signal: AbortSignal | undefined; answer: (result: Answer) => void }[] = [] + const workspacePathApplications = vi.fn((request: { path: string }, signal?: AbortSignal) => new Promise((answer, reject) => { + queries.push({ path: request.path, signal, answer }) + signal?.addEventListener('abort', () => { reject(new Error('cancelled')) }, { once: true }) + })) + return { queries, controller: new OpenInAppPathController(remoteOf({ workspacePathApplications })) } + } + + it('shares an answer across files with the same final extension and keeps extensionless names apart', async () => { + const answers: Record = { + '/w/notes.txt': answered(app('TextEdit')), '/w/Makefile': answered(app('Xcode')), '/w/.env': answered(app('Zed')), + } + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications: async ({ path }) => answers[path]! })) + const signal = new AbortController().signal + expect(controller.cachedApplications('/w/notes.txt')).toBeUndefined() + for (const path of Object.keys(answers)) await controller.applications(path, signal) + expect(controller.cachedApplications('/elsewhere/todo.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('C:\\work\\archive.tar.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('/w/NOTES.TXT')).toBeUndefined() + expect(controller.cachedApplications('/w/Makefile')).toEqual([app('Xcode')]) + expect(controller.cachedApplications('/other/Makefile')).toBeUndefined() + expect(controller.cachedApplications('/w/.env')).toEqual([app('Zed')]) + expect(controller.cachedApplications('/w/draft.')).toBeUndefined() + }) + + it('publishes changed answers only, and an earlier query never replaces a later answer', async () => { + const { queries, controller } = deferredRemote() + const signal = new AbortController().signal + const earlier = controller.applications('/w/a.txt', signal) + const later = controller.applications('/w/b.txt', signal) + queries[1]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + expect(await later).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const published = controller.associations.getSnapshot() + queries[0]!.answer(answered(app('TextEdit'))) + expect(await earlier).toEqual([app('TextEdit')]) + expect(controller.associations.getSnapshot()).toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const unchanged = controller.applications('/w/c.txt', signal) + queries[2]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + await unchanged + expect(controller.associations.getSnapshot()).toBe(published) + const changed = controller.applications('/w/c.txt', signal) + queries[3]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit'))) + await changed + expect(controller.associations.getSnapshot()).not.toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit')]) + const other = controller.applications('/w/d.md', signal) + queries[4]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'))) + await other + expect(controller.cachedApplications('/w/e.md')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3')]) + expect(controller.cachedApplications('/w/e.txt')).toHaveLength(2) + }) + + it('keeps the recorded answer through refused and rejected queries', async () => { + const workspacePathApplications = vi.fn() + .mockResolvedValueOnce(answered(app('Preview'))) + .mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'boom', {}) }) + .mockRejectedValueOnce(new Error('down')) + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications })) + const signal = new AbortController().signal + await controller.applications('/w/a.png', signal) + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(controller.cachedApplications('/w/b.png')).toEqual([app('Preview')]) + }) + + it('runs one background refresh at a time, cancelling the older for the newer file, and disposal cancels it', async () => { + const { queries, controller } = deferredRemote() + void controller.refreshApplications('/w/a.txt') + void controller.refreshApplications('/w/b.txt') + expect(queries.map(query => [query.path, query.signal?.aborted])).toEqual([['/w/a.txt', true], ['/w/b.txt', false]]) + queries[1]!.answer(answered(app('TextEdit'))) + await vi.waitFor(() => { expect(controller.cachedApplications('/w/c.txt')).toEqual([app('TextEdit')]) }) + void controller.refreshApplications('/w/d.md') + controller.dispose() + expect(queries[2]).toMatchObject({ path: '/w/d.md', signal: { aborted: true } }) + void controller.refreshApplications('/w/e.json') + expect(queries).toHaveLength(3) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('TextEdit')]) + }) +}) diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index 6122766724..af4f1664fd 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -24,8 +24,8 @@ en: 2a44a378364912db zh: 8c514ce17469747f /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-a-bundle: - en: 390dc85aceac033a - zh: 746ceae45f70dd33 + en: 188ebf6f1590bad1 + zh: e6d41e8586190fa0 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-one-row-of-a-bundle: en: d3627d4dba5e6cc2 zh: e0d0eada4c20331f @@ -33,8 +33,8 @@ en: e9da90f03691101b zh: 902cda935a4ce3c8 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/detail-page-extension-points: - en: d5e3cad5c31cae59 - zh: 6dc38f09b410d247 + en: 16dbfb0ab558c951 + zh: adf098c0751a7144 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/page-tabs: en: 99c06790c2163746 zh: daa87ad1ce9a76ae diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 1b23459a8b..155ef55105 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -78,7 +78,7 @@ After the checks, the list toolbar says how many plugins can be updated, that al ### Switching a bundle -A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete; the Settings Plugins section's Plugin list tab inspects their plugins. +A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete; the Settings Plugins section's Plugin list tab inspects their plugins. ### Switching one row of a bundle @@ -100,7 +100,7 @@ The bundle's patch must declare the row under that id, and the registration exis ### Detail page extension points -A plugin with something to say about a bundle, a row, or an official plugin it does not own contributes to that object's page through three list slots the page declares: `plugins.detail.actions` for a control at the head of the page, before the page's own switch and uninstall; `plugins.detail.badge` for a tag beside the title, after the version, experimental, and problem tags; and `plugins.detail.section` for a section under the page's own content — after the source on a bundle's page, after the configuration on a row's or an official plugin's page. Every entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`, where `pkg` and `row` carry the name, version, installed and enabled facts, and the row list a contribution decides on. An entry renders null for a subject it has nothing for and draws its own section chrome; the page orders entries by `order`. +A plugin with something to say about a bundle, a row, or an official plugin it does not own contributes to that object's page through three list slots the page declares: `plugins.detail.actions` for a control at the head of the page, before the page's own switch and uninstall; `plugins.detail.badge` for a tag beside the title, after the version, experimental, and problem or not-running tags; and `plugins.detail.section` for a section under the page's own content — after the source on a bundle's page, after the configuration on a row's or an official plugin's page. Every entry is rendered with the page's `subject`: `{ kind: 'bundle', pkg }`, `{ kind: 'row', pkg, row }`, or `{ kind: 'item', id }`, where `pkg` and `row` carry the name, version, installed and enabled facts, and the row list a contribution decides on. An entry renders null for a subject it has nothing for and draws its own section chrome; the page orders entries by `order`. ```tsx ignore-check ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 8062b0e426..586d8adadf 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -78,7 +78,7 @@ Host 将网络失败或超时归因于 GitHub 地址,且提供 npmmirror 时 ### 切换一个组合包 -组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据;设置中「插件」分区的「插件列表」标签页负责查看它们的插件。 +组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据;设置中「插件」分区的「插件列表」标签页负责查看它们的插件。 ### 切换组合包里的一行 @@ -100,7 +100,7 @@ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({ ### 详情页扩展点 -对某个不属于自己的组合包、行或官方插件有话要说的插件,通过本页声明的三个 list slot 向该对象的页面贡献内容:`plugins.detail.actions` 在页头放一个控件,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁放一个标签,位于版本、实验性和异常标签之后;`plugins.detail.section` 在页面自身内容之下放一个区块——组合包页在来源信息之后,行页和官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`,其中 `pkg` 与 `row` 携带包名、版本、是否已安装、是否启用以及行列表这些供贡献者判断的事实。条目对无话可说的 subject 返回 null,自绘区块外观;页面按 `order` 排列条目。 +对某个不属于自己的组合包、行或官方插件有话要说的插件,通过本页声明的三个 list slot 向该对象的页面贡献内容:`plugins.detail.actions` 在页头放一个控件,位于页面自己的开关和卸载之前;`plugins.detail.badge` 在标题旁放一个标签,位于版本、实验性和异常或未运行标签之后;`plugins.detail.section` 在页面自身内容之下放一个区块——组合包页在来源信息之后,行页和官方插件页在配置之后。每个条目都以页面的 `subject` 渲染:`{ kind: 'bundle', pkg }`、`{ kind: 'row', pkg, row }` 或 `{ kind: 'item', id }`,其中 `pkg` 与 `row` 携带包名、版本、是否已安装、是否启用以及行列表这些供贡献者判断的事实。条目对无话可说的 subject 返回 null,自绘区块外观;页面按 `order` 排列条目。 ```tsx ignore-check ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({ diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index d24d1f08fe..f7fac78f91 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -12,6 +12,10 @@ --plugin-page-top-inset: 28px; --bundle-progress-size: 14px; --bundle-toggle-gap: 8px; + /* A card head's inset, icon size, and gap after the icon; a card's reason lines align under its title from these. */ + --card-head-inset: 8px; + --card-icon-size: 48px; + --card-head-gap: 14px; display: flex; flex-direction: column; @@ -387,8 +391,8 @@ .cardHead { display: flex; align-items: center; - gap: 14px; - padding: 8px; + gap: var(--card-head-gap); + padding: var(--card-head-inset); } .cardIcon { @@ -396,14 +400,19 @@ flex: none; align-items: center; justify-content: center; - width: 48px; - height: 48px; + width: var(--card-icon-size); + height: var(--card-icon-size); /* The same hairline frame as the component rows below. */ border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-lg); color: var(--dsw-alias-label-secondary); } +/* A card's reason lines start under its title. */ +.card > .reason { + padding: 0 var(--card-head-inset) var(--card-head-inset) calc(var(--card-head-inset) + var(--card-icon-size) + var(--card-head-gap)); +} + .packageImage { object-fit: contain; } diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index 41df8e96a2..53f0b7d67b 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -419,12 +419,30 @@ function EnableSwitch({ pkg, title, t, busy, onSetEnabled }: { ) } -/** The status one card carries: running, off, or a problem the Host reported. */ -function packageStatus(pkg: PackageView): 'running' | 'disabled' | 'problem' { +/** The status one card carries: running, off, not running because the Host skipped a selected bundle's layer, or another problem. */ +type PackageStatus = 'running' | 'disabled' | 'not-running' | 'problem' + +/** The tag each status shows beside the title on a card and on its page; running and off show none. */ +const STATUS_TAG_KEYS = { + 'running': undefined, + 'disabled': undefined, + 'not-running': 'statusNotRunning', + 'problem': 'statusProblem', +} satisfies Record + +/** A selected bundle the Host reports an error for is not running when none of its rows has a live entry. */ +function packageStatus(pkg: PackageView): PackageStatus { + if (pkg.enabled && pkg.error !== undefined && pkg.rows.every(row => row.entryId === undefined)) return 'not-running' if (pkg.error !== undefined || (pkg.enabled && pkg.rows.some(row => row.phase === 'failed'))) return 'problem' return pkg.enabled ? 'running' : 'disabled' } +/** The danger tag a status carries. */ +function StatusTag({ status, t }: { readonly status: PackageStatus; readonly t: Translate }): ReactNode { + const key = STATUS_TAG_KEYS[status] + return key === undefined ? null : {t(key)} +} + /** The head every card shares: the artwork, the name that opens the page beside its tags, its one-liner, and what sits at the end. */ function CardHead({ title, t, onOpen, icon, tags, description, end }: { readonly title: string @@ -529,7 +547,10 @@ function updateAvailable(pkg: PackageView): boolean { || ((target.spec.startsWith('link:') || pkg.source?.startsWith('link:') === true) && pkg.source !== target.spec) } -/** One package as a card that opens its page: its name, its one-liner, its tags, and its bundle switch. */ +/** + * One package as a card that opens its page: its name, its one-liner, its tags, its bundle switch, and why the Host + * skipped it or does not support its platform. + */ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, onSetEnabled }: { readonly pkg: PackageView /** The newer registry version a version check offers. */ @@ -558,7 +579,7 @@ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, on tags={( <> {beta ? {t('statusBeta')} : null} - {status === 'problem' ? {t('statusProblem')} : null} + {pkg.availability === 'missing' ? {t(pkg.installed ? 'statusMissingFiles' : 'statusNotInstalled')} : null} {updateAvailable(pkg) || newer !== undefined ? {t('statusUpdateAvailable')} : null} @@ -567,7 +588,10 @@ function PackageCard({ pkg, t, resolveText, busy, highlighted, newer, onOpen, on end={} /> - {pkg.error?.code === 'unsupported-platform' &&

{managementText(pkg.error, t)}

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

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

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

{title}

{pkg.version === undefined ? null : {t('versionTag', { version: pkg.version })}} {beta ? {t('statusBeta')} : null} - {status === 'problem' ? {t('statusProblem')} : null} + {pkg.availability === 'missing' ? {t(pkg.installed ? 'statusMissingFiles' : 'statusNotInstalled')} : null} {updateAvailable(pkg) || newer !== undefined ? {t('statusUpdateAvailable')} : null} {renderSlot('plugins.detail.badge', { subject })} @@ -799,7 +823,8 @@ function PackageDetail({ ) : null} - {pkg.availability === 'missing' ? null : ( { pkg({ name: '@deepseek-ai/dsh-web-app', installed: false, removable: false }), pkg({ name: 'dsh-protected', readOnlyReason: 'management-required' }), pkg({ name: '@acme/dsh-tool', enabled: false }), - // Selected by the profile but not a bundle: a problem the person can switch off, in the profile's own group. + // Selected by the profile but not a bundle: its layer is skipped, so it reads as not running. pkg({ name: 'dsh-selected', installed: false, error: { code: 'not-bundle' } }), pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', installed: false, optional: true, removable: false, enabled: false }), ], @@ -747,7 +747,7 @@ describe('PluginManagerPage', () => { expect(cards.map(card => card.getAttribute('data-plugin-package'))).toEqual([ '@deepseek-ai/dsh-experimental-voice-input-bundle', 'dsh-better-sidebar', 'dsh-broken', 'dsh-protected', '@acme/dsh-tool', 'dsh-selected', ]) - expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'problem']) + expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'not-running']) // Group titles have no counts; the official bundle retains its experimental marker. expect(screen.getByRole('heading', { name: en.bundlesTitle })).toBeTruthy() expect(screen.getByRole('heading', { name: en.extensionsTitle })).toBeTruthy() @@ -755,7 +755,8 @@ describe('PluginManagerPage', () => { expect(screen.getAllByText(en.statusBeta)).toHaveLength(1) expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', '@acme/dsh-tool') })).toHaveProperty('disabled', false) expect(screen.getByText('A sidebar.')).toBeTruthy() - expect(screen.getAllByText(en.statusProblem)).toHaveLength(2) + expect(screen.getAllByText(en.statusProblem)).toHaveLength(1) + expect(screen.getAllByText(en.statusNotRunning)).toHaveLength(1) // The switch acts on the bundle; a bundle the Host cannot read stays off, a protected one stays as it is. fireEvent.click(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })) expect(actions.setEnabled).toHaveBeenCalledWith('dsh-better-sidebar', false) @@ -904,6 +905,51 @@ describe('PluginManagerPage', () => { expect(screen.getByText(`${en.reasonLabel}: native preparation unavailable`)).toBeTruthy() }) + it.each([en, zh])('marks a selected bundle the Host skipped as not running with its reason, keeping its switch on', (dict) => { + const name = 'dsh-late' + const { actions, setLanguage } = renderTab({ packages: [pkg({ name, error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] } })] }) + setLanguage(dict) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('not-running') + expect(within(card).getByText(dict.statusNotRunning)).toBeTruthy() + expect(within(card).queryByText(dict.statusProblem)).toBeNull() + // The card names the incompatibility without the requirement list the page carries. + expect(within(card).getByText(`${dict.reasonIncompatibleVersionUnnamed}${dict.sentenceSeparator}${dict.reasonIncompatibleInstalled}`)).toBeTruthy() + const toggle = within(card).getByRole('switch', { name: dict.enableToggle.replace('{name}', name) }) + expect(toggle.getAttribute('aria-checked')).toBe('true') + fireEvent.click(toggle) + expect(actions.setEnabled).toHaveBeenCalledExactlyOnceWith(name, false) + }) + + it('keeps a selected bundle whose rows run as a problem when the Host reports an error beside them', () => { + renderTab({ packages: [pkg({ error: { code: 'unsupported-platform' }, rows: [row()] })] }) + const card = document.querySelector('[data-plugin-package="dsh-better-sidebar"]') as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('problem') + expect(within(card).getByText(en.statusProblem)).toBeTruthy() + }) + + it('keeps a selected bundle running when only its metadata carries a diagnostic', () => { + const name = 'dsh-better-sidebar' + const error = 'dsh.bundle.listedByDefault must be a boolean' + renderTab({ packages: [pkg({ meta: { error }, rows: [row()] })] }) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(card.getAttribute('data-plugin-status')).toBe('running') + expect(within(card).queryByText(en.statusNotRunning)).toBeNull() + expect(within(card).getByText(en.metadataError.replace('{error}', error))).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(detail.querySelector('[data-plugin-rows]')).not.toBeNull() + }) + + it('lists the rows of a skipped layer whose patch the Host read, none of them live', () => { + const name = 'dsh-late' + renderTab({ packages: [pkg({ name, error: { code: 'unsupported-platform' }, rows: [{ rowId: 'late', moduleName: name, enabled: false, phase: null }] })] }) + fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(within(detail).getByText(en.statusNotRunning)).toBeTruthy() + expect(within(detail).getAllByRole('listitem').filter(item => item.hasAttribute('data-plugin-row'))).toHaveLength(1) + }) + it('shows Computer Use permission guidance on the experimental plugins page', () => { const description = 'Review application access before use.' const { actions } = renderTab({ packages: [pkg({ @@ -1617,14 +1663,20 @@ describe('PluginManagerPage', () => { expect(actions.uninstall).toHaveBeenCalledWith('dsh-better-sidebar') fireEvent.click(within(detail).getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })) expect(actions.setEnabled).toHaveBeenCalledWith('dsh-better-sidebar', false) + // A bundle without rows says so. + set({ packages: [pkg()] }) + expect(within(detail).getByText(en.partsEmpty)).toBeTruthy() // A problem and a protection the Host reports read on the page in the dictionary's words; the page leaves with the crumb. set({ packages: [pkg({ error: { code: 'operation-error', diagnostic: 'unreadable' }, readOnlyReason: 'management-required' })] }) expect(within(detail).getByText(`${en.reasonLabel}: unreadable`)).toBeTruthy() expect(within(detail).getByText(en.reasonManagementRequired)).toBeTruthy() expect(within(detail).getByRole('button', { name: en.uninstallLabel.replace('{name}', 'dsh-better-sidebar') })).toHaveProperty('disabled', true) - expect(within(detail).getByText(en.partsEmpty)).toBeTruthy() set({ packages: [pkg({ error: { code: 'not-bundle' } })] }) expect(within(detail).getByText(`${en.reasonLabel}: ${en.reasonNotBundle}`)).toBeTruthy() + // The Host skipped this selected bundle's layer without reading its patch: it is not running, and its rows are unknown. + expect(within(detail).getByText(en.statusNotRunning)).toBeTruthy() + expect(within(detail).queryByText(en.statusProblem)).toBeNull() + expect(detail.querySelector('[data-plugin-rows]')).toBeNull() set({ packages: [pkg({ error: { code: 'operation-error' } })] }) expect(within(detail).getByText(`${en.reasonLabel}: ${en.reasonOperationError}`)).toBeTruthy() // An incompatibility reads from its structured packages in the dictionary's words, one sentence per package. diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index b15c957779..662fc787a4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -21,8 +21,8 @@ en: 54c5085d03bf4c53 zh: 6b5114206ca545f3 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: 2fc65b908307b52e - zh: e5c1181ecd2da6e5 + en: 8265fa792c6fd9ec + zh: 600d2af4d5a3d183 /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: en: e2649937f077d4e0 zh: 6ad604cb5adfc16b @@ -45,8 +45,8 @@ en: 45f4cd1ef96bb6d2 zh: f264d25b780ad1dc /deepseek-ai-dsh-client-ui-primitives/further-exploration: - en: daa908e173136285 - zh: 5f8492ce8a4c4e48 + en: 19f1407f92cb8264 + zh: 16205d2db9c91ad1 /deepseek-ai-dsh-client-ui-primitives/model-experience: en: 3120df665299c634 zh: 1d9f365d091d0d2a diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 60151abe0f..5c817b94b2 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -97,7 +97,7 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` or `Medium`. Line artwork uses stroke widths of 1 and 1.3 SVG user units respectively; the `size` prop controls rendered dimensions. Strokes scale with the viewport: a 1-unit stroke in a 16-unit view box renders at 0.875 CSS px at 14px and 0.75 CSS px at 12px, before further transforms. The renderer does not apply non-scaling strokes; filled contours scale as geometry and do not respond to stroke-width changes. Shared menus render icons at 14px, or 12px in compact lists, through `Menu.module.css`; these are rendered sizes, not fixed stroke widths. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `IconEyeOutlineRegular`/`Medium` draw an open eye with a pupil and `IconEyeOffOutlineRegular`/`Medium` the same contour crossed by a diagonal slash, for paired show and hide toggles. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A portalled `Menu` caps its card height against the layout viewport, with its pinned footer outside the inner scrolling region; child cards use their own body portal, so a scrolling parent never clips them. `HoverCard` adds 20px to the frame's published top clearance, or keeps 20px in native fullscreen, while preserving its own minimum margin in ordinary browsers; while an anchor is inside that top strip, the card is never pushed lower than the anchor's bottom edge plus its gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use CSS Anchor Positioning to follow their trigger and constrain their dimensions to the layout viewport. Every placement candidate reserves 12px layout-viewport margins and uses the frame overlay inset as its minimum top edge; pointer-positioned contextual menus keep 12px at the top. When the preferred placement cannot fit, CSS tries a horizontal adjustment or the opposite side before using a window-bounded fallback. Browser zoom and panning move the menu with the page; it may extend beyond the visual viewport, including while the keyboard is open. Internal scrolling, dismissal, and focus restoration remain independent. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. It stays hidden until its first fit, prefers the requested side, then tries the opposite and perpendicular sides, sliding along the anchor without covering it when a side fits. Horizontal placements keep a 10px gap; vertical placements use `gap` (8px by default). Width and height stay within a 12px viewport margin; text wraps, and content taller than the viewport scrolls when pinned. If no side fits, a stable viewport-bounded fallback can overlap the anchor. Viewport resize refreshes the anchor coordinates; label-size changes reuse them. Fitting does not synchronously measure the bubble or trigger a React render. Touch presses dismiss unpinned hints and do not trigger hover hints, including compatibility mouse events. Mouse entry opens hints only while `(any-hover: hover)` reports an available hover-capable input, excluding iOS mouse entry caused by a tapped icon changing. Keyboard focus and explicit click-to-open explanations remain available on touch-only devices. Opt-in `openOnClick` lets an informational button pin the bubble by click or tap and associates it with the anchor description. Another click or tap, Escape, Tab, or an outside pointerdown closes it. Ordinary action buttons execute their action directly without a touch tooltip. Opt-in `onlyWhenClipped` shows the bubble only when the anchor or an HTML element inside it overflows horizontally when the bubble is about to show, so a label that repeats ellipsis-cut text appears only while it adds information. @@ -209,7 +209,7 @@ These pages place the atoms in the client stack and the design system. ----- -`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text; editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation. +`QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text unless the owner supplies a `QuoteSummary`: its label and body then replace the inline excerpt, assistive technology reads the title and optional detail in place of the label, and the popover shows its title, optional detail, and body on every hover. Editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation. `MarkdownDelegate.getTriggerProps` receives explicit file, URL, or original-image targets and returns gesture props. File paths and line numbers are carried by callbacks. File mentions can supply `contextMenuProps`; `ImageLightbox.contextMenuProps` delegates the original image gesture. An image menu owns Escape and Tab while it holds focus, returning to the preview before closing it. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 83dc9032e7..f3e1c1719a 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -97,7 +97,7 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 或 `Medium` 结尾。线条图形分别使用 1 和 1.3 SVG 用户单位的描边宽度;`size` prop 控制渲染尺寸。描边随视口缩放:16 单位 viewBox 中宽度为 1 的描边,在 14px 下为 0.875 CSS px,在 12px 下为 0.75 CSS px,尚未计入额外变换。渲染器不使用非缩放描边;填充轮廓随几何缩放,不受 stroke-width 变化影响。共享菜单通过 `Menu.module.css` 将图标渲染为 14px,紧凑列表为 12px;这些是渲染尺寸,不是固定描边宽度。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`IconEyeOutlineRegular`/`Medium` 绘制带瞳孔的睁眼,`IconEyeOffOutlineRegular`/`Medium` 在同一轮廓上加一条斜线,用于成对的显示与隐藏开关。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。portal 模式的 `Menu` 按布局视口限制卡片高度,固定页脚位于内部滚动区域之外;子卡片使用各自的 body portal,父级滚动不会裁剪它们。`HoverCard` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,卡片不会被推到低于锚点底边加自身间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 通过 CSS Anchor Positioning 跟随触发元素,并按布局视口限制尺寸。每个候选位置都保留 12px 布局视口边距,并将框架浮层起点作为顶部下限;按指针定位的上下文菜单顶部保留 12px。首选位置放不下时,CSS 尝试横向调整或相反方向,最后使用窗口内的回退位置。浏览器缩放和平移时,菜单随页面移动,可以超出视觉视口,包括键盘打开时。内部滚动、菜单关闭和焦点恢复保持独立。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前保持隐藏,优先使用指定方向,再尝试相反方向和垂直于该方向的两侧;只要某一侧容得下,就沿锚点平移而不遮挡锚点。左右放置保留 10px 间距,上下放置使用 `gap`(默认 8px)。宽高限制在视口内并保留 12px 边距;文本自动换行,超出视口高度的内容在固定气泡后可滚动。若所有方向都放不下,则使用稳定的视口内回退位置,可能遮挡锚点。视口尺寸变化会重新读取锚点坐标,标签尺寸变化则复用坐标;定位不会同步测量气泡,也不会触发 React 渲染。 触摸按下会关闭未固定的提示,且不会触发悬停提示,包括触摸后的兼容鼠标事件。只有 `(any-hover: hover)` 表明存在可悬停的输入设备时,鼠标进入才会打开提示,从而排除 iOS 因已点击图标变化而生成的鼠标进入事件。仅有触摸输入的设备仍可使用键盘聚焦提示和显式点击打开的说明。信息按钮可显式启用 `openOnClick`,通过鼠标或触摸点击固定气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮在触摸点击时直接执行操作,不显示 Tooltip。可选的 `onlyWhenClipped` 只在气泡即将显示时锚点或其内部某个 HTML 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 @@ -209,7 +209,7 @@ kind: "package-library" ----- -`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文;可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。 +`QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文,除非所有者提供 `QuoteSummary`:此时行内摘录改为显示其 label 和 body,辅助技术以 title 和可选的 detail 代替 label 朗读,每次悬停时弹层显示其 title、可选的 detail 和 body。可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。 `MarkdownDelegate.getTriggerProps` 接收明确的文件、链接或原图目标并返回手势 props。文件路径与行号通过回调传递。文件引用可提供 `contextMenuProps`;`ImageLightbox.contextMenuProps` 转发原图手势。图片菜单持有焦点时负责 Escape 与 Tab,先返回预览再关闭预览。 diff --git a/packages/client/ui-primitives/src/QuotePreview.module.css b/packages/client/ui-primitives/src/QuotePreview.module.css index 1418d8393c..19be7febf6 100644 --- a/packages/client/ui-primitives/src/QuotePreview.module.css +++ b/packages/client/ui-primitives/src/QuotePreview.module.css @@ -22,6 +22,43 @@ white-space: pre-wrap; } +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.inlineBody { + color: var(--dsw-alias-label-secondary); +} + +.summary { + display: flex; + flex-direction: column; + gap: 4px; + padding: 8px 10px; + font-size: 14px; + line-height: 20px; +} + +.summaryTitle { + color: var(--dsw-alias-state-business-primary); + overflow-wrap: anywhere; +} + +.summaryDetail { + color: var(--dsw-alias-label-secondary); +} + +.summaryBody { + color: var(--dsw-alias-label-primary); + overflow-wrap: anywhere; + white-space: pre-wrap; +} + .source { min-width: 0; padding: 0; diff --git a/packages/client/ui-primitives/src/QuotePreview.tsx b/packages/client/ui-primitives/src/QuotePreview.tsx index 4cc56d2cec..f9a9eb5cd0 100644 --- a/packages/client/ui-primitives/src/QuotePreview.tsx +++ b/packages/client/ui-primitives/src/QuotePreview.tsx @@ -25,10 +25,24 @@ export interface QuotePreviewRemoval { readonly onRemove: () => void } +/** Owner-supplied readable form of a quote whose exact text is long structured content. */ +export interface QuoteSummary { + /** Short inline label shown before `body` in place of the exact text; assistive technology reads `title` and `detail` instead. */ + readonly label: string + /** First popover line, such as a file path; also the label's accessible text. */ + readonly title: string + /** Secondary popover line, such as a line range. */ + readonly detail?: string | undefined + /** Main text, such as a user's comment, shown inline after `label` and in full in the popover. */ + readonly body: string +} + /** Presentation inputs for one compact quote excerpt. */ export interface QuotePreviewProps { - /** Exact selected text rendered inline and exposed in a popover while clipped. */ + /** Exact selected text rendered inline and exposed in a popover while clipped, unless `summary` replaces it. */ readonly text: string + /** Readable replacement for `text`: its label renders inline and its popover opens on every hover. */ + readonly summary?: QuoteSummary | undefined /** Composer-only removal action; omit for inert sent quotes. */ readonly removal?: QuotePreviewRemoval | undefined } @@ -36,10 +50,10 @@ export interface QuotePreviewProps { /** * Render one width-capped quote preview shared by editable drafts and sent messages. * Clipped excerpts open a content-sized, scrollable popover that fits within the viewport. - * @param props - selected text and optional localized removal action. - * @returns a non-navigating quote preview with a full-text popover only while clipped. + * @param props - selected text, optional summary, and optional localized removal action. + * @returns a non-navigating quote preview with a full-text popover only while clipped, or a summary popover. */ -export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element { +export function QuotePreview({ text, summary, removal }: QuotePreviewProps): JSX.Element { const sourceRef = useRef(null) const [truncated, setTruncated] = useState(false) useLayoutEffect(() => { @@ -86,7 +100,15 @@ export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element )} - {text} + + {summary === undefined ? text : ( + <> + + {summary.detail === undefined ? summary.title : `${summary.title} ${summary.detail}`} + {' '}{summary.body} + + )} + ) return ( @@ -95,9 +117,17 @@ export function QuotePreview({ text, removal }: QuotePreviewProps): JSX.Element grouped fitContent openDelayMs={0} - disabled={!truncated} + disabled={summary === undefined && !truncated} anchor={preview} - content={} + content={summary === undefined + ? + : ( + + )} /> ) } diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index 28a3819995..b5f7a16028 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -24,6 +24,8 @@ export const ICON_ARTWORK = { 'save-outline': { size: 16, svg: strokeWidth => `` }, 'new-chat-outline': { size: 16, svg: strokeWidth => `` }, 'search-outline': { size: 16, svg: strokeWidth => `` }, + 'eye-outline': { size: 16, svg: strokeWidth => `` }, + 'eye-off-outline': { size: 16, svg: strokeWidth => `` }, 'globe-outline': { size: 14, svg: strokeWidth => `` }, 'settings-outline': { size: 16, svg: strokeWidth => `` }, 'panel-left-outline': { size: 16, svg: strokeWidth => `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index b6f03f1299..4d28b0376a 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -42,6 +42,18 @@ export const IconSearchOutlineRegular = productIcon('search-outline', 'regular') /** Medium IconSearchOutline artwork with a 1.3px stroke. */ export const IconSearchOutlineMedium = productIcon('search-outline', 'medium') +/** Regular one-pixel IconEyeOutline artwork. */ +export const IconEyeOutlineRegular = productIcon('eye-outline', 'regular') + +/** Medium IconEyeOutline artwork with a 1.3px stroke. */ +export const IconEyeOutlineMedium = productIcon('eye-outline', 'medium') + +/** Regular one-pixel IconEyeOffOutline artwork. */ +export const IconEyeOffOutlineRegular = productIcon('eye-off-outline', 'regular') + +/** Medium IconEyeOffOutline artwork with a 1.3px stroke. */ +export const IconEyeOffOutlineMedium = productIcon('eye-off-outline', 'medium') + /** Regular one-pixel IconGlobeOutline artwork. */ export const IconGlobeOutlineRegular = productIcon('globe-outline', 'regular') diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 3d590e865e..44dbcd8871 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -136,7 +136,7 @@ export { ImageLightbox } from './ImageLightbox.tsx' export type { ImageLightboxLabels } from './ImageLightbox.tsx' export { QuotePreview } from './QuotePreview.tsx' -export type { QuotePreviewProps, QuotePreviewRemoval } from './QuotePreview.tsx' +export type { QuotePreviewProps, QuotePreviewRemoval, QuoteSummary } from './QuotePreview.tsx' export { formatQuoteText } from './markdown/quote-text.ts' export type { MarkdownMenuTarget } from './markdown/MarkdownDelegate.tsx' diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 9bf949a9db..9c550e0949 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -42,6 +42,7 @@ describe('product icon set', () => { 'IconMicrophoneOutlineRegular', 'IconPlanOutlineRegular', 'IconCompactOutlineRegular', 'IconShieldOutlineRegular', 'IconDeliverDocRegular', 'IconWarningTriangleOutlineRegular', 'IconCompareSplitOutlineRegular', 'IconCloseCircleFillRegular', + 'IconEyeOutlineRegular', 'IconEyeOffOutlineRegular', ])) }) @@ -58,6 +59,18 @@ describe('product icon set', () => { expect(render().container.querySelector('svg')!.getAttribute('width')).toBe('16') }) + it('draws the open eye as an outline with a pupil and the closed eye with a slash through the same contour', () => { + for (const weight of ['regular', 'medium'] as const) { + const eye = artwork('eye-outline', weight) + expect(eye.documentElement.getAttribute('viewBox')).toBe('0 0 16 16') + expect(eye.querySelector('circle')?.getAttribute('r')).toBe('2.25') + const off = artwork('eye-off-outline', weight) + expect(off.querySelector('circle')).toBeNull() + expect(off.querySelector('path')?.getAttribute('d')).toBe('M2.25 2.25L13.75 13.75') + for (const doc of [eye, off]) expect([...doc.querySelectorAll('path, circle')].every(node => node.getAttribute('fill') === null)).toBe(true) + } + }) + it.each([ ['regular', primitives.IconUsersOutlineRegular, 1], ['medium', primitives.IconUsersOutlineMedium, 1.3], diff --git a/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx b/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx index 985dc710ba..740977901d 100644 --- a/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx +++ b/packages/client/ui-primitives/tests/quote-preview.client.spec.tsx @@ -112,6 +112,29 @@ describe('QuotePreview', () => { } }) + it('shows an owner summary inline and in a popover that opens without clipping', async () => { + const text = '## User Comment 1\nFile: src/index.ts\nComment:\nrename this' + const view = render() + const quote = view.container.querySelector('[data-quote-preview]')! + const inline = quote.querySelector('[data-quote-preview-text]')! + expect([...inline.children].map(part => [part.textContent, part.getAttribute('aria-hidden')])) + .toEqual([['index.ts L78', 'true'], ['src/index.ts L78', null], ['rename this', null]]) + expect(view.queryByText(text)).toBeNull() + fireEvent.pointerEnter(quote) + await waitFor(() => { + expect([...document.querySelector('[data-quote-popover]')!.children].map(line => line.textContent)) + .toEqual(['src/index.ts', 'L78', 'rename this']) + }) + view.unmount() + + render() + expect(document.querySelector('[data-quote-preview-text]')?.children[1]?.textContent).toBe('src/index.ts') + fireEvent.pointerEnter(document.querySelector('[data-quote-preview]')!) + await waitFor(() => { + expect([...document.querySelector('[data-quote-popover]')!.children].map(line => line.textContent)).toEqual(['src/index.ts', 'rename this']) + }) + }) + it('contains keyboard and pointer removal events inside the editable preview', () => { const onRemove = vi.fn() const onPointerDown = vi.fn() diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 96bad805a3..1371e74c19 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 405b30feaf48c087 /deepseek-ai-dsh-client-ui-schedule/use-this-package: - en: 99626c29eb801b6f - zh: 9693d278f467ad90 + en: 68526e7df25338d4 + zh: 3bfdfa01dc9afaec /deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source: en: 4005b800e930f581 zh: ccb9318dad7f7e8f diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index 2db007cce9..fbd7582bd2 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -35,7 +35,7 @@ The destination menu offers a new conversation that the first delivery creates a The repeat editor offers once, minute, hour, day, week, month, and custom rules. Date and clock controls reuse existing pickers. Guided presets produce RRULE; minute and hour intervals start from the current minute in the selected zone. The Custom choice and Customize input do not name either syntax; the input accepts a two-line RRULE or a five-field Cron expression with an explicit zone. RRULE retains the zone in `DTSTART`; Cron retains its expression and selected zone as Cron timing. Complex RRULE values remain verbatim. The shared time parser checks new or changed Custom text before enabling Save; invalid or empty input keeps the draft and explains which field to change. Invalid Custom text offers manual correction, another repeat option, or correction by the Agent. The Host performs the final validation on save. Stored After and At tasks show date and clock fields immediately; a repeated local time uses UTC when needed to retain the exact instant. Every, Daily, and Weekly tasks show the matching controls when their interval or wall-clock precision is representable. Other stored timings remain in Custom and keep their typed timing until replaced. Viewing a task or editing other fields preserves its timing and committed occurrence. -Pause and resume update lifecycle state. Unsaved changes hold pause, resume, Run now, and Delete until you save or discard them. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables its fields, Save, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt. +Pause and resume update lifecycle state. While a pause or resume, a catalog reload, or a deletion is in progress, the toggle keeps its look and focus and ignores activation. During a pause, resume, or Run now request, the rule fields reject input without turning grey, and Close and Discard keep their look and ignore activation. Unsaved changes hold pause, resume, Run now, and Delete until you save or discard them. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables its fields, Save, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt. The list, detail, header, and Session hover show the later of the scheduled occurrence and the Host delivery floor as the next run. Creation and editing show one short minimum-interval hint for per-run conversation targets, read from `schedule.deliveryLimits`; a failed read offers Retry. Scheduled and immediate runs share this limit. diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index b51f75b673..51b523d0b9 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -35,7 +35,7 @@ kind: "package-reference" 重复编辑提供仅一次、每分钟、每小时、每天、每周、每月和自定义规则。日期和时间控件复用已有选择器。引导选项生成 RRULE;分钟和小时间隔从所选时区的当前分钟开始。自定义选项和自定义输入框不提示任何语法名称;输入框接受两行 RRULE 或带显式时区的五字段 Cron。RRULE 在 `DTSTART` 中保留时区;Cron 将表达式和所选时区保留为 Cron 时间类型。复杂 RRULE 保持原文。新的或已修改的自定义文本由共享时间解析器校验,校验通过后才能保存;无效或空输入保留草稿,并说明需要修改的字段。自定义文本无效时,提示手动修改规则、选择其他重复方式,或让智能体修改规则。宿主在保存时执行最终校验。已有 After、At 任务直接显示日期和时间控件;本地时间重复时,必要时使用 UTC 保留准确时点。Every、Daily、Weekly 任务在控件可表示其间隔或钟表时间精度时直接显示对应控件;其他时间规则仍在自定义中显示描述,并在替换前保留原类型。查看任务或编辑其他字段保留其时间规则及已提交发生时点。 -暂停和恢复修改生命周期状态。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用字段、保存、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。 +暂停和恢复修改生命周期状态。暂停或恢复请求、目录重读或删除进行期间,切换按钮保持原有外观和焦点,并忽略点击。暂停、恢复或立即执行请求期间,规则字段拒绝输入但不变灰,关闭和“放弃”保持原有外观并忽略点击。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用字段、保存、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。 列表、详情、页头和会话悬浮内容的下次运行时间,取计划发生时间和宿主最早允许投递时间中较晚的一项。创建和编辑“每次新建对话”时,通过 `schedule.deliveryLimits` 读取宿主配置,以一句短提示显示最小间隔;读取失败可重试。定时与立即执行共用此限制。 diff --git a/packages/client/ui-schedule/src/client/TaskDetail.tsx b/packages/client/ui-schedule/src/client/TaskDetail.tsx index cafd802378..8c1f612643 100644 --- a/packages/client/ui-schedule/src/client/TaskDetail.tsx +++ b/packages/client/ui-schedule/src/client/TaskDetail.tsx @@ -215,10 +215,13 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { ? JSON.stringify(draft) !== JSON.stringify({ ...initial, cwd: initial.cwd || projects.defaultCwd }) : storedDirty const issue = dirty ? taskDraftIssue(draft, changes) : undefined const valid = issue === undefined - const [actionPending, setPending] = useState(false) + const [actionPending, setPending] = useState<'toggle' | 'run' | 'delete' | null>(null) const [actionFailure, setFailure] = useState(null) const saving = cached?.pending === true - const pending = actionPending || saving + const pending = actionPending !== null || saving + // A pause, resume, or run would otherwise flash its controls grey between two enabled states. + const actionHold = actionPending === 'toggle' || actionPending === 'run' + const nativeHold = pending && !actionHold const failure = !pending && dirty && base !== undefined && task !== undefined && base.updatedAt !== task.updatedAt ? 'host.conflict' : actionFailure ?? cached?.failure ?? null const [menuOpen, setMenuOpen] = useState(false) @@ -281,18 +284,20 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } else props.actions.setDraft(key, { base, draft, failure: outcome.failed, ...(task === undefined ? { initial } : {}) }) } const setActive = async (task: ScheduleCatalogEntry): Promise => { - setPending(true) + // The toggle stays focusable while busy, so a second press is ignored here instead of by `disabled`. + if (busy) return + setPending('toggle') const outcome = await hostActions.edit({ id: task.id, action: 'update', patch: { active: task.status !== 'active' }, expectedUpdatedAt: task.updatedAt ?? null }) if (!mounted.current) return - setPending(false) + setPending(null) setFailure(outcome === 'saved' ? null : outcome.failed) } const run = async (id: ScheduleId): Promise => { setMenuOpen(false) - setPending(true) + setPending('run') const outcome = await hostActions.run(id) if (!mounted.current) return - setPending(false) + setPending(null) setFailure(outcome === 'queued' ? null : outcome.failed) } @@ -321,8 +326,10 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
}
{task !== undefined && <> - @@ -346,7 +353,8 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } {onClose !== undefined && } + disabled={nativeHold} aria-disabled={actionHold || undefined} + onClick={() => { if (!actionHold) onClose() }}>}
: failure === 'host.executionPending' ?

{t(failure)}

: failure !== null &&

{t(failure)}

} {draft.target === 'new' && } @@ -404,8 +412,8 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { } {(tab === 'rule' || dirty) &&
{dirty ? t('rule.unsaved') : ''} - + @@ -418,12 +426,12 @@ function TaskDetailView(props: TaskDetailProps): ReactNode { - -} diff --git a/packages/client/ui-settings-account/src/client/AccountSection.tsx b/packages/client/ui-settings-account/src/client/AccountSection.tsx index e65252994e..d2a4674e9a 100644 --- a/packages/client/ui-settings-account/src/client/AccountSection.tsx +++ b/packages/client/ui-settings-account/src/client/AccountSection.tsx @@ -10,14 +10,10 @@ import { formatBalance } from './formatBalance.ts' import { AccountAvatar } from './AccountAvatar.tsx' import type { AccountAvatarSnapshot } from './account-avatar.ts' import { authorizeUrlWithTheme } from './authorize-url.ts' -import type { BonusNotice } from './bonus-notices.ts' import css from './AccountSection.module.css' /** Safe account snapshot shared by the settings page and launcher. */ export interface AccountSnapshot { - /** Server-authored notices in front-to-back order, absent when none are available. */ - notices?: readonly BonusNotice[] - /** Latest Host state, absent until the stream responds. */ view: AccountView | undefined /** Sanitized profile and balance query outcomes, absent while loading. */ @@ -30,7 +26,7 @@ export interface AccountSnapshot { loginVisible?: boolean /** Latest explicit start request failed before a Host state was available. */ loginFailed?: boolean - /** Model credential onboarding owns the login dialog and delays bonus notices while mounted. */ + /** Model credential onboarding owns the login dialog and delays account notifications while mounted. */ onboarding?: boolean /** Desktop introduction covers the workspace during loading, saving, and exit animation. * True on Desktop until shell.overlay reports visibility, false in browsers; Desktop layouts must render that slot. @@ -62,7 +58,7 @@ export interface AccountSectionInjected { theme: HostObservable } /** - * Retry a failed avatar and read the profile, balance, bonus wallets and unnotified bonus once. The Settings launcher + * Retry a failed avatar, read the profile and balances, and notify account refresh extensions. The Settings launcher * calls it on each entry, and a page opener on return from top-up. * @returns after the account queries settle; image loading completes independently. */ @@ -73,10 +69,6 @@ export interface AccountSectionInjected { showLogin: (visible: boolean) => void /** Claim dialog ownership for the onboarding step. */ setOnboarding: (active: boolean) => void - /** @param orderId - notice whose card finished a presented frame while visible. */ - bonusNoticeShown: (orderId: BonusNotice['orderId']) => void - /** @param orderId - notice the user closed. */ - bonusNoticeDismissed: (orderId: BonusNotice['orderId']) => void /** @returns after the login attempt is created. */ start: () => Promise /** @param id - attempt to cancel. @returns after cancellation or an already-admitted commit. */ diff --git a/packages/client/ui-settings-account/src/client/account-ui.ts b/packages/client/ui-settings-account/src/client/account-ui.ts new file mode 100644 index 0000000000..e2c6e696ee --- /dev/null +++ b/packages/client/ui-settings-account/src/client/account-ui.ts @@ -0,0 +1,49 @@ +/** Account state and presentation extension points shared with client plugins. */ +import type { AccountClientMetadata, AccountView } from '@deepseek-ai/dsh-deepseek-account/types' + +/** Latest account-stream availability, without notification state. */ +export interface AccountUiState { + readonly view: AccountView | undefined + readonly failed: boolean +} + +/** Read the account stream already owned by the account settings plugin. */ +export interface AccountUi { + /** Read the current state from the existing account snapshot. + * @returns the latest account state. + */ + getSnapshot(): AccountUiState + /** Build metadata for one account request. + * @param locale - requested language. + * @returns this client's version, language, and timezone. + */ + clientMetadata(locale: string): AccountClientMetadata +} + +/** Account-menu presentation facts supplied to its notification extension. */ +export interface AccountNotificationsOwnerProps { + /** Whether the account menu can display notifications outside onboarding. */ + active: boolean + /** Open the account section in the existing settings shell. */ + openAccount: () => void +} + +declare module '@deepseek-ai/cordis' { + interface Context { accountUi: AccountUi } + interface Events { + /** Account stream update or loss of access. @mode parallel + * @param state - latest account state. + * @param reset - whether account availability, credentials, or the connection lifetime changed. + */ + 'account-ui/change'(state: AccountUiState, reset: boolean): void + /** Explicit account refresh from Settings or a returned Platform page. @mode parallel */ + 'account-ui/refresh'(): Promise + } +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** Notifications anchored at the account menu; the contribution owns its markup and lifecycle. */ + 'settings.launcher.notifications': { kind: 'single'; scope: 'root'; owner: AccountNotificationsOwnerProps } + } +} diff --git a/packages/client/ui-settings-account/src/client/bonus-notices.ts b/packages/client/ui-settings-account/src/client/bonus-notices.ts deleted file mode 100644 index e19f740b49..0000000000 --- a/packages/client/ui-settings-account/src/client/bonus-notices.ts +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Lifecycle of bonus notices: one foreground card in a stack, one read result in - * force at a time, and one acknowledgement per displayed card. Reads happen when - * the account becomes active and when the user asks for a refresh, never on a - * timer; the server owns which bonus is unnotified and what its copy says. - * - * An order is acknowledged once its foreground card reports a presented frame: the card has - * a position, the document is visible, and it painted one frame. The card measures - * no cover, so a card painted under the open Settings overlay reports like any - * other, and closing the card counts as a display too. - * - * One lifecycle covers one signed-in session. A repeated signed-in frame — the - * second commit update of one sign-in, or a reconnected stream's replay — keeps - * the card and its acknowledgement retries and reads again, so a credential - * replaced in place is still named by a fresh read. Signing out, unloading, or a - * read naming another account clears all of it; a later sign-in shows whatever - * the server still offers. - * @module @deepseek-ai/dsh-client-ui-settings-account/src/client/bonus-notices - */ -import type { - AccountBonusBatch, AccountBonusOrderId, AccountUserId, -} from '@deepseek-ai/dsh-deepseek-account/types' - -/** Notice eligible for display; the message is server-authored for the active locale. */ -export interface BonusNotice { - /** Server-localized plain-text title; absent responses use the localized bonus title. */ - readonly title?: string - /** Server order identity. */ - readonly orderId: AccountBonusOrderId - /** Server-localized plain text, including any award amount or expiration. */ - readonly message: string - /** Server expiration, re-checked at display time; an empty string means no expiration. */ - readonly expiresAt: string -} - -/** Deployment-varying acknowledgement retry timings. */ -export interface BonusNoticeTiming { - /** Delay before the first acknowledgement retry, doubled per further failure. */ - readonly ackRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - readonly ackRetryMaxDelayMs: number -} - -/** Collaborators and timings of one bonus notice lifecycle. */ -export interface BonusNoticeControllerOptions extends BonusNoticeTiming { - /** Read the signed-in account's unnotified bonus. @returns the batch, or null when no account is signed in. */ - read: () => Promise - /** - * Record one order as notified. - * @param accountId - account the order belongs to. - * @param orderId - shown order. - * @returns false when the account changed or signed out; a protocol failure rejects. - */ - acknowledge: (accountId: AccountUserId, orderId: AccountBonusOrderId) => Promise - /** @param notices - notices in front-to-back order; empty when none are shown. */ - publish: (notices: readonly BonusNotice[]) => void -} - -/** Commands the account plugin issues to the bonus notice lifecycle. */ -export interface BonusNoticeController { - /** - * Start the signed-in lifecycle and read. Re-entry during a live lifecycle keeps - * the card and its acknowledgement retries and reads again, so a credential - * replaced in place is named by that frame's own read. - */ - begin(): void - /** Stop the lifecycle, drop the displayed notice, and discard pending acknowledgement retries. */ - end(): void - /** - * Read the unnotified bonus once, for one Settings entry. - * @returns after the read settles, so callers can await the whole entry. - */ - refresh(): Promise - /** @param orderId - notice whose card passed a presented frame while visible. */ - shown(orderId: AccountBonusOrderId): void - /** @param orderId - notice the user closed, which counts as seen. */ - dismiss(orderId: AccountBonusOrderId): void -} - -/** Signed-in scope; the account and its pending acknowledgements appear once a read names them. */ -interface NoticeScope { - accountId?: AccountUserId - /** Orders whose card was presented and whose acknowledgement has not settled, oldest first. */ - readonly pending: AccountBonusOrderId[] -} - -/** - * @param expiresAt - server expiration timestamp. - * @param at - milliseconds since epoch. - * @returns whether the bonus can no longer be shown. - */ -function expired(expiresAt: string, at: number): boolean { - if (expiresAt === '') return false - const expires = Date.parse(expiresAt) - // An unparsable timestamp is not evidence of expiry, so the notice still shows. - return !Number.isNaN(expires) && expires <= at -} - -/** - * Own the read, display, and acknowledgement lifecycle of bonus notices. - * @param options - collaborators and timings. - * @returns the controller the account plugin drives from account and settings state. - */ -export function createBonusNoticeController(options: BonusNoticeControllerOptions): BonusNoticeController { - let scope: NoticeScope | undefined - /** Notice currently published to the sidebar, including the expiration checked at display time. */ - let current: readonly BonusNotice[] = [] - /** Newest read; an older read still in flight has its result dropped once a newer one starts. */ - let readGeneration = 0 - let ackTimer: ReturnType | undefined - let ackInFlight = false - let ackDelay = options.ackRetryDelayMs - /** Orders the card on screen already reported, so one mount cannot acknowledge twice. */ - const reported = new Set() - const clearAckTimer = (): void => { if (ackTimer !== undefined) { clearTimeout(ackTimer); ackTimer = undefined } } - const setCurrent = (notices: readonly BonusNotice[]): void => { - if (notices.length === current.length && notices.every((notice, index) => { - const previous = current[index] - return notice.orderId === previous?.orderId && notice.message === previous.message - && notice.title === previous.title && notice.expiresAt === previous.expiresAt - })) return - const retained = new Set(notices.map(notice => notice.orderId)) - for (const orderId of reported) if (!retained.has(orderId)) reported.delete(orderId) - current = notices - options.publish(notices) - } - const scheduleAck = (delay: number): void => { - clearAckTimer() - ackTimer = setTimeout(() => { void runAcks() }, delay) - } - /** Drop acknowledgement work of the previous account or lifecycle, so its carry-over cannot reach the next one. */ - const resetAcks = (): void => { - clearAckTimer() - ackInFlight = false - ackDelay = options.ackRetryDelayMs - } - const startAcks = (): void => { if (scope !== undefined && scope.pending.length > 0) scheduleAck(0) } - - /** - * Apply the server-ordered stack, excluding expired notices. An empty batch - * retains only the foreground card if the user has already seen it. - */ - const apply = (scopeAtRead: NoticeScope, batch: AccountBonusBatch): void => { - if (scopeAtRead.accountId !== batch.accountId) { - // A different account answered: the previous account's card and pending - // acknowledgements belong to it and must not outlive its sign-in. - scopeAtRead.accountId = batch.accountId - scopeAtRead.pending.length = 0 - resetAcks() - setCurrent([]) - } - const candidates = batch.bonuses.filter(notice => !expired(notice.expiresAt, Date.now())) - if (candidates.length === 0) { - // Keep an already presented foreground card until dismissal; unseen cards are withdrawn. - const foreground = current[0] - setCurrent(foreground !== undefined && reported.has(foreground.orderId) ? [foreground] : []) - return - } - setCurrent(candidates) - } - - /** - * Read once for one live lifecycle. A newer read supersedes one in flight: the - * older result is dropped instead of applied, so only the newest read can report - * an account change. - * @param scopeAtRead - lifecycle this read belongs to. - * @returns after this read settles. - */ - function runRead(scopeAtRead: NoticeScope): Promise { - const generation = ++readGeneration - return (async () => { - let batch: AccountBonusBatch | null - try { batch = await options.read() } - catch { - // A failed read reports nothing to the user and leaves the lifecycle as - // it stands, so a pending acknowledgement keeps retrying. - batch = null - } - if (scope !== scopeAtRead || generation !== readGeneration) return - if (batch !== null) apply(scopeAtRead, batch) - })() - } - - /** - * Acknowledge presented orders one at a time. A protocol failure backs off up - * to the ceiling and retries for the rest of the signed-in lifecycle, which - * never persists. A false answer settles the order without a retry: this - * session cannot make the server accept it. A hidden window keeps retrying, - * because the presented frame is what a pending acknowledgement proves. - */ - async function runAcks(): Promise { - const scopeAtCall = scope - if (scopeAtCall === undefined || ackInFlight) return - const accountId = scopeAtCall.accountId - const orderId = scopeAtCall.pending[0] - /* v8 ignore next -- an acknowledgement runs only while a read named the account and left a pending order */ - if (accountId === undefined || orderId === undefined) return - ackInFlight = true - /** @returns whether this call still owns the lifecycle and account it started for. */ - const owns = (): boolean => scope === scopeAtCall && scopeAtCall.accountId === accountId - let acknowledged: boolean - try { acknowledged = await options.acknowledge(accountId, orderId) } - catch { - // The lifecycle ended or another account answered while the call was in flight: - // its pending list, in-flight flag and timer now belong to the new owner. - if (!owns()) return - ackInFlight = false - scheduleAck(ackDelay) - ackDelay = Math.min(ackDelay * 2, options.ackRetryMaxDelayMs) - return - } - if (!owns()) return - ackInFlight = false - // Success needs no record and a refusal has no retry, so either way this order - // is settled for this lifecycle. - /* v8 ignore next -- the call owns the scope, and this order is its head until this shift */ - if (scopeAtCall.pending[0] === orderId) scopeAtCall.pending.shift() - ackDelay = options.ackRetryDelayMs - if (acknowledged && scopeAtCall.pending.length > 0) scheduleAck(0) - else clearAckTimer() - } - - /** Queue a presented order, so an acknowledgement interrupted by a failure retries within this sign-in. */ - const report = (orderId: AccountBonusOrderId): void => { - const scopeAtReport = scope - if (scopeAtReport === undefined || current[0]?.orderId !== orderId || reported.has(orderId)) return - reported.add(orderId) - if (!scopeAtReport.pending.includes(orderId)) scopeAtReport.pending.push(orderId) - ackDelay = options.ackRetryDelayMs - scheduleAck(0) - } - - const endLifecycle = (): void => { - if (scope === undefined) return - // The lifecycle a read started for is gone, so its scope check drops the result. - resetAcks() - scope = undefined - reported.clear() - setCurrent([]) - } - - return { - begin() { - // Re-entry is the same signed-in session: the card and its acknowledgement - // retries stay, and this frame's own read supersedes any read still in flight, - // so a credential swapped in place is never left unnamed. - scope ??= { pending: [] } - void runRead(scope) - }, - end: endLifecycle, - refresh(): Promise { - if (scope === undefined) return Promise.resolve() - startAcks() - return runRead(scope) - }, - shown(orderId) { - setCurrent(current.filter(notice => !expired(notice.expiresAt, Date.now()))) - if (current[0]?.orderId !== orderId) return - report(orderId) - }, - dismiss(orderId) { - setCurrent(current.filter(notice => !expired(notice.expiresAt, Date.now()))) - if (current[0]?.orderId !== orderId) return - // Closing the card is the user seeing it, so queue its acknowledgement before withdrawing. - report(orderId) - setCurrent(current.slice(1).filter(notice => !expired(notice.expiresAt, Date.now()))) - }, - } -} diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index 45f13a1b97..a8ac2c89fa 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -10,7 +10,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-api-remote-access/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' -import type { AccountView, AccountDetails } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountUpdate, AccountDetails } from '@deepseek-ai/dsh-deepseek-account/types' import type { OnboardingChange } from './onboarding-contract.ts' import type { PlatformBridge } from './PlatformOverlay.tsx' import { ContactConfig, CONTACT_CONFIG_GLOBAL } from '../contact-config.ts' @@ -22,7 +22,6 @@ import { AccountPlatformHost, type AccountPlatformHostInjected } from './Account import { AccountMenu } from './AccountMenu.tsx' import { createPlatformPages, type PlatformPages } from './platform-pages.ts' import { AccountSection, type AccountSnapshot, type AccountSectionInjected } from './AccountSection.tsx' -import { createBonusNoticeController } from './bonus-notices.ts' import { accountClientMetadata } from './client-metadata.ts' import { en, ja, es, fr, de, ru, pt, zh, type AccountKey } from './locales.ts' import { AccountQuotaNotice, type AccountQuotaNoticeInjected } from './AccountQuotaNotice.tsx' @@ -36,6 +35,7 @@ export type { AccountSectionInjected, AccountSectionProps } from './AccountSecti export type { AccountMenuProps } from './AccountMenu.tsx' export type { AccountSnapshot } from './AccountSection.tsx' export type { AccountKey } from './locales.ts' +export type { AccountUi, AccountUiState, AccountNotificationsOwnerProps } from './account-ui.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { 'settings.account': AccountKey } @@ -60,31 +60,9 @@ export function apply(ctx: Context): void { const publish = (value: AccountSnapshot) => { snapshot = value; for (const listener of listeners) listener() } const avatar = new AccountAvatarLoader((value) => { publish({ ...snapshot, avatar: value }) }) ctx.effect(() => () => { avatar.dispose() }, 'account: profile picture lifetime') - /** @returns the client identity for one account call, read at call time so it carries the language and zone in effect then. */ - const client = () => accountClientMetadata(ctx.locale.getSnapshot().active, process.env.DSH_CLIENT_VERSION) - // The browser half of the notice lifecycle: reads when the account becomes - // active and on an explicit refresh, and acknowledges an order only after its - // card reports a presented frame. The Host owns which bonus is unnotified and - // the server owns the copy. - const notices = createBonusNoticeController({ - ackRetryDelayMs: config.bonusAckRetryDelayMs, - ackRetryMaxDelayMs: config.bonusAckRetryMaxDelayMs, - read: async () => { - const result = await ctx.remote.account.getUnnotifiedBonuses(client()) - if (!result.ok) throw new Error('account bonus read failed') - return result.value - }, - acknowledge: async (accountId, orderId) => { - const result = await ctx.remote.account.ackBonusNotified(accountId, orderId, client()) - if (!result.ok) throw new Error('account bonus acknowledgement failed') - return result.value - }, - publish: (notices) => { - const { notices: _replaced, ...withoutNotices } = snapshot - publish(notices.length === 0 ? withoutNotices : { ...withoutNotices, notices }) - }, - }) - ctx.effect(() => () => { notices.end() }, 'account: bonus notice lifetime') + /** @param locale - requested language. @returns client metadata with the current timezone. */ + const client = (locale: string) => accountClientMetadata(locale, process.env.DSH_CLIENT_VERSION) + ctx.provide('accountUi', { getSnapshot: () => snapshot, clientMetadata: client }) let revision = 0 let refreshing: Promise | undefined const refresh = (): Promise => { @@ -101,13 +79,13 @@ export function apply(ctx: Context): void { } const request = Promise.all([ read('profile', async () => { - const result = await ctx.remote.account.getProfile(client()) + const result = await ctx.remote.account.getProfile(client(ctx.locale.getSnapshot().active)) if (!result.ok) throw new Error('account profile failed') if (generation === revision && result.value?.status === 'ready') avatar.setUrl(result.value.value.avatarUrl) return result.value }), read('balance', async () => { - const result = await ctx.remote.account.getBalance(client()) + const result = await ctx.remote.account.getBalance(client(ctx.locale.getSnapshot().active)) if (!result.ok) throw new Error('account balance failed') return result.value }), @@ -119,17 +97,17 @@ export function apply(ctx: Context): void { ctx.effect(() => () => { revision++ }, 'account: details request lifetime') // The account stream, and the reads it starts, follow access to this host's account state. ctx.remoteAccess.whenAccess('account/watch', function* () { - const stream = ctx.remote.$stream({ + const stream = ctx.remote.$stream({ name: 'account', open: signal => ctx.remote.account.watch(signal), ended: () => new Error('account stream ended'), + carrierFailed: () => { + publish({ ...snapshot, failed: true }) + ctx.emit('account-ui/change', snapshot, true) + }, }) + let accountGeneration = 0 // Read across closures: the disposer ends this grant while the frame loop awaits. const grant = { ended: false } - // Withdrawing access invalidates the reads this grant started, closes the - // pending authorization tab, and clears the account view and the sign-in - // dialog state, synchronously, so the next grant starts from no account - // state. `notices.end()` disposes this generation's notice lifetime, which a - // frame of this stream begins; the notice controller stays outside and - // begins again under the next grant. + // Revocation clears shared account state before another access grant can start. yield () => { grant.ended = true revision++ @@ -138,25 +116,27 @@ export function apply(ctx: Context): void { browser.dispose() const { loginFailed: _loginFailed, ...current } = snapshot publish({ ...current, view: undefined, details: undefined, avatar: undefined, failed: false, loginVisible: false }) - notices.end() + ctx.emit('account-ui/change', snapshot, true) return stream.dispose() } void (async () => { for await (const frame of stream) { // A frame the stream delivered before the revocation is not this grant's to apply. if (grant.ended) return + const credentialsChanged = frame.value.type === 'credentials-changed' + const view = frame.value.state + const generationChanged = frame.generation !== accountGeneration + const reset = credentialsChanged || generationChanged || snapshot.view?.status !== view.status || snapshot.failed + accountGeneration = frame.generation revision++ refreshing = undefined avatar.reset() - const initialize = frame.value.status === 'credential-stored' && frame.value.attempt?.phase === 'succeeded' + const initialize = view.status === 'credential-stored' && view.attempt?.phase === 'succeeded' && snapshot.view?.attempt?.phase !== 'succeeded' - const { notices: previousNotices, ...previous } = snapshot - publish({ ...previous, view: frame.value, details: undefined, avatar: undefined, failed: false, - ...(frame.value.status === 'credential-stored' && previousNotices ? { notices: previousNotices } : {}) }) - browser.update(frame.value) + publish({ ...snapshot, view, details: undefined, avatar: undefined, failed: false }) + browser.update(view) frame.accept() - if (frame.value.status === 'credential-stored') notices.begin() - else notices.end() + ctx.emit('account-ui/change', snapshot, reset) if (initialize) void (async () => { try { const initialized = await ctx.remote.session.initializeDefaultModel() @@ -167,7 +147,12 @@ export function apply(ctx: Context): void { })() void refresh() } - })().catch(() => { if (!grant.ended) publish({ ...snapshot, failed: true }) }) + })().catch(() => { + if (!grant.ended) { + publish({ ...snapshot, failed: true }) + ctx.emit('account-ui/change', snapshot, true) + } + }) }) const nativePlatform = (globalThis as typeof globalThis & { dshPlatform?: PlatformBridge }).dshPlatform // One request channel for the single native Platform view. It always exists @@ -175,12 +160,10 @@ export function apply(ctx: Context): void { // lets an entry request one. const platformPages = createPlatformPages() ctx.effect(() => () => { platformPages.dispose() }, 'account: platform page request') - // One account refresh: the recharge/bonus wallet and the unnotified-bonus read, - // whichever surface asks — a Settings entry, or returning from top-up. Both - // reads are independent, and a concurrent refresh shares the in-flight request. + // Extensions share explicit refreshes; profile and wallet reads remain coalesced. const refreshAccount = async (): Promise => { avatar.retry() - await Promise.all([refresh(), notices.refresh()]) + await Promise.all([refresh(), ctx.parallel('account-ui/refresh')]) } /** * Narrow the shared channel to one surface's post-return read: only a viewer @@ -231,8 +214,6 @@ export function apply(ctx: Context): void { }, showLogin(visible) { publish({ ...snapshot, loginVisible: visible }) }, setOnboarding(active) { publish({ ...snapshot, onboarding: active }) }, - bonusNoticeShown(orderId) { notices.shown(orderId) }, - bonusNoticeDismissed(orderId) { notices.dismiss(orderId) }, hooks: { account: { getSnapshot: () => snapshot, @@ -249,7 +230,7 @@ export function apply(ctx: Context): void { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__ const request = async () => { - const result = await ctx.remote.account.startSignIn(client(), + const result = await ctx.remote.account.startSignIn(client(ctx.locale.getSnapshot().active), desktop && transport?.streamBaseUrl !== undefined ? new URL(transport.streamBaseUrl).origin : window.location.origin, desktop ? 'desktop' : 'web') if (!result.ok) throw new Error('account start failed') @@ -270,7 +251,7 @@ export function apply(ctx: Context): void { return result.value }, async signOut() { - const result = await ctx.remote.account.signOut(client()) + const result = await ctx.remote.account.signOut(client(ctx.locale.getSnapshot().active)) if (result.ok) return throw result.error }, @@ -332,6 +313,7 @@ export function apply(ctx: Context): void { } ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher', locale: 'settings.account', inject: () => operations, + children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, }, AccountMenu))) ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => { let unregister: (() => void) | undefined diff --git a/packages/client/ui-settings-account/src/client/locales.ts b/packages/client/ui-settings-account/src/client/locales.ts index 43ed4d17c1..1e5efc5bbf 100644 --- a/packages/client/ui-settings-account/src/client/locales.ts +++ b/packages/client/ui-settings-account/src/client/locales.ts @@ -33,7 +33,6 @@ export const en = { quotaTitle: 'No balance available', quotaDescription: 'DeepSeek Harness cannot start a new task with this account when no balance is available. Would you like to top up? You can also top up later in Settings → Account.', quotaTopUp: 'Top up', - bonusNoticeTitle: 'Bonus credited', } as const /** Account locale keys. */ export type AccountKey = keyof typeof en @@ -69,7 +68,6 @@ export const zh: Record = { quotaTitle: '当前无可用余额', quotaDescription: '没有可用额度时,DeepSeek Harness 无法开始新的任务,是否前往充值?或者可以稍后前往 设置 → 账号与余额 进行充值。', quotaTopUp: '去充值', - bonusNoticeTitle: '赠金已到账', } /** Japanese copy, checked against the English keys. */ @@ -129,7 +127,6 @@ export const ja = { 'quotaTitle': '残高がありません', 'quotaDescription': '残高がない場合、DeepSeek Harness はこのアカウントで新しいタスクを開始できません。チャージしますか?後から設定 → アカウントでチャージすることもできます。', 'quotaTopUp': 'チャージ', - 'bonusNoticeTitle': 'ボーナスが付与されました', } satisfies Record /** Spanish dictionary, checked against the English keys. */ @@ -164,7 +161,6 @@ export const es = { quotaTitle: 'No hay saldo disponible', quotaDescription: 'DeepSeek Harness no puede iniciar una nueva tarea con esta cuenta cuando no hay saldo disponible. ¿Quieres recargar? También puedes recargar más tarde en Configuración → Cuenta.', quotaTopUp: 'Recargar', - bonusNoticeTitle: 'Bono acreditado', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -199,7 +195,6 @@ export const fr = { quotaTitle: 'Aucun solde disponible', quotaDescription: "DeepSeek Harness ne peut pas démarrer une nouvelle tâche avec ce compte lorsqu'aucun solde n'est disponible. Souhaitez-vous recharger ? Vous pouvez également recharger plus tard dans Paramètres → Compte.", quotaTopUp: 'Recharger', - bonusNoticeTitle: 'Bonus crédité', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -234,7 +229,6 @@ export const de = { quotaTitle: 'Kein Guthaben verfügbar', quotaDescription: 'DeepSeek Harness kann mit diesem Konto keine neue Aufgabe starten, wenn kein Guthaben verfügbar ist. Möchten Sie aufladen? Sie können das Guthaben auch später unter Einstellungen → Konto aufladen.', quotaTopUp: 'Auffüllen', - bonusNoticeTitle: 'Bonus gutgeschrieben', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -269,7 +263,6 @@ export const ru = { quotaTitle: 'Нет доступного баланса', quotaDescription: 'DeepSeek Harness не может запустить новую задачу с этой учетной записью, если на ней нет баланса. Хотите пополнить счет? Вы также можете пополнить счет позже в «Настройки» → «Аккаунт».', quotaTopUp: 'Пополнить', - bonusNoticeTitle: 'Бонус начислен', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -304,5 +297,4 @@ export const pt = { quotaTitle: 'Nenhum saldo disponível', quotaDescription: 'DeepSeek Harness não pode iniciar uma nova tarefa com esta conta quando não houver saldo disponível. Você gostaria de recarregar? Você também pode recarregar mais tarde em Configurações → Conta.', quotaTopUp: 'Recarregar', - bonusNoticeTitle: 'Bônus creditado', } satisfies Record diff --git a/packages/client/ui-settings-account/src/contact-config.ts b/packages/client/ui-settings-account/src/contact-config.ts index b1afcbf049..234e758b9f 100644 --- a/packages/client/ui-settings-account/src/contact-config.ts +++ b/packages/client/ui-settings-account/src/contact-config.ts @@ -1,23 +1,17 @@ -/** Public contact and bonus notice options shared by Host and Client. */ +/** Public contact options shared by Host and Client. */ import z from '@deepseek-ai/schemastery' -/** 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 } /** Validate public questionnaire options. */ export const ContactConfigFields = { contactFormUrl: z.string().pattern(/^https:\/\/[^/\s]+\//).default('https://trtgsjkv6r.feishu.cn/share/base/form/shrcnlCoGElW7MQznGy9r3YYXcg?hide_uid=1&hide_device_info=1&hide_harness_version=1'), contactSource: z.string().default(''), - bonusAckRetryDelayMs: z.number().min(1).default(1_000), - bonusAckRetryMaxDelayMs: z.number().min(1).default(60_000), } /** Validate public questionnaire options. */ export const ContactConfig: z, ContactConfig> = z.object(ContactConfigFields) diff --git a/packages/client/ui-settings-account/src/index.ts b/packages/client/ui-settings-account/src/index.ts index e37bccc073..326da6d0cc 100644 --- a/packages/client/ui-settings-account/src/index.ts +++ b/packages/client/ui-settings-account/src/index.ts @@ -27,8 +27,6 @@ export interface Config extends ContactConfig { export const Config = z.object({ contactFormUrl: ContactConfigFields.contactFormUrl, contactSource: ContactConfigFields.contactSource, - bonusAckRetryDelayMs: ContactConfigFields.bonusAckRetryDelayMs, - bonusAckRetryMaxDelayMs: ContactConfigFields.bonusAckRetryMaxDelayMs, version: OnboardingSettingsFields.version.volatile(), step: OnboardingSettingsFields.step.volatile(), purpose: OnboardingSettingsFields.purpose.volatile(), @@ -50,7 +48,6 @@ export function apply(ctx: Context, config: Config): void { ctx.on('webserver/index-inject', (table) => { table.push({ kind: 'global', name: CONTACT_CONFIG_GLOBAL, value: { contactFormUrl: config.contactFormUrl, contactSource: config.contactSource, - bonusAckRetryDelayMs: config.bonusAckRetryDelayMs, bonusAckRetryMaxDelayMs: config.bonusAckRetryMaxDelayMs, } satisfies ContactConfig }) }) } diff --git a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts index c969148d1b..3e55d655d9 100644 --- a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts +++ b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts @@ -46,6 +46,7 @@ it('withdraws every account surface and the account stream on revocation, and re const streams: { readonly signal: AbortSignal; readonly accepted: Promise }[] = [] const lifetime: (() => void)[] = [] const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -71,7 +72,10 @@ it('withdraws every account surface and the account stream on revocation, and re remote: { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, - account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }) }, + account: { + getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }), + getNotifications: async () => ({ ok: true, value: null }), + }, $stream: () => { const abort = new AbortController() const accepted = Promise.withResolvers() @@ -80,7 +84,7 @@ it('withdraws every account surface and the account stream on revocation, and re signal: abort.signal, dispose: () => { abort.abort() }, async *[Symbol.asyncIterator]() { - yield { value: signedIn, accept: () => { accepted.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { accepted.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -121,6 +125,7 @@ it('drops reads a revoked grant started, and the next grant shows no account sec const firstFrames: { release: () => void; accepted: Promise }[] = [] const lifetime: (() => void)[] = [] const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -147,7 +152,10 @@ it('drops reads a revoked grant started, and the next grant shows no account sec remote: { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, - account: { getProfile: async () => await profile.promise, getBalance: async () => ({ ok: true, value: null }) }, + account: { + getProfile: async () => await profile.promise, getBalance: async () => ({ ok: true, value: null }), + getNotifications: async () => ({ ok: true, value: null }), + }, $stream: () => { const abort = new AbortController() const gate = Promise.withResolvers() @@ -158,7 +166,7 @@ it('drops reads a revoked grant started, and the next grant shows no account sec dispose: () => { abort.abort() }, async *[Symbol.asyncIterator]() { await gate.promise - yield { value: signedIn, accept: () => { accepted.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { accepted.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -207,9 +215,10 @@ function revocationHarness(scripts: StreamScript[]) { const lifetime: (() => void)[] = [] let operations: AccountSectionInjected | undefined const getProfile = vi.fn(async () => ({ ok: true, value: null })) - const getUnnotifiedBonuses = vi.fn(async () => ({ ok: true, value: null })) + const getNotifications = vi.fn(async () => ({ ok: true, value: null })) const startSignIn = vi.fn<() => Promise<{ ok: false }>>() const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -238,7 +247,7 @@ function revocationHarness(scripts: StreamScript[]) { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, account: { - getProfile, getBalance: async () => ({ ok: true, value: null }), getUnnotifiedBonuses, startSignIn, + getProfile, getBalance: async () => ({ ok: true, value: null }), getNotifications, startSignIn, }, $stream: () => { const abort = new AbortController() @@ -251,7 +260,7 @@ function revocationHarness(scripts: StreamScript[]) { async *[Symbol.asyncIterator]() { await Promise.resolve() script(() => {}) - yield { value: signedIn, accept: () => { delivered.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { delivered.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -260,7 +269,7 @@ function revocationHarness(scripts: StreamScript[]) { } apply(ctx as never) return { - guards, registered, accepted, getProfile, getUnnotifiedBonuses, startSignIn, + guards, registered, accepted, getProfile, getNotifications, startSignIn, operations: () => operations!, dispose: () => { revoke(guards); for (const dispose of lifetime.reverse()) dispose() }, } @@ -276,7 +285,7 @@ it('ignores a frame the stream delivered just before the revocation', async () = expect(b.operations().hooks.account.getSnapshot().view).toBeUndefined() expect(b.registered.get('settings.section') ?? 0).toBe(0) expect(b.getProfile).not.toHaveBeenCalled() - expect(b.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(b.getNotifications).not.toHaveBeenCalled() } finally { b.dispose() } diff --git a/packages/client/ui-settings-account/tests/account.client.spec.tsx b/packages/client/ui-settings-account/tests/account.client.spec.tsx index 0ff3cb139f..50b2668895 100644 --- a/packages/client/ui-settings-account/tests/account.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/account.client.spec.tsx @@ -9,8 +9,8 @@ import type { PlatformBridge } from '../src/client/PlatformOverlay.tsx' import { createPlatformPages, type PlatformPages } from '../src/client/platform-pages.ts' import { AccountPlatformHost } from '../src/client/AccountPlatformHost.tsx' import { AccountSection, type AccountSectionInjected, type AccountSnapshot } from '../src/client/AccountSection.tsx' -import type { BonusNotice } from '../src/client/bonus-notices.ts' import type { AccountMenuProps } from '../src/client/AccountMenu.tsx' +import type { AccountNotificationsOwnerProps } from '../src/client/account-ui.ts' import type {} from '../src/client/index.ts' import { en, zh, type AccountKey } from '../src/client/locales.ts' import css from '../src/client/AccountSection.module.css' @@ -37,7 +37,6 @@ function operationsOf(state: Omit, details?: Partial false), contactUs: vi.fn(), showLogin: vi.fn(), setOnboarding: vi.fn(), - bonusNoticeShown: vi.fn(), bonusNoticeDismissed: vi.fn(), refreshAccount: vi.fn(() => Promise.resolve()), avatarFailed: vi.fn(), start: vi.fn(() => Promise.resolve()), cancel: vi.fn(() => Promise.resolve()), signOut: vi.fn(() => Promise.resolve()), @@ -93,12 +92,14 @@ function SharedPlatformHost({ Globals, pages, platform, copy, refreshAccount }: * @param settingsOpen - whether the settings panel covers the sidebar. * @returns the sidebar launcher with its framework hooks wired to the test face. */ -async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean) { +async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean, + renderSlot: AccountMenuProps['renderSlot'] = () => null, + openSettings: AccountMenuProps['openSettings'] = () => {}, wide = true) { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - return selector(snapshot())} wide + return selector(snapshot())} wide={wide} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} - openOnboarding={() => {}} openSettings={() => {}} t={key => en[key as AccountKey]} /> + openOnboarding={() => {}} openSettings={openSettings} t={key => en[key as AccountKey]} /> } it.each([en, zh])('renders account cards without inventing profile or balance data', async (copy) => { @@ -128,7 +129,7 @@ it.each([en, zh].flatMap(copy => ([false, true, 'unknown'] as const).map(running const operations = mount({ status: 'credential-stored', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} hasRunningAccountTasks={async () => { if (running === 'unknown') throw new Error('offline'); return running }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} @@ -155,7 +156,7 @@ it.each([en, zh])('updates the Settings menu keycaps and accessible combination const operations = mount({ status: 'signed-out', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const props: AccountMenuProps = { + const props: AccountMenuProps = { renderSlot: () => null, ...({} as GlobalStandardProps), ...operations, wide: true, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -184,7 +185,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco const openSettings = vi.fn() const operations = operationsOf({ status: 'signed-out', attempt: null }) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} t={key => key in copy ? copy[key as AccountKey] : key} />) @@ -204,7 +205,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco it.each([true, false])('keeps the account inset local through sign-in changes with wide=%s', async (wide) => { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let operations = operationsOf({ status: 'signed-out', attempt: null }) - const props: AccountMenuProps = { + const props: AccountMenuProps = { renderSlot: () => null, ...({} as GlobalStandardProps), ...operations, wide, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -236,7 +237,8 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( snapshot = { ...snapshot, loginVisible: true, loginFailed: true } return Promise.reject(new Error('account start failed')) }) - const view = render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + start={start} useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} t={key => key in en ? en[key as AccountKey] : key} />) @@ -244,7 +246,8 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en.signIn })) }) expect(start).toHaveBeenCalledOnce() expect(screen.queryByRole('alert')).toBeNull() - view.rerender( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + start={start} useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} t={key => key in en ? en[key as AccountKey] : key} />) @@ -260,7 +263,7 @@ it('keeps the confirmation dialog open after a failed sign-out', async () => { cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const signOut = vi.fn((): Promise => Promise.reject(new Error('account sign-out failed'))) - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide @@ -422,7 +425,7 @@ it.each([ }) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -435,7 +438,7 @@ it('shows the same shared picture outcome in settings and the sidebar', async () profile: { status: 'ready', value: { id: null, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' } }, }, undefined, avatar) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -506,7 +509,7 @@ it.each([en, zh])('shows a localized toast when the account credential expires', const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let expire: (() => void) | undefined const unsubscribe = vi.fn() - const element = null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} subscribeSessionExpired={(listener) => { expire = listener; return unsubscribe }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -605,7 +608,8 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const openOnboarding = vi.fn() let snapshot = operations.hooks.account.getSnapshot() - const props = { ...({} as GlobalStandardProps), ...operations, wide: false, settingsOpen: false, openSettings: vi.fn(), openOnboarding, + const props = { ...({} as GlobalStandardProps), ...operations, renderSlot: () => null, wide: false, settingsOpen: false, + openSettings: vi.fn(), openOnboarding, useAccount: (select: (value: AccountSnapshot) => T) => select(snapshot), useTheme: (select: (value: ThemeSnapshot) => T) => select(operations.hooks.theme.getSnapshot()), t: (key: string) => en[key as AccountKey] } @@ -625,29 +629,6 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard expect(screen.queryByRole('dialog')).toBeNull() }) -it('paints the bonus notice under the open settings panel and reports its display once', async () => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }) - const operations = mount({ status: 'credential-stored', attempt: null }, en, { - profile: { status: 'ready', value: { id: null, name: 'User', contact: null } }, - }) - cleanup() - const notice = { orderId: 'order-1' as BonusNotice['orderId'], message: 'Awarded 5.00', expiresAt: '2099-01-01T00:00:00Z' } - // The launcher mounts first; the entry's refresh then delivers the notice while the panel is open. - let snapshot: AccountSnapshot = operations.hooks.account.getSnapshot() - const view = render(await accountMenu(operations, () => snapshot, true)) - expect(screen.queryByRole('status')).toBeNull() - snapshot = { ...snapshot, notices: [notice] } - view.rerender(await accountMenu(operations, () => snapshot, true)) - // The settings overlay is translucent, so the card paints underneath it instead of waiting for the exit. - await vi.waitFor(() => { expect(screen.getByRole('status').textContent).toBe(`${en.bonusNoticeTitle}${notice.message}`) }) - // A card that passed a presented frame reports once even while the panel is open; that report is the acknowledgement. - await vi.waitFor(() => { expect(operations.bonusNoticeShown).toHaveBeenCalledExactlyOnceWith(notice.orderId) }) - // Leaving the panel keeps the same card without reporting its display a second time. - view.rerender(await accountMenu(operations, () => snapshot, false)) - await vi.waitFor(() => { expect(screen.getByRole('status').textContent).toBe(`${en.bonusNoticeTitle}${notice.message}`) }) - expect(operations.bonusNoticeShown).toHaveBeenCalledOnce() -}) - it('reads once per Settings entry, whatever section the entry opens', async () => { const operations = mount({ status: 'credential-stored', attempt: null }, en) cleanup() @@ -716,7 +697,7 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after const unsubscribe = vi.fn(() => { listener = undefined }) operations.subscribeModelSignInRequired = (next) => { listener = next; return unsubscribe } const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const element = null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -737,20 +718,39 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after expect(screen.queryByRole('alert')).toBeNull() }) -it.each(['desktopOnboardingVisible', 'onboarding'] as const)('defers bonus display and acknowledgement until %s ends', async (field) => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }) +it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notification slot until %s ends', async (field) => { const operations = operationsOf({ status: 'credential-stored', attempt: null }) - const notice = { orderId: 'order-onboarding' as BonusNotice['orderId'], message: 'Awarded 5.00', expiresAt: '2099-01-01T00:00:00Z' } - let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), notices: [notice], [field]: true } - const view = render(await accountMenu(operations, () => snapshot, false)) - expect(screen.queryByText(notice.message)).toBeNull() - expect(operations.bonusNoticeShown).not.toHaveBeenCalled() - view.unmount() - expect(operations.bonusNoticeShown).not.toHaveBeenCalled() - const reopened = render(await accountMenu(operations, () => snapshot, false)) - expect(screen.queryByText(notice.message)).toBeNull() + let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), [field]: true } + let active: boolean | undefined + let openAccount: (() => void) | undefined + const openSettings = vi.fn() + const renderSlot: AccountMenuProps['renderSlot'] = (name, owner) => { + expect(name).toBe('settings.launcher.notifications') + const value: object = owner + const props = value as AccountNotificationsOwnerProps + active = props.active + openAccount = props.openAccount + return null + } + const view = render(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + expect(active).toBe(false) snapshot = { ...snapshot, [field]: false } - reopened.rerender(await accountMenu(operations, () => snapshot, false)) - await vi.waitFor(() => { expect(operations.bonusNoticeShown).toHaveBeenCalledExactlyOnceWith(notice.orderId) }) - expect(screen.getByText(notice.message)).toBeTruthy() + view.rerender(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + expect(active).toBe(true) + openAccount?.() + expect(openSettings).toHaveBeenCalledExactlyOnceWith('account') +}) + +it('keeps notification DOM inside the launcher while the collapsed rail hides it', async () => { + const operations = operationsOf({ status: 'credential-stored', attempt: null }) + const snapshot = () => operations.hooks.account.getSnapshot() + const renderSlot: AccountMenuProps['renderSlot'] = () =>
Notification
+ const view = render(await accountMenu(operations, snapshot, false, renderSlot)) + const notice = screen.getByRole('status') + expect(view.container.contains(notice)).toBe(true) + view.rerender(await accountMenu(operations, snapshot, false, renderSlot, undefined, false)) + expect(screen.queryByRole('status')).toBeNull() + expect(notice.isConnected).toBe(true) + view.rerender(await accountMenu(operations, snapshot, false, renderSlot)) + expect(screen.getByRole('status')).toBe(notice) }) diff --git a/packages/client/ui-settings-account/tests/apply.client.spec.ts b/packages/client/ui-settings-account/tests/apply.client.spec.ts index 300641d109..cadea02dfe 100644 --- a/packages/client/ui-settings-account/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-account/tests/apply.client.spec.ts @@ -1,11 +1,11 @@ // @vitest-environment jsdom /** Account operations in the shipped client composition, in Desktop and in a plain browser. */ -import { afterEach, beforeEach, expect, vi } from 'vitest' +import { afterEach, beforeEach, expect, onTestFinished, vi } from 'vitest' import { ok } from '@deepseek-ai/dsh-remote-mock' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import type { - AccountBonusBatch, AccountBonusOrderId, AccountDetails, AccountUserId, AccountView, SignInAttemptId, + AccountDetails, AccountUserId, AccountView, SignInAttemptId, } from '@deepseek-ai/dsh-deepseek-account/types' import type { QuotaNoticeOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import type { ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client' @@ -31,15 +31,6 @@ const view: AccountView = { } const stored: AccountView = { ...view, status: 'credential-stored' } const profile: AccountDetails['profile'] = { status: 'ready', value: { id: 'account-user' as AccountUserId, name: 'User', contact: null } } -/** @param orderId - server order. @param message - server copy. @returns one unnotified bonus for this account. */ -function bonus(orderId: string, message = 'Awarded 5.00'): AccountBonusBatch { - return { - accountId: 'account-user' as AccountUserId, - bonuses: [{ - orderId: orderId as AccountBonusOrderId, expiresAt: '2099-01-01T00:00:00Z', message, - }], - } -} function operations(c: TestClient): AccountSectionInjected { const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!() return injected as AccountSectionInjected @@ -133,7 +124,7 @@ it('shares account actions across seats, publishes dialog ownership, and opens c expect(signedOut.searchParams.has('prefill_uid')).toBe(false) expect(signedOut.searchParams.get('hide_uid')).toBe('1') c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) const entry = c.ctx.slots.entries('settings.section').find(entry => entry.options.id === 'account')! expect(entry.inject!()).toBe(actions) @@ -153,7 +144,7 @@ it('shares account actions across seats, publishes dialog ownership, and opens c expect(support.searchParams.has(`hide_${field}`)).toBe(false) } expect(support.searchParams.has('prefill_app_version')).toBe(false) - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) actions.contactUs() const signedOutAgain = new URL(String(open.mock.calls.at(-1)![0])) @@ -206,10 +197,10 @@ it('reports the account sampled by the click when a native read outlasts a sign- const c = await start() const actions = operations(c) c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) actions.contactUs() - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) device.resolve('platform=darwin; os=15.0; app_arch=arm64; memory_gib=16.0') await vi.waitFor(() => { expect(open).toHaveBeenCalledOnce() }) @@ -229,7 +220,7 @@ it('publishes one avatar load and retries it through the shared Settings refresh status: 'ready', value: { id: 'account-user' as AccountUserId, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' }, } c.mock.remote.account.getProfile.mockResolvedValue(ok(picture)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(images).toHaveLength(1) }) images[0]!.dispatchEvent(new Event('error')) expect(actions.hooks.account.getSnapshot().avatar?.status).toBe('failed') @@ -252,7 +243,7 @@ it('publishes one avatar load and retries it through the shared Settings refresh const successor = actions.hooks.account.getSnapshot().avatar! actions.avatarFailed(ready) expect(actions.hooks.account.getSnapshot().avatar).toBe(successor) - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) expect(actions.hooks.account.getSnapshot().avatar).toBeUndefined() expect(images[3]!.getAttribute('src')).toBeNull() @@ -268,7 +259,7 @@ it('keeps successful account refreshes silent and reports only failed reads', as await actions.refreshAccount() c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok({ status: 'ready', value: [], bonusWallets: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) await actions.refreshAccount() for (const spy of [output, info, log]) { @@ -299,7 +290,7 @@ it('coalesces refreshes, publishes independent failures, and rejects stale respo const pending = Promise.withResolvers>>() c.mock.remote.account.getProfile.mockReturnValueOnce(pending.promise) c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) // Two concurrent account refreshes share the one in-flight request, so the // second call adds no second read of the profile or the balance. @@ -307,14 +298,14 @@ it('coalesces refreshes, publishes independent failures, and rejects stale respo const concurrently = actions.refreshAccount() expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() expect(c.mock.remote.account.getBalance).toHaveBeenCalledOnce() - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) pending.resolve(ok(profile)) await Promise.all([a, concurrently]) expect(actions.hooks.account.getSnapshot().details).toBeUndefined() c.mock.remote.account.getProfile.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) c.mock.remote.account.getBalance.mockRejectedValueOnce(new Error('offline')) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details).toEqual({ profile: { status: 'failed' }, balance: { status: 'failed' } }) }) const pendingAgain = Promise.withResolvers>>() c.mock.remote.account.getProfile.mockReturnValueOnce(pendingAgain.promise) @@ -361,7 +352,7 @@ it('navigates the preopened browser tab to the themed authorization page', async const attempt = { id: 'attempt' as SignInAttemptId, phase: 'waiting-browser' as const, authorizeUrl: 'https://platform.deepseek.com/dsh/authorize' } mock.remote.account.startSignIn.mockResolvedValue(ok({ ...view, attempt: { id: attempt.id, phase: 'initializing' } })) await actions.start() - c.mock.streams.push('account/watch', { ...view, attempt }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...view, attempt } }) const theme = (c.ctx.get('theme') as ThemeRuntime).getTheme().active.colorScheme await vi.waitFor(() => { expect(replace).toHaveBeenCalledExactlyOnceWith(`${attempt.authorizeUrl}?theme=${theme}`) }) }, 60_000) @@ -410,32 +401,32 @@ it('re-reads the account when the shared host returns from top-up, and not from const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok(null)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok({ accountId: 'account-user' as AccountUserId, bonuses: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.remote.account.getNotifications.mockResolvedValue(ok({ nextPollAfterSeconds: 300, notifications: [] })) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) // The account becoming active already ran one shared refresh; measure only the // reads each return triggers from here. - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() - c.mock.remote.account.getUnnotifiedBonuses.mockClear() + c.mock.remote.account.getNotifications.mockClear() c.mock.remote.account.getProfile.mockClear() // Usage changes nothing the account owns, so returning from it reads nothing. actions.openPlatformPage!('usage', vi.fn()) host.closePage() await c.flush() - expect(mock.remote.account.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(mock.remote.account.getNotifications).not.toHaveBeenCalled() // Closing with no page showing is not a return, so it reads nothing either. host.closePage() await c.flush() - expect(mock.remote.account.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(mock.remote.account.getNotifications).not.toHaveBeenCalled() // Top up may have changed what the account holds, so its return runs the one // shared refresh: the wallet reads and the unnotified-bonus read. actions.openPlatformPage!('top-up', vi.fn()) host.closePage() - await vi.waitFor(() => { expect(mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() }) + await vi.waitFor(() => { expect(mock.remote.account.getNotifications).toHaveBeenCalledOnce() }) expect(mock.remote.account.getProfile).toHaveBeenCalledOnce() }, 60_000) @@ -455,12 +446,12 @@ it('re-reads profile and balance but no bonus for the onboarding recharge return const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok(null)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok({ accountId: 'account-user' as AccountUserId, bonuses: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.remote.account.getNotifications.mockResolvedValue(ok({ nextPollAfterSeconds: 300, notifications: [] })) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() - const bonusesBefore = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length + const bonusesBefore = c.mock.remote.account.getNotifications.mock.calls.length // The account becoming active already ran the shared refresh; measure only the // reads each later event triggers. c.mock.remote.account.getProfile.mockClear() @@ -485,7 +476,7 @@ it('re-reads profile and balance but no bonus for the onboarding recharge return await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) await vi.waitFor(() => { expect(c.mock.remote.account.getBalance).toHaveBeenCalledOnce() }) await c.flush() - expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBe(bonusesBefore) + expect(c.mock.remote.account.getNotifications.mock.calls.length).toBe(bonusesBefore) }, 60_000) it('waits for an in-flight pre-return read before the post-top-up read', async ({ start }) => { @@ -495,20 +486,20 @@ it('waits for an in-flight pre-return read before the post-top-up read', async ( await c.reload(SELF) const actions = operations(c) const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() c.mock.remote.account.getProfile.mockClear() c.mock.remote.account.getBalance.mockClear() - c.mock.remote.account.getUnnotifiedBonuses.mockClear() + c.mock.remote.account.getNotifications.mockClear() const pending = Promise.withResolvers>>>() c.mock.remote.account.getBalance.mockReturnValueOnce(pending.promise) try { - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) // The baseline includes the frame's own notice read, which is not the return read. - const bonusesBeforeReturn = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length + const bonusesBeforeReturn = c.mock.remote.account.getNotifications.mock.calls.length actions.openPlatformPage!('top-up', vi.fn()) host.closePage() @@ -520,133 +511,13 @@ it('waits for an in-flight pre-return read before the post-top-up read', async ( pending.resolve(ok(null)) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledTimes(2) }) await vi.waitFor(() => { expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(2) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBeGreaterThan(bonusesBeforeReturn) }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications.mock.calls.length).toBeGreaterThan(bonusesBeforeReturn) }) } finally { // A failed assertion above must not strand the read the host is awaiting. pending.resolve(ok(null)) } }, 60_000) -it('reads the unnotified bonus in the active locale and acknowledges only after the card renders', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - c.mock.remote.account.ackBonusNotified.mockResolvedValue(ok(true)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId, message: 'Awarded 5.00' }) - }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' })) - // A successful read is not a display, so nothing may be acknowledged yet. - expect(c.mock.remote.account.ackBonusNotified).not.toHaveBeenCalled() - actions.bonusNoticeShown(orderId as AccountBonusOrderId) - await vi.waitFor(() => { - expect(c.mock.remote.account.ackBonusNotified).toHaveBeenCalledWith('account-user', orderId, expect.objectContaining({ locale: 'en' })) - }) - actions.bonusNoticeDismissed(orderId as AccountBonusOrderId) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() -}, 60_000) - -it('keeps the notice and its acknowledgement retry across repeated signed-in frames', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - vi.stubGlobal(CONTACT_CONFIG_GLOBAL, { bonusAckRetryDelayMs: 1, bonusAckRetryMaxDelayMs: 4 }) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - c.mock.remote.account.ackBonusNotified.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId }) }) - actions.bonusNoticeShown(orderId as AccountBonusOrderId) - await vi.waitFor(() => { expect(c.mock.remote.account.ackBonusNotified.mock.calls.length).toBeGreaterThan(0) }) - // One sign-in commits the credential and then updates the attempt; a reconnected - // stream replays the same signed-in state. None of them is a new account. - c.mock.streams.push('account/watch', stored) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - // The displayed card stays, no second read replaces it, and the failed - // acknowledgement keeps backing off instead of stopping until sign-out. - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() - await vi.waitFor(() => { expect(c.mock.remote.account.ackBonusNotified.mock.calls.length).toBeGreaterThan(1) }, { timeout: 30_000 }) -}, 60_000) - -it('keeps the notice absent when the bonus read is refused, then shows the next read', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValueOnce({ - ok: false, error: new RemoteError('gateway/internal', 'offline', {}), - }) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() }) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() - expect(c.mock.remote.account.ackBonusNotified).not.toHaveBeenCalled() - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - await actions.refreshAccount() - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId, message: 'Awarded 5.00' }) - }) -}, 60_000) - -it('drops the previous account notice and stops reading after sign-out', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000001'))) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]?.message).toBe('Awarded 5.00') - }) - c.mock.streams.push('account/watch', view) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() - // Signing out ends the lifecycle, so no further read follows. - const reads = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length - await new Promise((resolve) => { setTimeout(resolve, 20) }) - expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBe(reads) -}, 60_000) - -it('refreshes balances and the bonus read on one Settings entry, without polling', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const balance: AccountDetails['balance'] = { - status: 'ready', value: [{ currency: 'CNY', balance: '12.34' }], bonusWallets: [{ currency: 'CNY', balance: '5.00' }], - } - c.mock.remote.account.getBalance.mockResolvedValue(ok(balance)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - // Signing in reads once; nothing else reads on a timer. - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - await new Promise((resolve) => { setTimeout(resolve, 20) }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) - // Signing in already read the wallet once through the details refresh. - const balances = c.mock.remote.account.getBalance.mock.calls.length - await actions.refreshAccount() - expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(balances + 1) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(2) - // The bonus read carries the active UI language. - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'en' })) -}, 60_000) - -it('publishes a failed balance from a Settings entry without dropping the bonus read', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - await actions.refreshAccount() - expect(actions.hooks.account.getSnapshot().details?.balance).toEqual({ status: 'failed' }) - // The bonus read still ran: a failed wallet read does not cancel it. - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(2) -}, 60_000) - it('publishes a terminal state-stream failure without mistaking it for plugin disposal', async ({ start }) => { vi.stubGlobal('dshDesktop', {}) const c = await start() @@ -681,16 +552,16 @@ it('samples the build version, language, and UTC offset for every account call', const c = await start() const actions = operations(c) const offset = vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(480) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith({ + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith({ version: '0.0.0-test', locale: 'en', timezoneOffsetSeconds: -28_800, }) // The next call reads the zone again instead of reusing the first sample. offset.mockReturnValue(-300) await actions.refreshAccount() - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith({ + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith({ version: '0.0.0-test', locale: 'en', timezoneOffsetSeconds: 18_000, }) }, 60_000) @@ -783,3 +654,27 @@ it('applies API-key defaults through the desktop slot and shared configuration o expect(values['ui-settings']).toEqual({ enabled: true }) expect(values['ui-chat']).toMatchObject({ transcriptView: 'standard' }) }, 60_000) + + +it('ignores a delayed iterator rejection after the account plugin has unloaded', async ({ start }) => { + const c = await start() + const entered = Promise.withResolvers() + const failed = Promise.withResolvers() + onTestFinished(() => { failed.resolve(undefined) }) + const original = c.ctx.remote.$stream.bind(c.ctx.remote) + vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { + const stream = original(options) + vi.spyOn(stream, Symbol.asyncIterator).mockImplementation(async function* () { + entered.resolve(undefined) + await failed.promise + }) + return stream + }) + await c.reload(SELF) + await entered.promise + const actions = operations(c) + await c.unload(SELF) + failed.reject(new Error('late stream rejection')) + await c.flush() + expect(actions.hooks.account.getSnapshot()).toMatchObject({ view: undefined, failed: false }) +}) diff --git a/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts b/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts deleted file mode 100644 index 6ab5b50104..0000000000 --- a/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts +++ /dev/null @@ -1,612 +0,0 @@ -// @vitest-environment jsdom -/** - * Bonus notice lifecycle: reads happen when the account becomes active and on - * an explicit refresh, never on a timer. A notice is acknowledged only after its - * card reports a presented frame, with backoff retry for the rest of the - * signed-in lifecycle; nothing about a notice survives sign-out or unload. - */ -import { afterEach, expect, it, vi } from 'vitest' -import type { AccountBonusBatch, AccountBonusOrderId, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import { createBonusNoticeController, type BonusNotice } from '../src/client/bonus-notices.ts' - -const TIMING = { ackRetryDelayMs: 1_000, ackRetryMaxDelayMs: 60_000 } - -/** - * @param accountId - owning account. - * @param orderId - server order. - * @param expiresAt - server expiration. - * @returns one unnotified bonus as the Host projects it. - */ -function batch(accountId: string, orderId: string, expiresAt = '2099-01-01T00:00:00Z'): AccountBonusBatch { - return { - accountId: accountId as AccountUserId, - bonuses: [{ - orderId: orderId as AccountBonusOrderId, - expiresAt, - message: 'Server copy 5.00', - }], - } -} - -function setup() { - const read = vi.fn(async (): Promise => null) - const acknowledge = vi.fn(async (): Promise => true) - const stacks: (readonly BonusNotice[])[] = [] - const published: (BonusNotice | null)[] = [] - const controller = createBonusNoticeController({ - ...TIMING, read, acknowledge, publish: (notices) => { stacks.push(notices); published.push(notices[0] ?? null) }, - }) - /** @returns the most recently published notice. */ - const latest = (): BonusNotice | null | undefined => published.at(-1) - return { controller, read, acknowledge, published, latest, stacks } -} - -afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() }) - -it('reads once when the account becomes active and never on a timer', async () => { - vi.useFakeTimers() - const { controller, read } = setup() - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(1) - // Nothing else schedules a read: only an explicit refresh does. - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - expect(read).toHaveBeenCalledTimes(1) - await controller.refresh() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(2) - controller.end() -}) - -it('publishes the server copy for the first unnotified order', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', message: 'Server copy 5.00' }) }) - controller.end() -}) - -it('acknowledges only after the card reports a presented frame, then keeps the card until it is closed', async () => { - const { controller, read, acknowledge, published, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - expect(acknowledge).not.toHaveBeenCalled() - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - // A refresh still offering the order must not republish the open card. - const publishedBefore = published.length - await controller.refresh() - await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(2) }) - expect(published.length).toBe(publishedBefore) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.dismiss('order-1' as AccountBonusOrderId) - expect(latest()).toBeNull() - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('retries a failed acknowledgement with a growing backoff starting at the configured delay', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs - 1) - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(acknowledge).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 2) - expect(acknowledge).toHaveBeenCalledTimes(3) - controller.end() -}) - -it('keeps the card and its pending acknowledgement when the signed-in session re-enters', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // The second commit update of one sign-in and a reconnected stream's replayed - // state both re-enter here. Each frame reads again, and neither may drop the - // card or stop the failed acknowledgement from backing off. - controller.begin() - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(3) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - controller.end() -}) - -it.each(['aborted', 'null'] as const)("does not adopt the replaced credential's in-flight read when it answers %s", async (answer) => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // Account A's next signed-in frame starts a read the Host abandons when the - // credential is replaced by B. B's frame must not inherit it: A's answer names - // the replaced account, so adopting it would leave B with no read of its own. - const abandoned = Promise.withResolvers() - read.mockReturnValueOnce(abandoned.promise) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - read.mockResolvedValueOnce(batch('account-b', 'order-2')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(3) - expect(latest()).toMatchObject({ orderId: 'order-2' }) - if (answer === 'aborted') abandoned.reject(new Error('aborted')) - else abandoned.resolve(null) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - // The abandoned answer neither restores A's card nor resumes A's retry. - expect(latest()).toMatchObject({ orderId: 'order-2' }) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('refreshes the copy of the order already on screen when a read offers it again', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', message: 'Server copy 5.00' }) }) - // The same order arrives with new copy: its card updates in place instead of being replaced. - read.mockResolvedValue({ ...batch('account-a', 'order-1'), bonuses: [{ ...batch('account-a', 'order-1').bonuses[0]!, title: 'Updated title', message: 'Updated copy' }] }) - await controller.refresh() - expect(latest()).toMatchObject({ orderId: 'order-1', title: 'Updated title', message: 'Updated copy' }) - controller.end() -}) - -it('withdraws a card the user never saw when a read offers no bonus', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // The card never reported a presented frame, so an empty read withdraws it. - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [] }) - await controller.refresh() - expect(latest()).toBeNull() - controller.end() -}) - -it('queues the next shown order behind a settling acknowledgement', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((resolve) => { settle = resolve })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // A later order replaces the card while the first acknowledgement is still settling. - read.mockResolvedValue(batch('account-a', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.shown('order-2' as AccountBonusOrderId) - settle?.(true) - // The settled order clears and the next one follows without a further display. - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'order-2') }) - controller.end() -}) - -it('ignores an acknowledgement pump that fires while one is already in flight', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementation(() => new Promise((resolve) => { settle = resolve })) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // A Settings entry schedules another pump while the first call is unresolved. - read.mockResolvedValue(batch('account-a', 'order-1')) - void controller.refresh() - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - settle?.(true) - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.end() -}) - -it('stops retrying when the account changes while an acknowledgement is failing', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let fail: ((reason: Error) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // Another account answers before account-a's call fails: its failure must not - // schedule a retry into the new account's queue. - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - fail?.(new Error('offline')) - await new Promise((resolve) => { setTimeout(resolve, 10) }) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('ignores a dismissal that names an order the card does not show', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.dismiss('order-2' as AccountBonusOrderId) - // The other order's dismissal neither withdraws this card nor queues its acknowledgement. - expect(latest()).toMatchObject({ orderId: 'order-1' }) - expect(acknowledge).not.toHaveBeenCalled() - controller.end() -}) - -it('keeps one queued acknowledgement when a reported order returns after another card', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - read.mockResolvedValue(batch('account-a', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - read.mockResolvedValue(batch('account-a', 'order-1')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // Its acknowledgement was already queued and is still retrying, so no second entry joins it. - controller.shown('order-1' as AccountBonusOrderId) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.end() -}) - -it('displays an order the server offers again after an earlier sign-in acknowledged it', async () => { - const first = setup() - first.read.mockResolvedValue(batch('account-a', 'order-1')) - first.controller.begin() - await vi.waitFor(() => { expect(first.latest()).toMatchObject({ orderId: 'order-1' }) }) - first.controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(first.acknowledge).toHaveBeenCalledTimes(1) }) - first.controller.end() - // Nothing is remembered, so the same order the server still offers displays again. - const second = setup() - second.read.mockResolvedValue(batch('account-a', 'order-1')) - second.controller.begin() - await vi.waitFor(() => { expect(second.latest()).toMatchObject({ orderId: 'order-1' }) }) - second.controller.end() -}) - -it('discards the previous account card and retries when a credential is replaced without a signed-out frame', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockResolvedValue(false) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledOnce() }) - // The credential is replaced in place: another signed-in frame arrives, the read - // names the other account, and no signed-out frame ever describes the switch. - read.mockResolvedValue(batch('account-b', 'order-2')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.end() -}) - -it('keeps the retry going when the re-entry read fails', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // The replayed state re-enters and its read fails; a failed read must leave the - // pending acknowledgement retrying rather than strand it. - read.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - controller.end() -}) - -it('acknowledges a re-offered order once per displayed card', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // Closing the card withdraws it; the next read of the same order is a new card. - controller.dismiss('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(2) }) - controller.end() -}) - -it('keeps the visible card when a read offers no bonus', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // A card the user has already seen keeps its place. - controller.shown('order-1' as AccountBonusOrderId) - // A Settings entry whose read returns nothing must not pull the card out from under the user. - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [] }) - await controller.refresh() - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.dismiss('order-1' as AccountBonusOrderId) - await controller.refresh() - expect(latest()).toBeNull() - controller.end() -}) - -it('keeps a pending acknowledgement for the signed-in lifecycle and drops it at sign-out', async () => { - // Advance the backoff clock explicitly so retry observation has no competing deadline. - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - acknowledge.mockRejectedValue(new Error('offline')) - read.mockResolvedValue(batch('account-a', 'order-1')) - const again = setup() - try { - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - - // Signing out ends the retry with the lifecycle; the next sign-in starts clean. - controller.end() - const callsAtEnd = acknowledge.mock.calls.length - again.read.mockResolvedValue(batch('account-a', 'order-1')) - again.controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(again.latest()).toMatchObject({ orderId: 'order-1' }) - // The next sign-in must not inherit the earlier pending acknowledgement. - expect(again.acknowledge).not.toHaveBeenCalled() - expect(acknowledge.mock.calls.length).toBe(callsAtEnd) - // Past the next retry delay: the ended lifecycle scheduled nothing. - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 3) - expect(acknowledge.mock.calls.length).toBe(callsAtEnd) - } finally { - controller.end() - again.controller.end() - } -}) - -it('ignores an acknowledgement that settles after the lifecycle it belonged to', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementation(() => new Promise((resolve) => { settle = resolve })) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - controller.end() - // The new sign-in has its own pending queue; the old call settling later must not touch it. - const next = setup() - next.read.mockResolvedValue(batch('account-a', 'order-2')) - next.controller.begin() - await vi.waitFor(() => { expect(next.latest()).toMatchObject({ orderId: 'order-2' }) }) - next.controller.shown('order-2' as AccountBonusOrderId) - await vi.waitFor(() => { expect(next.acknowledge).toHaveBeenCalledTimes(1) }) - settle?.(true) - await new Promise((resolve) => { setTimeout(resolve, 5) }) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - expect(next.latest()).toMatchObject({ orderId: 'order-2' }) - next.controller.end() -}) - -it('does not let an in-flight acknowledgement of one account clear another account\'s queue', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settleA: ((value: boolean) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((resolve) => { settleA = resolve })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - // Another account answers the same lifecycle before account-a's call settles. - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - settleA?.(true) - await new Promise((resolve) => { setTimeout(resolve, 5) }) - // The stale answer settled account-a's order, not account-b's retry. - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.shown('order-2' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-b', 'order-2') }) - controller.end() -}) - -it('restarts the retry delay after a lifecycle ends', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 3) - expect(acknowledge.mock.calls.length).toBeGreaterThan(2) - controller.end() - // The next lifecycle starts from the configured delay, not the previous backoff. - const next = setup() - next.read.mockResolvedValue(batch('account-a', 'order-2')) - next.acknowledge.mockRejectedValue(new Error('offline')) - next.controller.begin() - await vi.advanceTimersByTimeAsync(0) - next.controller.shown('order-2' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs - 1) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(next.acknowledge).toHaveBeenCalledTimes(2) - next.controller.end() -}) - -it('withdraws the displayed card when the signed-in account changes', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.end() -}) - -it('never acknowledges after the plugin unloads', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.end() - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - expect(acknowledge).not.toHaveBeenCalled() -}) - -it('suppresses a bonus that expired before its first presented frame', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1', '2000-01-01T00:00:00Z')) - controller.begin() - await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(1) }) - expect(latest()).toBeUndefined() - controller.end() -}) - -it('does not record a display when the award expired before the card could render', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - // The card refuses to render an expired award, so no display is reported. - controller.shown('order-1' as AccountBonusOrderId) - expect(acknowledge).not.toHaveBeenCalled() - controller.end() -}) - -it('displays and acknowledges a notice without expiration', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1', '')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', expiresAt: '' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - controller.end() -}) - -it('publishes every live notice and only acknowledges the foreground as dismissals advance the stack', async () => { - const { controller, read, acknowledge, stacks } = setup() - const bonuses = ['first', 'second', 'third'].flatMap(id => batch('account-a', id, '').bonuses) - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toEqual(bonuses) }) - controller.shown('second' as AccountBonusOrderId) - controller.dismiss('third' as AccountBonusOrderId) - expect(acknowledge).not.toHaveBeenCalled() - expect(stacks.at(-1)).toEqual(bonuses) - controller.shown('first' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'first') }) - controller.dismiss('first' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual(bonuses.slice(1)) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.shown('second' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'second') }) - controller.dismiss('second' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual(bonuses.slice(2)) - controller.dismiss('third' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual([]) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'third') }) - controller.end() -}) - -it('drops queued notices that expire before promotion without acknowledging them', async () => { - const { controller, read, acknowledge, stacks } = setup() - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [ - ...batch('account-a', 'first', '').bonuses, - ...batch('account-a', 'expired', '2099-01-01T00:00:00Z').bonuses, - ...batch('account-a', 'last', '').bonuses, - ] }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(3) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - controller.dismiss('first' as AccountBonusOrderId) - expect(stacks.at(-1)?.map(notice => notice.orderId)).toEqual(['last']) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'first') }) - controller.end() -}) - -it('publishes a title-only refresh without acknowledging the same card twice', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'first', '')) - controller.begin() - await vi.waitFor(() => { expect(latest()?.orderId).toBe('first') }) - controller.shown('first' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, - bonuses: batch('account-a', 'first', '').bonuses.map(notice => ({ ...notice, title: 'Updated title' })) }) - await controller.refresh() - expect(latest()?.title).toBe('Updated title') - controller.shown('first' as AccountBonusOrderId) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('does not read or acknowledge when refreshed outside an active account lifecycle', async () => { - const { controller, read, acknowledge } = setup() - await controller.refresh() - expect(read).not.toHaveBeenCalled() - expect(acknowledge).not.toHaveBeenCalled() -}) - -it('closes the visible notice when the preceding card expires before its display callback', async () => { - const { controller, read, acknowledge, stacks } = setup() - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [ - ...batch('account-a', 'first', '2099-01-01T00:00:00Z').bonuses, - ...batch('account-a', 'second', '').bonuses, - ] }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(2) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - controller.dismiss('second' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual([]) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'second') }) - controller.end() -}) diff --git a/packages/client/ui-settings-account/tests/config.client.spec.ts b/packages/client/ui-settings-account/tests/config.client.spec.ts index 850cf78660..1129937481 100644 --- a/packages/client/ui-settings-account/tests/config.client.spec.ts +++ b/packages/client/ui-settings-account/tests/config.client.spec.ts @@ -11,13 +11,12 @@ const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) - const config: Config = Config({ contactSource: 'harness', bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100 }) - await ctx.plugin({ Config, apply }, { contactSource: 'harness', bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100 }) + const config: Config = Config({ contactSource: 'harness' }) + await ctx.plugin({ Config, apply }, { contactSource: 'harness' }) const table: IndexInjection[] = [] ctx.emit('webserver/index-inject', table, PAGE_PEER) expect(table).toEqual([{ kind: 'global', name: CONTACT_CONFIG_GLOBAL, value: { contactFormUrl: config.contactFormUrl, contactSource: config.contactSource, - bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100, } }]) await ctx.fiber.dispose() table.length = 0 diff --git a/packages/client/ui-settings-account/tests/initialization.client.spec.ts b/packages/client/ui-settings-account/tests/initialization.client.spec.ts index a17217f0d2..a6f1d82767 100644 --- a/packages/client/ui-settings-account/tests/initialization.client.spec.ts +++ b/packages/client/ui-settings-account/tests/initialization.client.spec.ts @@ -24,10 +24,12 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize const signedIn: AccountView = { status: 'credential-stored', links, attempt: { id: 'login' as SignInAttemptId, phase: 'succeeded' }, } - const frames: AccountView[] = [signedIn, signedIn, { status: 'signed-out', links, attempt: null }] + const frames: AccountView[] = [signedIn, signedIn, signedIn, { status: 'signed-out', links, attempt: null }] + const getNotifications = vi.fn(async () => ({ ok: true, value: null })) const disposers: (() => void)[] = [] let operations: AccountSectionInjected | undefined const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) disposers.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -55,11 +57,12 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize remote: { $on: () => () => {}, session: { initializeDefaultModel }, - account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }) }, + account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }), + getNotifications }, $stream: () => ({ signal: abort.signal, dispose: () => { abort.abort(); release.resolve(undefined) }, async *[Symbol.asyncIterator]() { - for (const value of frames) yield { value, accept: () => { + for (const [index, value] of frames.entries()) yield { generation: index < 2 ? 1 : 2, value: { type: 'snapshot', state: value }, accept: () => { const snapshot = operations?.hooks.account.getSnapshot() observed.push({ status: snapshot?.view?.status, failed: snapshot?.failed }) if (value.status === 'signed-out') done.resolve(undefined) @@ -73,7 +76,9 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize apply(ctx as never) await done.promise expect(initializeDefaultModel).toHaveBeenCalledExactlyOnceWith() + expect(getNotifications).not.toHaveBeenCalled() expect(observed).toEqual([ + { status: 'credential-stored', failed: false }, { status: 'credential-stored', failed: false }, { status: 'credential-stored', failed: false }, { status: 'signed-out', failed: false }, diff --git a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx index 04b3a65747..21523784dc 100644 --- a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx @@ -34,7 +34,7 @@ it('claims onboarding while loading, offers API key fallback, and completes afte useTheme: (select: (snapshot: ThemeSnapshot) => T) => select(theme), start: vi.fn(async () => {}), cancel: vi.fn(async () => {}), signOut: vi.fn(async () => {}), contactUs: vi.fn(), t: makeTranslate(en), - refreshAccount: vi.fn(async () => {}), bonusNoticeShown: vi.fn(), bonusNoticeDismissed: vi.fn(), + refreshAccount: vi.fn(async () => {}), avatarFailed: vi.fn(), } const view = render() diff --git a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx index 89fe09d0fe..7393ce1d5a 100644 --- a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx @@ -66,7 +66,7 @@ function sectionOperations(account: AccountSnapshot, pages: PlatformPages): Acco openPlatformPage: pages.open, refreshAccount: async () => {}, avatarFailed: () => {}, - bonusNoticeShown: () => {}, bonusNoticeDismissed: () => {}, + hasRunningAccountTasks: async () => false, contactUs: () => {}, showLogin: () => {}, setOnboarding: () => {}, start: async () => {}, cancel: async () => {}, signOut: async () => {}, diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index 216983e29e..a3e6d06c2b 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -15,8 +15,8 @@ en: 83760d53b3ee5fb8 zh: 30dd8802d4ffdcb7 /deepseek-ai-dsh-client-ui-settings-general/use-this-package: - en: d427d20b4dab6653 - zh: 84e80592f0a30a9f + en: 8ae337011190f5f3 + zh: 508eca60c6fcdc34 /deepseek-ai-dsh-client-ui-settings-general/use-this-package/the-general-section: en: de35e867b2a56d73 zh: 6d4e5c912636f889 @@ -27,8 +27,8 @@ en: 7600861d064dbc99 zh: a52ba446016e3a21 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation: - en: 9c8c35ae0e672b14 - zh: 503c8e9d24a93d88 + en: 4d25df8fe0e60b20 + zh: cecd02d3b6e47b24 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/ledger-projections: en: fd99444278ab8530 zh: 2efc5831c7e19be1 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index bca8bb88ee..a7782b0518 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -39,7 +39,7 @@ When the page reconnects to a Host running another release, a **Service version When the section navigation exceeds the panel's available height, the list scrolls independently of the settings content and keeps the Settings title fixed; in browsers below 768px the strip scrolls along its own axis the same way. -In Desktop, the account-row update control shows availability, progress, verification, readiness, and persistent retry feedback. It shares the connection indicator’s 28px height, 8px corners, 14px icon slot, 4px icon gap, and 12px medium text with an 18px line height; update-state border, fill, and text colors remain independently defined. Retry text and its dot use the same brand blue as other update labels; numeric download progress has no ellipsis. The preload carries semantic phase, version, progress, and classified failures; the component resolves every visible and accessible string from the active `settings` locale, including after an in-application language change. Selecting an available update starts downloading; installation requires a separate shell-owned confirmation. A collapsed sidebar shows the same status as a brand-blue dot on its top expand button, including failures. Connection feedback takes priority except during shell-reported installation, when the expected backend disconnect must not hide update status. Failure restores connection feedback. Both controls share one carrier subscription; browser code cannot choose packages or authorize installation. [Desktop updates](../../../apps/desktop/README.md) owns the release workflow. Checking, verifying, and preparing-to-restart tooltips show only the supplied version; without a version, they retain the state label. Desktop update tooltips preserve the complete version and prerelease suffix without adding v or V; their error summaries match the shell update dialogs, including guidance to exit fullscreen and retry after a fullscreen-transition timeout. +In Desktop, the account-row update control shows availability, progress, verification, readiness, and persistent retry feedback. It shares the connection indicator’s 28px height, 8px corners, 14px icon slot, 4px icon gap, and 12px medium text with an 18px line height; update-state border, fill, and text colors remain independently defined. Retry text and its dot use the same brand blue as other update labels; numeric download progress has no ellipsis and uses tabular digits with space for three digits and the percent sign to keep its width stable. The preload carries semantic phase, version, progress, and classified failures; the component resolves every visible and accessible string from the active `settings` locale, including after an in-application language change. Selecting the download percentage opens the shell’s download-status dialog; closing it leaves the download running. Selecting an available update starts downloading; installation requires a separate shell-owned confirmation. A collapsed sidebar shows the same status as a brand-blue dot on its top expand button, including failures. Connection feedback takes priority except during shell-reported installation, when the expected backend disconnect must not hide update status. Failure restores connection feedback. Both controls share one carrier subscription; browser code cannot choose packages or authorize installation. [Desktop updates](../../../apps/desktop/README.md) owns the release workflow. Checking, verifying, and preparing-to-restart tooltips show only the supplied version; without a version, they retain the state label. Desktop update tooltips preserve the complete version and prerelease suffix without adding v or V; their error summaries match the shell update dialogs, including guidance to exit fullscreen and retry after a fullscreen-transition timeout. Settings visibility and section selection live in the shell owner store. The shell supplies the effective Settings binding to the contributed launcher for menu keycaps and `aria-keyshortcuts`; the fallback button uses the same binding for hover and keyboard-focus hints and `aria-keyshortcuts`. The Settings command (Desktop: `Mod+,`; Windows/macOS Web: `Mod+Alt+,`) toggles the dialog when Settings is in front or no modal is open; the sidebar control opens the same dialog. The command cannot open or close Settings while the shortcut reference or another modal is in front. Held-key repeats do nothing. The account menu opens General settings; closing the dialog clears the section selection. Onboarding can open a specified section. Initial focus lands on the selected section in the navigation, or on the title when no sections are available, without drawing a focus outline. The section buttons precede header actions and Close in the Tab order. Tab and directional navigation retain their visible focus indicators. `Mod+/` can open the shortcut reference above Settings; `Escape` closes the top dialog and restores focus to its invoking control. Return focus omits outlines after shortcut, Escape, or pointer dismissal. @@ -68,7 +68,7 @@ Desktop also contributes an **Update channel** row to General when the preload e ## Understand the implementation -The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. +The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section.
Implementation internals — click to expand diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index e014b6f91f..a9e949c08e 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference" 当分区导航超出面板可用高度时,列表独立于设置内容滚动,并保持「设置」标题固定;浏览器宽度低于 768px 时,条带以同样方式沿自身轴滚动。 -在 Desktop 中,账户行更新控件显示可用版本、进度、验证、就绪和持久重试反馈。它与连接指示器共用 28px 高度、8px 圆角、14px 图标占位、4px 图文间距,以及 12px 中等字重文字和 18px 行高;更新状态的边框、填充和文字颜色独立定义。重试文字及其圆点与其他更新文案使用相同的品牌蓝色;数字下载进度不带省略号。预加载仅传递语义化阶段、版本、进度和失败类别;组件从当前 `settings` locale 解析全部可见与无障碍文案,并在应用内语言变化后同步更新。选择可用更新即开始下载;安装需要独立的壳拥有的确认。侧栏收起时,其顶部展开按钮以品牌蓝色圆点显示相同状态,包括失败状态。连接反馈通常优先展示,但壳报告正在安装时,预期的后端断开不能遮盖更新状态;失败后恢复连接反馈。两个控件共用一次载体订阅;浏览器代码不能选择安装包或授权安装。[Desktop 更新](../../../apps/desktop/README.zh.md)负责发布流程。检查中、校验中和准备重启状态的悬浮提示只显示已提供的版本号;没有版本号时保留状态文案。桌面更新提示完整保留版本号及预发布后缀,不额外添加 v 或 V;错误提示与桌面升级弹窗保持一致,包括全屏切换超时后退出全屏并重试的指引。 +在 Desktop 中,账户行更新控件显示可用版本、进度、验证、就绪和持久重试反馈。它与连接指示器共用 28px 高度、8px 圆角、14px 图标占位、4px 图文间距,以及 12px 中等字重文字和 18px 行高;更新状态的边框、填充和文字颜色独立定义。重试文字及其圆点与其他更新文案使用相同的品牌蓝色;数字下载进度不带省略号,采用等宽数字并预留三位数字及百分号的空间,使宽度保持稳定。预加载仅传递语义化阶段、版本、进度和失败类别;组件从当前 `settings` locale 解析全部可见与无障碍文案,并在应用内语言变化后同步更新。选择下载百分比会打开壳的下载状态提示,关闭提示不影响下载。选择可用更新即开始下载;安装需要独立的壳拥有的确认。侧栏收起时,其顶部展开按钮以品牌蓝色圆点显示相同状态,包括失败状态。连接反馈通常优先展示,但壳报告正在安装时,预期的后端断开不能遮盖更新状态;失败后恢复连接反馈。两个控件共用一次载体订阅;浏览器代码不能选择安装包或授权安装。[Desktop 更新](../../../apps/desktop/README.zh.md)负责发布流程。检查中、校验中和准备重启状态的悬浮提示只显示已提供的版本号;没有版本号时保留状态文案。桌面更新提示完整保留版本号及预发布后缀,不额外添加 v 或 V;错误提示与桌面升级弹窗保持一致,包括全屏切换超时后退出全屏并重试的指引。 设置的可见状态和分区选择由 shell owner store 保存。外壳将设置命令的有效绑定传给入口贡献,用于菜单键帽和 `aria-keyshortcuts`;回退按钮使用相同绑定提供悬停、键盘聚焦提示和 `aria-keyshortcuts`。设置位于最前方或没有模态弹窗时,设置命令(Desktop 为 `Mod+,`,Windows/macOS Web 为 `Mod+Alt+,`)切换设置弹窗的开关;侧栏控件打开同一弹窗。快捷键速查或其他模态弹窗位于前方时,该命令不能打开或关闭设置。长按产生的重复按键不执行操作。账号菜单打开通用设置;关闭弹窗会清空分区选择。引导流程可以打开指定分区。初始焦点落在导航中选中的分区;没有可用分区时落在标题上,均不绘制焦点外轮廓线。Tab 顺序中,分区按钮先于头部操作和关闭按钮。Tab 和方向键导航保留可见焦点提示。`Mod+/` 可在设置上方打开快捷键速查;`Escape` 关闭最上层弹窗,焦点返回触发该弹窗的控件。通过快捷键、Esc 或鼠标关闭后的回焦均不绘制外轮廓线。 @@ -68,7 +68,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ## 理解实现 -外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 +外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。
实现细节——点击展开 diff --git a/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.module.css b/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.module.css index b5b0eea658..2a503fb967 100644 --- a/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.module.css +++ b/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.module.css @@ -20,6 +20,12 @@ cursor: pointer; } +.progress { + min-inline-size: calc(3ch + 1em); + font-variant-numeric: tabular-nums; + text-align: end; +} + .icon { display: grid; place-items: center; diff --git a/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.tsx b/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.tsx index ae22d5c6fb..4fcc71f12a 100644 --- a/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.tsx +++ b/packages/client/ui-settings-general/src/client/DesktopUpdateIndicator.tsx @@ -73,14 +73,15 @@ export function DesktopUpdateIndicator({ wide, hidden, t, view, onOpen }: { const label = failed ? retryLabel : copy.label const error = failed || state?.phase === 'error' || state?.configurationError !== undefined const busy = opening || (state !== undefined && state.configurationError === undefined && BUSY_PHASES.has(state.phase)) + const disabled = opening || (busy && state?.phase !== 'downloading') return } diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index 980e59a06d..95e74201b7 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -224,7 +224,10 @@ export function SettingsRoot(props: SettingsRootComponentProps) { <>
{renderSlot('settings.launcher', { - wide, settingsOpen: open, openSettings: actions.open, + wide, settingsOpen: open, openSettings: (sectionId) => { + if (sectionId === undefined) actions.open() + else actions.openSection(sectionId) + }, ...(shortcut?.keys.length ? { settingsShortcut: { keys: shortcut.keys, aria: shortcut.aria } } : {}), openOnboarding: (id) => { close(); setRequestedOnboarding(id) }, }, { fallback: diff --git a/packages/client/ui-settings-general/src/client/desktop-update-source.ts b/packages/client/ui-settings-general/src/client/desktop-update-source.ts index d7025952b6..ac62ff44d7 100644 --- a/packages/client/ui-settings-general/src/client/desktop-update-source.ts +++ b/packages/client/ui-settings-general/src/client/desktop-update-source.ts @@ -8,6 +8,7 @@ export class DesktopUpdateSource { readonly store = createSnapshotStore({ failed: false, opening: false }) private live = true private received = false + private openingOperation: symbol | undefined private readonly unsubscribe: (() => void) | undefined /** @param bridge - Optional isolated Electron API, absent in ordinary browsers. */ @@ -15,7 +16,10 @@ export class DesktopUpdateSource { this.unsubscribe = bridge?.subscribe((presentation) => { if (!this.live) return this.received = true - this.store.set({ ...this.store.getSnapshot(), presentation, failed: false }) + const previous = this.store.getSnapshot() + const startedDownload = presentation.phase === 'downloading' && previous.presentation?.phase !== 'downloading' + if (startedDownload) this.openingOperation = undefined + this.store.set({ ...previous, presentation, failed: false, opening: startedDownload ? false : previous.opening }) }) void bridge?.status().then((presentation) => { if (this.live && !this.received) this.store.set({ ...this.store.getSnapshot(), presentation }) @@ -29,12 +33,17 @@ export class DesktopUpdateSource { if (!this.live || this.bridge === undefined) return const state = this.store.getSnapshot() if (state.opening || (state.presentation !== undefined && state.presentation.configurationError === undefined - && ['checking', 'downloading', 'verifying', 'installing'].includes(state.presentation.phase))) return + && ['checking', 'verifying', 'installing'].includes(state.presentation.phase))) return + const operation = Symbol() + this.openingOperation = operation this.store.set({ ...state, opening: true }) void this.bridge.open().catch(() => { - if (this.live) this.store.set({ ...this.store.getSnapshot(), failed: true }) + if (this.live && this.openingOperation === operation) this.store.set({ ...this.store.getSnapshot(), failed: true }) }).finally(() => { - if (this.live) this.store.set({ ...this.store.getSnapshot(), opening: false }) + if (this.live && this.openingOperation === operation) { + this.openingOperation = undefined + this.store.set({ ...this.store.getSnapshot(), opening: false }) + } }) } diff --git a/packages/client/ui-settings-general/tests/desktop-update.client.spec.tsx b/packages/client/ui-settings-general/tests/desktop-update.client.spec.tsx index a1291e5fb6..3a207e1fde 100644 --- a/packages/client/ui-settings-general/tests/desktop-update.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/desktop-update.client.spec.tsx @@ -71,8 +71,10 @@ it('keeps the newest event, hides for connection priority, and invokes only the expect(screen.queryByRole('button')).toBeNull() await f.emit({ phase: 'downloading', version: available.version, percent: 58 }) f.view.rerender() + expect(screen.getByRole('button', { name: '58%' }).getAttribute('aria-disabled')).toBe('false') fireEvent.click(screen.getByRole('button', { name: '58%' })) - expect(f.open).toHaveBeenCalledOnce() + await act(async () => {}) + expect(f.open).toHaveBeenCalledTimes(2) await f.emit({ phase: 'error', version: available.version, failure: 'download' }) const retry = screen.getByRole('button', { name: '重试更新' }) fireEvent.focus(retry) @@ -214,3 +216,27 @@ it('keeps a configuration error actionable while download progress continues', a f.view.unmount() f.status.resolve({ phase: 'idle' }) }) + +it('opens download status while the original download action remains pending and coalesces status clicks', async () => { + const f = fixture() + const download = Promise.withResolvers() + const statusDialog = Promise.withResolvers() + try { + await act(async () => { f.status.resolve(available) }) + f.open.mockImplementationOnce(() => download.promise).mockImplementationOnce(() => statusDialog.promise) + fireEvent.click(screen.getByRole('button', { name: '新版本' })) + await f.emit({ phase: 'downloading', percent: 12, version: available.version }) + const progress = screen.getByRole('button', { name: '12%' }) + fireEvent.click(progress) + fireEvent.click(progress) + expect(f.open).toHaveBeenCalledTimes(2) + await act(async () => { download.resolve(undefined) }) + expect(progress.getAttribute('aria-disabled')).toBe('true') + await act(async () => { statusDialog.resolve(undefined) }) + expect(progress.getAttribute('aria-disabled')).toBe('false') + } finally { + f.view.unmount() + download.resolve(undefined) + statusDialog.resolve(undefined) + } +}) diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index 094ef4787a..7a3e6ba80f 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -524,6 +524,14 @@ it('opens Account from the contributed sidebar launcher', () => { expect(renderSlot.mock.calls.filter(call => call[0] === 'settings.launcher').at(-1)?.[1]).toMatchObject({ settingsOpen: false }) }) +it('opens the section requested by the contributed sidebar launcher', () => { + const { renderSlot } = mount({ rows: [{ id: 'general', order: 0, label: 'General' }, { id: 'account', order: 1, label: 'Account' }] }) + const launcher = renderSlot.mock.calls.find(call => call[0] === 'settings.launcher')! + act(() => { (launcher[1] as { openSettings: (sectionId?: string) => void }).openSettings('account') }) + expect(screen.getByTestId('section-account')).toBeTruthy() + expect(screen.queryByTestId('section-general')).toBeNull() +}) + it('shows the effective settings binding on focus and exposes it to assistive technology', () => { mount({ shortcuts: [{ id: 'settings.open' as ShortcutCommandId, label: 'Open settings', aliases: [], keys: ['⌘', ','], aria: 'Meta+,', binding: { code: 'Comma', modifiers: ['meta'] }, modified: false, conflicts: [], issue: null }] }) const trigger = screen.getByRole('button', { name: 'Settings' }) diff --git a/packages/client/ui-settings-general/tests/shell.client.spec.ts b/packages/client/ui-settings-general/tests/shell.client.spec.ts index 4b5776de36..75af01b079 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -121,13 +121,13 @@ describe('ui-settings-general shell', () => { const { sections } = injectedOf(c).hooks await c.mock.streams.opened('account/watch', 1) expect(sections.getSnapshot().map(row => row.id)).toEqual(PRODUCT_SECTIONS) - c.mock.streams.push('account/watch', { status: 'credential-stored', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'credential-stored', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().map(row => row.id)).toEqual(['account', ...PRODUCT_SECTIONS]) }) - c.mock.streams.push('account/watch', { status: 'credential-stored', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'credential-stored', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().filter(row => row.id === 'account')).toHaveLength(1) }) - c.mock.streams.push('account/watch', { status: 'signed-out', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'signed-out', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().map(row => row.id)).toEqual(PRODUCT_SECTIONS) }) }) diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 74ecbbb6d5..0b4439bdbe 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: f4817eb2e3537ed9 - zh: e589c193fa85473f + en: fa2cefbf8c4fdafe + zh: 3a4689591b50f6ea /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: a0501172f15c3286 - zh: 6dfa112f215b2d3d + en: a83a61e44b6f1c00 + zh: 2dc6d84692e524ac /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 5039f7988d..ec7675d6c6 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,15 +41,15 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. +API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. An editable, nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display the Host-generated masked preview as a placeholder; the actual input value stays empty and the full key never reaches the Client. A provider that omits the preview shows only the saved-key notice. The local provider’s [preview policy](../../credentials/credentials-local/README.md) preserves selected identifying characters and the Unicode code-point count. Saved keys hide the reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. -The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint never receives a credential value or changes field writability. +The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint receives no credential value and never changes field writability. ### Editing a provider -A blank key field offers a saved credential when one is detected, with no status text below the input; otherwise it offers environment authentication. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +Leaving the saved mask untouched preserves existing authentication. A saved credential shows a server-masked preview and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Apply; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Apply to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their full values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index a6a1595bda..244e1c0e05 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,7 +41,7 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。 +API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。可编辑的草稿非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥以 Host 生成的脱敏预览作为占位文字;实际输入值保持为空,完整密钥不进入 Client。提供方未提供预览时,仅显示使用已保存密钥的提示。本地提供方的[预览规则](../../credentials/credentials-local/README.zh.md)保留部分识别字符和 Unicode 码点数。已保存密钥隐藏显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 @@ -49,7 +49,7 @@ API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求 ### 编辑提供商 -密钥字段留空时,已检测到已保存凭据则提示使用该凭据,输入框下方不显示状态文字;否则提示使用环境认证。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +保持已保存掩码不变时保留现有认证。已保存凭据显示服务端生成的脱敏预览和绿色的使用已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将完整变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index e983a40303..64ce7ac448 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -1,4 +1,4 @@ -/** Write-only credential input with the same reveal behavior as masked conversation text. */ +/** Credential drafts can be revealed; saved keys are represented by a protected mask. */ import { useState } from 'react' import type { InputHTMLAttributes, ReactNode } from 'react' import type { en } from './locales.ts' @@ -12,37 +12,51 @@ const EYE_OFF_PATH = `${EYE_CONTOUR}M2.5 2.5L13.5 13.5` interface ApiKeyInputProps extends Omit, 'value' | 'type' | 'className' | 'autoComplete'> { /** Unsaved input; stored credentials are never read into this field. */ readonly value: string + /** Server-masked preview and actions; the full stored credential stays on the Host. */ + readonly saved?: { + readonly masked: string + readonly clear?: () => void + } /** Section copy, including the same reveal labels as SecretText. */ readonly t: (key: keyof typeof en) => string } /** - * Reveal only a nonempty draft; a different value starts masked, as in SecretText. + * Reveal only a nonempty draft. Saved keys allow whole replacement or deletion. * @param props - current draft, input attributes, and translated control labels. * @returns a password input with an optional reveal button. */ -export function ApiKeyInput({ value, t, ...props }: ApiKeyInputProps): ReactNode { +export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): ReactNode { const [revealedValue, setRevealedValue] = useState() - const revealed = value.length > 0 && revealedValue === value + const canReveal = saved === undefined && value.length > 0 && props.disabled !== true + const revealed = canReveal && revealedValue === value return ( -
+
0 ? styles['keyInputFilled'] : ''}`} + className={`${styles['input']} ${canReveal ? styles['keyInputFilled'] : ''}`} type={revealed ? 'text' : 'password'} autoComplete="new-password" value={value} + placeholder={saved === undefined ? props.placeholder : saved.masked} + onCopy={(event) => { if (saved !== undefined) event.preventDefault() }} + onCut={(event) => { if (saved !== undefined) event.preventDefault() }} + onKeyDown={(event) => { + if (saved !== undefined && (event.key === 'Backspace' || event.key === 'Delete')) { + event.preventDefault() + saved.clear?.() + } + }} onChange={(event) => { setRevealedValue(undefined) props.onChange?.(event) }} /> - {value.length === 0 ? null :
-
+
{children}
diff --git a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx index fb24a887b4..8e0c2b089c 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx @@ -861,6 +861,8 @@ describe('TextPreview — workspace navigator Factories', () => { return { toggle: header?.lastElementChild?.getAttribute('data-navigator-factory'), navigator: row?.lastElementChild?.getAttribute('data-navigator-factory'), + // The navigator's filled layout hides the body of the row this attribute names. + navigatorRow: row?.hasAttribute('data-files-navigator-row'), } } @@ -876,7 +878,7 @@ describe('TextPreview — workspace navigator Factories', () => { ]) expect(view.container.querySelector('[data-textpreview-state="loading"]')).not.toBeNull() expect(seats(view.container)).toEqual({ - toggle: 'sidebar.files.navigator.toggle', navigator: 'sidebar.files.navigator', + toggle: 'sidebar.files.navigator.toggle', navigator: 'sidebar.files.navigator', navigatorRow: true, }) const navigator = view.container.querySelector('[data-textpreview-content] > [data-navigator-factory]')! const toggle = view.container.querySelector('[data-textpreview-path]')?.parentElement?.lastElementChild @@ -890,7 +892,7 @@ describe('TextPreview — workspace navigator Factories', () => { await settle() expect(view.container.querySelector('[data-textpreview-state="text"]')).not.toBeNull() expect(seats(view.container)).toEqual({ - toggle: 'sidebar.files.navigator.toggle', navigator: 'sidebar.files.navigator', + toggle: 'sidebar.files.navigator.toggle', navigator: 'sidebar.files.navigator', navigatorRow: true, }) expect(view.container.querySelector('[data-textpreview-content] > [data-navigator-factory]')).toBe(navigator) expect(view.container.querySelector('[data-textpreview-path]')?.parentElement?.lastElementChild).toBe(toggle) diff --git a/packages/client/ui-sidebar-files/README.i18n.yaml b/packages/client/ui-sidebar-files/README.i18n.yaml index 4006a124b3..dd3d34d879 100644 --- a/packages/client/ui-sidebar-files/README.i18n.yaml +++ b/packages/client/ui-sidebar-files/README.i18n.yaml @@ -9,32 +9,35 @@ en: ae5625c23b3a864f zh: 20cf48a229e806bf /deepseek-ai-dsh-client-ui-sidebar-files/summary: - en: 27a736e484be8693 - zh: 4778c310014c2c16 + en: 46067f0415ea2e76 + zh: f0b48804ad460a05 /deepseek-ai-dsh-client-ui-sidebar-files/table-of-contents: - en: 94e520881bd8666e - zh: 869ed79bd370c8b3 + en: 81cb6e051699a7b4 + zh: 566d0278acae69fa /deepseek-ai-dsh-client-ui-sidebar-files/what-it-registers: - en: 2b620997cf39cac8 - zh: ddfaa2da1c1bcd55 + en: c4b8f3a52f68bd51 + zh: 30b580320637572c /deepseek-ai-dsh-client-ui-sidebar-files/the-navigator: - en: 20a35b3b05ac0189 - zh: 4118fc609e94dffe + en: 3424600b15bde2d2 + zh: 2cf1c99ffef2ad50 /deepseek-ai-dsh-client-ui-sidebar-files/the-tree: - en: c6d5d2d068bdec7b - zh: dd41bcfa3e9080ad + en: 3d71e50801761213 + zh: e4e9ab19dd22288d +/deepseek-ai-dsh-client-ui-sidebar-files/search: + en: 275bc2aa20907881 + zh: 4dac902558cb29f5 /deepseek-ai-dsh-client-ui-sidebar-files/reusable-tree-factory: - en: 0a3e9645426b4203 - zh: 0478669e4157f15c + en: 76e4d93d65d3c50e + zh: b611bba888f86b85 /deepseek-ai-dsh-client-ui-sidebar-files/model-experience: en: a18a43f6842f1371 zh: 69f2a2b35f06dfc7 /deepseek-ai-dsh-client-ui-sidebar-files/model-experience/kv-cache-effect: - en: 5a6febb45089991a - zh: b17ed755fd098b83 + en: 39debadcc6cefd24 + zh: cc212c8377851a91 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work: - en: dd317b62980a9269 - zh: 0be3b9924f6b6c67 + en: f28a32e47e684f5c + zh: e5e38014048ebe59 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work/dev-note: en: 1ec99e9fb6b4c948 zh: c4f7883934307c3c diff --git a/packages/client/ui-sidebar-files/README.md b/packages/client/ui-sidebar-files/README.md index 23ac780722..3991ccec18 100644 --- a/packages/client/ui-sidebar-files/README.md +++ b/packages/client/ui-sidebar-files/README.md @@ -9,13 +9,14 @@ English | [中文](README.zh.md) ## Summary -Browse a Session's workspace tree beside the files you preview. Each pane, docked or floating, keeps one tree that every file tab in it shows: switching, opening, or closing files keeps its width, expansion, and scroll, and the tree marks the current file. A preview's tree opens a file in place of that preview; the `files` page opens it in a new tab where the right Sidebar places it by default. The root and expanded directories refresh automatically from direct-entry watches; manual reload remains available. The `files` page is reached from the guide and claims no resource address. +Browse a Session's workspace tree beside the files you preview. Each pane keeps one tree that every file tab in it shows with its width, expansion, and scroll, marking the current file. Its search bar searches the whole workspace through the Host. A preview's tree opens a file in place of that preview; the `files` page opens it in a new tab where the right Sidebar places it by default. The root and expanded directories refresh from direct-entry watches or on reload. The `files` page is reached from the guide and claims no resource address. ## Table of Contents - [What it registers](#what-it-registers) - [The navigator](#the-navigator) - [The tree](#the-tree) +- [Search](#search) - [Reusable tree Factory](#tree-factory) - [Model Experience](#model-experience) - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) @@ -26,13 +27,13 @@ Browse a Session's workspace tree beside the files you preview. Each pane, docke ## What it registers -The `workspace.files` command shows the navigator drawn beside a docked tab's content in the focused pane and moves keyboard focus to its tree, keeping the tab; from the conversation it uses the current Session's active dock pane. Elsewhere — the files page itself, a tab without the navigator, a Session without a working directory, a floating tab — it opens or focuses the files page, whose tree always shows. A guide gives way to the files page, and repeated opens retain one files page per pane. Desktop defaults to Mod+P. The guide entry displays the effective shortcut; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves this command unbound by default. +The `workspace.files` command shows the navigator beside a docked preview or expands the search bar on an existing docked files page, and moves keyboard focus to its search field, keeping the tab; from the conversation it uses the current Session's active dock pane. Elsewhere — a tab without the navigator, a Session without a working directory, a floating tab — it opens or focuses the files page, whose tree always shows. A guide gives way to the files page, and repeated opens retain one files page per pane. Desktop defaults to Mod+P. The guide entry displays the effective shortcut; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves this command unbound by default. - **The type** — `ctx.sidebarRightTabs.register(...)` with kind `files`, id `@deepseek-ai/dsh-client-ui-sidebar-files`, band `builtin`, no patterns, and one guide entry (order 10, its title and description from the `sidebarFiles` namespace, its glyph a yellow folder) that opens the type. -- **The page body** — the keyed `sidebar.right.pane.tab` seat under that id. Its header row spans the page and shows the root through the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) with subdued directories and a primary final segment; a clipped path retains its trailing characters with a left-edge fade, and hovering reveals the full path. The tree's reload control, the Session-scoped `sidebar.right.tab.files.actions` list, which the page's registration declares, with the displayed root passed as `absolutePath`, follow at its end, in the order a preview's header ends with its reload and file actions; [`ui-open-in-app`](../ui-open-in-app/README.md) contributes the workspace directory opener. The pane's navigator fills the page below the header, docked or floating, and has no toggle there. +- **The page body** — the keyed `sidebar.right.pane.tab` seat under that id. Its header row spans the page and shows the root through the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) with subdued directories and a primary final segment; a clipped path retains its trailing characters with a left-edge fade, and hovering reveals the full path. The tree's reload control and search-bar toggle precede the Session-scoped `sidebar.right.tab.files.actions` list, which the page's registration declares, with the displayed root passed as `absolutePath`; [`ui-open-in-app`](../ui-open-in-app/README.md) contributes the workspace directory opener. The pane's navigator fills the page below the header, docked or floating, and has no navigator toggle there. - **The rows** — the root-scoped Component Factory `sidebar.files.tree`, with caller-owned entries and a local `accessory` slot; see [Reusable tree Factory](#tree-factory). -- **The navigator** — the Session-scoped Component Factory `sidebar.files.navigator`, rendered directly by the page body and [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.md) beside every preview, docked or floating. It draws the tree and its resize edge without a header of its own: beside a preview the preview's header is the only one, and the tree's reload and directory actions stay on the `files` page. -- **The toggle** — the Session-scoped Factory `sidebar.files.navigator.toggle`, rendered directly at the end of the preview header with `useTabInfo`. Both Factories share the page's store handle and inject face, retaining one open choice per pane; the page body has no toggle. +- **The navigator** — the Session-scoped Component Factory `sidebar.files.navigator`, rendered directly by the page body and [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.md) beside every preview, docked or floating. It draws the [search bar](#search), the tree, and its resize edge without a header of its own: beside a preview the preview's header is the only one, and the tree's reload and directory actions stay on the `files` page. +- **The toggle** — the Session-scoped Factory `sidebar.files.navigator.toggle`, rendered directly at the end of the preview header with `useTabInfo`. Both Factories share the page's store handle and inject face, retaining one open choice per pane; the page body has no navigator toggle. - **The chip title** — the keyed `sidebar.right.pane.tab.title` seat under that id: a shared `FileTypeIcon` folder glyph at 16px before the type's label. The tree's own rows never draw this sheet. The [registration](src/client/index.ts) assembles the page, navigator, toggle, and tree Factories over the shared [files face](src/client/face.ts) and [pane store](src/client/store.ts). @@ -40,9 +41,9 @@ The [registration](src/client/index.ts) assembles the page, navigator, toggle, a ## The navigator -Render `sidebar.files.navigator` with `FileNavigatorInput`: `{ useTabInfo, page, onOpen }`. The required `onOpen: (address: string) => void` callback belongs to the containing plugin; the navigator builds the file address without choosing placement. `page` controls presentation only: `true` always fills the files page, while `false` follows the preview's pane preference and available width. +Render `sidebar.files.navigator` with `FileNavigatorInput`: `{ useTabInfo, page, onOpen }`. The required `onOpen: (address: string) => void` callback belongs to the containing plugin; the navigator builds the file address without choosing placement. `page` controls presentation only: `true` always fills the files page, while `false` follows the preview's pane preference and available width. Render the Factory as a direct child of the row it shares with the body, and mark that row with `data-files-navigator-row`: the layout that fills the row hides the row's other children only under that attribute, so a host without it leaves the covered body reachable by keyboard. -The navigator is drawn below the preview's header, which spans the pane, at the right of the row it shares with the body. Beside a preview, its pane's record decides whether it shows: a pane starts with it hidden, and the choice holds for every file tab of the pane until the toggle, Escape, the workspace command, or navigation to a covered preview changes it. A pane without a record of its own, such as a floating panel a tab was dragged out into, starts hidden at the default width. A click outside the tree does not hide it, and opening content in another pane does not hide it either. On the files page the tree fills the page below the header, docked or floating, without a separator, and always shows: the page draws no toggle and Escape leaves it. A file the page opens starts with the destination pane's own choice, hidden for a pane that has made none. +The navigator is drawn below the preview's header, which spans the pane, at the right of the row it shares with the body. Beside a preview, its pane's record decides whether it shows: a pane starts with it hidden, and the choice holds for every file tab of the pane until the toggle, Escape, the workspace command, or navigation to a covered preview changes it. A pane without a record of its own, such as a floating panel a tab was dragged out into, starts hidden at the default width. A click outside the tree does not hide it, and opening content in another pane does not hide it either. On the files page the tree fills the page below the header, docked or floating, without a separator, and always shows: the page draws no navigator toggle and Escape leaves it. A file the page opens starts with the destination pane's own choice, hidden for a pane that has made none. Its width is the pane's preference, 260px until the reader drags the separator on its left edge with the primary button or moves it with the arrow keys, Home (narrowest), or End (widest), clamped to the row: at least 180px when the row allows it, and at most the row's width less 336px where the navigator sits beside the body and less 120px where it floats. Beside a preview in a viewport at least 768px wide, the row's width, measured by the face, picks one of three layouts. From 560px on, the navigator is a raised panel beside the body, 8px inside the row's top, right, and bottom edges and 8px clear of the body, which narrows by the panel and its margins but keeps at least 320px. From 400px up to 560px, the same panel floats over the body's right part, so the body keeps its full width and the part the panel leaves uncovered stays scrollable and interactive; the panel covers the body's scrollbar and a renderer's sticky toolbar where they run beneath it. Both panels have rounded corners, the first raised background layer, and the shared elevation shadow with a hairline that is lighter in dark mode. The 560px threshold depends on the row alone, so resizing the tree never moves it between the two layouts. In a row narrower than 400px, or a viewport narrower than 768px, where the right Sidebar presents its panel fullscreen, the navigator fills the row below the header without the separator, and navigation to that preview hides the tree so the file shows. While filled, the covered body is hidden from keyboard navigation, including embedded frames. If the body holds focus when the row or viewport enters this layout, including the tree's first drawing, focus moves into the tree without changing the pane's open choice. The browser may blur the hidden body before the new width is reported; that focus also moves into the tree unless the reader moves the keyboard or the pointer, or the window loses focus, before the report. Docked and floating panes follow the same rules; the floating pane's resize handle remains reachable with the tree open in every layout. Beside a preview, an unmodified Escape that reaches the page's document from the body or the tree in the row closes the navigator at any row width and moves keyboard focus to the toggle; a key pressed while an embedded frame's document holds focus does not bubble to the page's document, so it leaves the navigator open. Escape is heard on the document after the row's own handlers, so a handler in the row that prevents it keeps it. @@ -55,7 +56,7 @@ The tree marks the row of the current file with `aria-current`. While the tree i ## The tree -The root is the session's working directory, read from `useSessions().byId[sessionId].cwd`. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Dotfiles are shown like any other entry. +The root is the session's working directory, read from `useSessions().byId[sessionId].cwd`. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Entries whose name starts with `.` are left out until the reader [shows hidden entries](#search). | Entry type | Row | |---|---| @@ -63,20 +64,35 @@ The root is the session's working directory, read from `useSessions().byId[sessi | `file` | Opens `dsh-resource://file/session//`, built by `fileAddressFor` from `@deepseek-ai/dsh-util-workspace-path` from the entry's absolute path and the tree's root, as [the navigator](#the-navigator) describes. While no registered tab type can open that address, for example without `ui-sidebar-documentpreview`, the row is shown greyed and not clickable with a line saying so, and it becomes clickable as soon as a type that opens it registers. | | `other` | Shown greyed and not clickable, so the directory is reported whole. | -A level cut by the endpoint's entry cap ends with a marker; an empty level says so; a level that failed shows one line per code — `workspace-file/not-found`, `outside-workspace`, `not-directory` — and the transport's own message otherwise. Reload refreshes the root and expanded levels in place, retaining displayed entries during reads instead of resetting the whole tree; collapsed levels are fetched again when they next open. A session without a working directory shows a single line instead of a tree. +A level cut by the endpoint's entry cap ends with a marker; an empty level says so, and a level whose every entry is hidden says that its hidden entries are not shown; a level that failed shows one line per code — `workspace-file/not-found`, `outside-workspace`, `not-directory` — and the transport's own message otherwise. Reload refreshes the root and expanded levels in place, retaining displayed entries during reads instead of resetting the whole tree; collapsed levels are fetched again when they next open. A session without a working directory shows a single line instead of a tree. -State lives outside the drawing, keyed by the pane id that `useTabInfo().panel` reports. The type's own store holds, per pane, the navigator's `open` choice and `width`, and its `tree` once first shown: `root`, `levels` (loading / ready / failed per absolute path, a ready level marked `refreshing` while it is listed again), `expanded`, and `autoRefresh`. Every file tab of a pane reads the same record, so switching, opening, or closing tabs redraws the navigator with its levels, expansion, width, and scroll intact; a tab switch lists nothing again. Hiding the tree, or showing only tabs without it, closes its directory watches; showing it again lists the root and the expanded directories again in place while their kept rows stay drawn. A tree rooted at a directory other than the Session's current working directory is replaced, and its scroll position and revealed file are reset. A pane keeps its tree while it shows the navigator or holds an open tab that last drew the navigator there: a file tab moved to another pane shows that pane's tree, a tab replaced in place, as a picked file replaces a preview, keeps it, and floating or docking a tab never ends it by itself. Once the last such tab closes or draws the navigator elsewhere, the pane's tree is forgotten. The page and every preview's navigator share one face per Session. +State lives outside the drawing, keyed by the pane id that `useTabInfo().panel` reports. The type's own store holds, per pane, the navigator's `open` choice and `width`, and its `tree` once first shown: `root`, `levels` (loading / ready / failed per absolute path, a ready level marked `refreshing` while it is listed again), `expanded`, and `autoRefresh`; its `query` holds the search field's text, and while that text is not blank `search` holds whether a search is pending and the last settled result: its matches as a tree, or the failure. The search results keep a scroll offset of their own. Every file tab of a pane reads the same record, so switching, opening, or closing tabs redraws the navigator with its levels, expansion, width, and scroll intact; a tab switch lists nothing again. Hiding the tree, or showing only tabs without it, closes its directory watches; showing it again lists the root and the expanded directories again in place while their kept rows stay drawn. A tree rooted at a directory other than the Session's current working directory is replaced, and its scroll position and revealed file are reset. A pane keeps its tree while it shows the navigator or holds an open tab that last drew the navigator there: a file tab moved to another pane shows that pane's tree, a tab replaced in place, as a picked file replaces a preview, keeps it, and floating or docking a tab never ends it by itself. Once the last such tab closes or draws the navigator elsewhere, the pane's tree is forgotten. The page and every preview's navigator share one face per Session. Each open `DirectoryNode` owns its target watch while the tree is drawn; collapse closes that node and its hidden descendants. Expansion changes during ancestor restoration update the store and pending nodes, so restored descendants follow the latest expansion preferences. Automatic refresh defaults to enabled; its separate toggle is hidden while state, labels, styles, and toggle logic remain. Changes received during a directory read or its completion remain pending for another refresh. File rows expose the shared [context menu](../ui-context-menu/README.md) without invoking ordinary click navigation. Directory rows and the root path use the `directory` target for native reveal and path copying without expanding the tree. + +## Search + +The files page starts with its search bar collapsed. The header's magnifier, between reload and the directory opener, expands the bar and focuses its field; pressing it again hides only the bar, retaining the query, results, and any running search. The pane keeps this display choice across tab switches and remounts, without persisting it. Reopening the bar does not search again. Beside a preview the bar stays shown. From left to right the bar holds the magnifier, which opens the search settings, the search field, the eye, which shows or hides hidden entries, and, while the field holds text, the clear control. The field's text is kept per pane in the type's store and is not persisted; ordinary tab switches or hiding the navigator retain it and the workspace preferences. + +Text with more than whitespace calls the face's `SearchWorkspace` at once with the Session, the trimmed query, the enabled rules' paths, whether hidden entries may match, and whether ignore files are respected, and calls it again whenever the workspace's preferences change. The plugin installs `createSearch(ctx.remote)`, which calls `remote.workspaceFiles.search` on the `@deepseek-ai/dsh-api-workspace-files` namespace; the Host walks the whole workspace, directories the tree never opened included, and applies the query and the preferences: a query without `/` matches names and one with `/` matches workspace-relative paths, both ignoring case; a rule without `/` excludes every file or directory of that name, a rule with `/` that one path, and an excluded, hidden, or ignored directory is not entered. Each pane runs one search at a time: a new query or a preference change aborts the running search and drops its answer when it arrives, and clearing the text or forgetting the pane aborts it too. While a search runs, a spinner follows the count line and the results area is marked busy; the last results stay drawn until the new answer replaces them, and before the pane's first answer the area stays empty. The tree's scroll container then draws the matches as a tree pruned to them: every directory level stays, all start expanded, each name highlights where the query occurs inside it, ignoring case, and a line above reports the number of results. The results keep their own expansion and scroll offset, and new results start at their top, so clearing the text draws the tree again with its expansion, scroll, and current file as they were. The line is a polite live region that stays mounted, empty and without height while the field is blank, so a screen reader announces each new result. A matched directory without matched descendants draws no empty-directory line. An empty result says so; when a filter was on, an information button beside the line opens a tooltip, on hover after a short delay or pinned by a click, that names which of the three filters left entries out: hidden entries, excluded files and directories, and files and directories that ignore files such as `.gitignore` ignore, in whichever combination applies. Below any result, one line says when more entries matched than the Host returns, so only the first ones are drawn and the query should be narrowed, and another says when the result may be incomplete, because the search passed its file limit or a directory could not be read. A search the Host could not run draws why, with the classified failures worded as the tree words them, and a Retry control in the results' place, never an empty result. Starting that retry, a new query, or a preference change drops a drawn failure instead of keeping it beside the spinner. Reload, by its control or the page's refresh shortcut, also runs the pane's search again while the field holds text, since the results are a snapshot of one search. + +The eye starts closed. Closed, the tree leaves out every entry whose name starts with `.`, and the search is asked to leave them out; open, both show them. It reports its state through `aria-pressed` under the fixed name "Show hidden entries". + +The settings panel floats over the navigator below the search bar and lists the excluded files and directories, newest first: each rule has a checkbox that turns it on or off, its path, and a remove control. A rule without `/` names every file or directory of that name at any depth, and a rule with `/` names one workspace-relative path; an excluded directory takes its contents with it. The field that adds a rule stays above the list, which alone scrolls; Enter adds the typed name or path at the top, or names why it is refused below the field. The default list holds version-control, package-manager, and build output directories (`.git`, `.hg`, `.next`, `.pnpm-store`, `.svn`, `.turbo`, `.yarn`, `build`, `coverage`, `dist`, `node_modules`), then the metadata macOS and Windows write (`.DS_Store`, `.Spotlight-V100`, `.Trashes`, `.fseventsd`, `Thumbs.db`, `desktop.ini`, `$RECYCLE.BIN`, `System Volume Information`). The header ends with the restore control, shown while the list differs from the default list in any way, order included, which replaces the list with the default list, and the close control. Above the list, the "Respect ignore files (.gitignore, etc.)" checkbox, checked by default, leaves out entries that ripgrep's ignore rules ignore: `.gitignore` files inside a git repository, including those above the workspace root, `.ignore` files, and the global Git excludes; outside a git repository `.gitignore` does not apply; like the eye, it is saved as soon as it changes. Rule edits stay in the panel until it closes, by the magnifier, by its close control, by Escape, or by keyboard focus leaving it, as a press outside it does; closing saves them. Exclusion rules narrow only the search, never the tree. + +The rules, the eye, and the `.gitignore` choice are kept per workspace root, the Session's working directory with trailing separators removed except the one a filesystem root needs, so every Session and pane rooted there shares them and other roots do not. They live in browser storage under `dsh.sidebar-files.workspace-search.v1`, one entry per root the reader changed, holding only the fields that differ from the defaults, so a later build's default list reaches a root whose rules the reader left alone; a root changed back to the defaults loses its entry, and a missing or malformed field reads as its default. A change while a pane's search text is not blank searches again at once. + +↓ in the search field moves keyboard focus to the first row, ↑ and ↓ move between rows of the tree or the results, and ↑ on the first row returns to the field while the bar is shown; Enter on a row acts as a click does. Escape closes the settings panel first, then clears the search text even while the bar is collapsed, and only then reaches the overlaying navigator's close; clearing a hidden query keeps focus in the tree. On an existing docked files page or beside a docked preview, `workspace.files` shows the search field and gives it keyboard focus; other targets follow the [command's page-opening behavior](#what-it-registers). + ## Reusable tree Factory To draw workspace listings, changed files, or local diffs, declare `const TREE_OPTIONS = { slots: { accessory: ModuleLevelComponent }, fallback: null }` at module scope, then call `renderFactorySlot('sidebar.files.tree', input, TREE_OPTIONS)`. Keep the options and its `slots` object stable; recreating the local selection makes the whole tree redraw on parent renders. The root-scoped Factory is available only while the files plugin is loaded; without it, `renderFactorySlot` renders the supplied `fallback`, or nothing when omitted. Import declarations and `FileTreeInput`, `TreeEntry`, `TreeEntryMeta`, `TreeEntryKind`, and `TreeDirectoryState` type-only from `@deepseek-ai/dsh-client-ui-sidebar-files/client`; no component value is exported. -`FileTreeInput` carries `root`, flat `entries`, `expanded`, `onToggle(entry, expanded)`, and `onOpen(entry)`. Optional `directories` supplies loading, localized failure, and truncation states by key; `current` and `currentRef` mark and expose the current file button. `canOpen(entry)` can refuse a file without disabling its accessory. `rowTriggerProps(entry, kind)` supplies context menu handlers for directory rows and openable file rows. The Factory owns loading, empty, truncated, and unavailable copy through the files locale; callers own data access, expansion, opening, ancestor reveal, and scrolling. +`FileTreeInput` carries `root`, flat `entries`, `expanded`, `onToggle(entry, expanded)`, and `onOpen(entry)`. Optional `directories` supplies loading, localized failure, and truncation states by key, and through `omitted` what a directory without drawn entries says: `hidden` says that its hidden entries are not shown, and `unmatched`, for a selection such as search matches, says nothing. Optional `highlight` marks each occurrence of its text inside a name, ignoring case; `current` and `currentRef` mark and expose the current file button. `canOpen(entry)` can refuse a file without disabling its accessory. `rowTriggerProps(entry, kind)` supplies context menu handlers for directory rows and openable file rows. The Factory owns loading, empty, truncated, and unavailable copy through the files locale; callers own data access, expansion, opening, ancestor reveal, and scrolling. A `TreeEntry` is `{ path, name, meta?: { kind?, hidden?, size? } }`. Only `/` separates levels; the parent is the prefix before the last `/`, or `root` when there is none. Names remain caller-supplied; repeated paths keep the first entry. Root-key entries are ignored, including the empty root. Missing intermediate directories are added once, with explicit entries taking precedence. An omitted kind means directory when entries lie below that path, otherwise file. Hidden rows use subdued ink without filtering; size is not drawn. Only visible levels sort, directories first and then by natural case-insensitive name order; each level keeps its sorting cache until its names or directory kinds change. @@ -89,12 +105,17 @@ None, as this package draws a workspace file tree in the browser and registers n #### KV Cache effect -None; directory listings travel over the Remote and assemble no model request. +None; directory listings and searches travel over the Remote and assemble no model request. ## Known Limitations and Deferred Work -- **Listing only.** No search, artifact filter, drag-and-drop, or rename. +- **Listing only.** No content search, artifact filter, drag-and-drop, or rename. +- **A hidden current file is not located while hidden entries are hidden.** The tree leaves it out, so its row cannot be marked or scrolled into view until the eye is opened. +- **Windows hides more in the search than in the tree.** The tree treats only names starting with `.` as hidden, while the Host's search on Windows also leaves out entries with the hidden file attribute, so such an entry is drawn in the tree but not found while the eye is closed. +- **A query with `/` highlights nothing across names.** Each name is highlighted on its own, so a query that spans a `/` marks no row. +- **Names with glob characters cannot be excluded.** A rule may not contain `* ? [ ] { } !`, so a literal path such as Next.js `app/[slug]` cannot be named. +- **Preferences do not follow other browser tabs.** Each tab reads browser storage once when the plugin loads and writes the preferences of every root back as one value, so a tab that writes overwrites the changes other tabs made since it loaded to any workspace's preferences, until it reloads. - **One root.** The tree is rooted at the session's working directory; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. diff --git a/packages/client/ui-sidebar-files/README.zh.md b/packages/client/ui-sidebar-files/README.zh.md index 9083fc8045..5c5e776ad2 100644 --- a/packages/client/ui-sidebar-files/README.zh.md +++ b/packages/client/ui-sidebar-files/README.zh.md @@ -9,13 +9,14 @@ kind: "package-reference" ## 概述 -在预览文件的同时浏览 Session 的工作区目录树。每个分栏(停靠或浮动)保留一棵树,分栏内的每个文件 tab 都显示它:切换、打开或关闭文件时保留其宽度、展开状态与滚动位置,并标出当前文件。预览旁的目录树在该预览的位置打开文件;`files` 页则在右侧 Sidebar 默认落位的新 tab 中打开文件。根目录与已展开目录通过直接子项监听自动刷新,手动重新读取仍可用。`files` 页从引导页进入,不认领资源地址。 +在预览文件的同时浏览 Session 的工作区目录树。每个分栏保留一棵树,分栏内的每个文件 tab 都显示它,并保留其宽度、展开状态与滚动位置,标出当前文件。搜索栏经 Host 搜索整个工作区。预览旁的目录树在该预览的位置打开文件;`files` 页则在右侧 Sidebar 默认落位的新 tab 中打开文件。根目录与已展开目录通过直接子项监听或重新读取刷新。`files` 页从引导页进入,不认领资源地址。 ## 目录 - [注册了什么](#what-it-registers) - [导航栏](#the-navigator) - [树](#the-tree) +- [搜索](#search) - [复用目录树 Factory](#tree-factory) - [模型体验](#model-experience) - [已知限制与暂缓事项](#known-limitations-and-deferred-work) @@ -26,13 +27,13 @@ kind: "package-reference" ## 注册了什么 -命令 `workspace.files` 在焦点分栏内显示画在停靠 tab 内容旁的导航栏,并把键盘焦点移到目录树,保留该 tab;从聊天区触发时使用当前会话的活动停靠分栏。其他情况下(文件页本身、不带导航栏的 tab、没有工作目录的会话、浮动 tab)打开或聚焦文件页,文件页的目录树始终显示。文件页替换开始页,同一分栏内重复打开仍保留一个文件页。桌面默认键为 Mod+P。开始页入口显示有效快捷键;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 默认不绑定此命令。 +命令 `workspace.files` 在焦点分栏内显示停靠预览旁的导航栏,或展开已有停靠文件页的搜索栏,并把键盘焦点移到其搜索框,保留该 tab;从聊天区触发时使用当前会话的活动停靠分栏。其他情况下(不带导航栏的 tab、没有工作目录的会话、浮动 tab)打开或聚焦文件页,文件页的目录树始终显示。文件页替换开始页,同一分栏内重复打开仍保留一个文件页。桌面默认键为 Mod+P。开始页入口显示有效快捷键;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 默认不绑定此命令。 - **类型**:`ctx.sidebarRightTabs.register(...)`,kind 为 `files`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-files`,档位 `builtin`,没有 patterns,另有一个打开该类型的引导页入口(order 10,标题与描述取自 `sidebarFiles` 命名空间,图标为黄色文件夹)。 -- **文件页正文**:以该 id 为键的 `sidebar.right.pane.tab` slot。其标题行横跨页面,通过共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 显示根路径,目录使用弱化颜色,最后一段使用主色;路径过长时保留尾部字符并在左侧渐隐,悬停显示完整路径。末端依次是目录树的重新读取控件、由文件页注册声明的 Session 作用域 `sidebar.right.tab.files.actions` 列表(通过 `absolutePath` 传入当前显示的根目录),顺序与预览标题行末端的重新读取与文件操作一致;[`ui-open-in-app`](../ui-open-in-app/README.zh.md) 在此提供工作区目录打开按钮。标题行下方由该分栏的导航栏铺满整页,停靠与浮动时都一样,这里没有开关。 +- **文件页正文**:以该 id 为键的 `sidebar.right.pane.tab` slot。其标题行横跨页面,通过共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 显示根路径,目录使用弱化颜色,最后一段使用主色;路径过长时保留尾部字符并在左侧渐隐,悬停显示完整路径。目录树的重新读取控件和搜索栏开关位于由文件页注册声明的 Session 作用域 `sidebar.right.tab.files.actions` 列表之前(通过 `absolutePath` 传入当前显示的根目录);[`ui-open-in-app`](../ui-open-in-app/README.zh.md) 在此提供工作区目录打开按钮。标题行下方由该分栏的导航栏铺满整页,停靠与浮动时都一样,这里没有导航栏开关。 - **各行**:root 作用域的 Component Factory `sidebar.files.tree`,接收调用方的条目和局部 `accessory` slot;见[复用目录树 Factory](#tree-factory)。 -- **导航栏**:Session 作用域的 Component Factory `sidebar.files.navigator`。文件页正文和 [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.zh.md) 直接渲染它,显示在每个预览旁,无论停靠还是浮动。它只绘制目录树及其调整宽度的边缘,没有自己的标题行:预览旁只有预览自己的标题行,目录树的重新读取与目录操作留在 `files` 页上。 -- **开关**:Session 作用域的 Factory `sidebar.files.navigator.toggle`,在预览头部末端直接渲染,传入 `useTabInfo`。两个 Factory 共用文件页的 store handle 和 inject face,每个分栏保留一份开关状态;文件页正文没有开关。 +- **导航栏**:Session 作用域的 Component Factory `sidebar.files.navigator`。文件页正文和 [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.zh.md) 直接渲染它,显示在每个预览旁,无论停靠还是浮动。它绘制[搜索栏](#search)、目录树及其调整宽度的边缘,没有自己的标题行:预览旁只有预览自己的标题行,目录树的重新读取与目录操作留在 `files` 页上。 +- **开关**:Session 作用域的 Factory `sidebar.files.navigator.toggle`,在预览头部末端直接渲染,传入 `useTabInfo`。两个 Factory 共用文件页的 store handle 和 inject face,每个分栏保留一份开关状态;文件页正文没有导航栏开关。 - **标签页标题**:以该 id 为键的 `sidebar.right.pane.tab.title` slot:类型标签前的一枚 16px 共享 `FileTypeIcon` 文件夹图标。树本身的行不画这枚图标。 [注册入口](src/client/index.ts) 在共享 [files face](src/client/face.ts) 与[分栏 store](src/client/store.ts) 上组装文件页、导航栏、开关和目录树 Factory。 @@ -40,9 +41,9 @@ kind: "package-reference" ## 导航栏 -用 `FileNavigatorInput` 渲染 `sidebar.files.navigator`:`{ useTabInfo, page, onOpen }`。必填的 `onOpen: (address: string) => void` 回调由容纳它的插件提供;导航栏构造文件地址,不决定落位。`page` 只控制呈现:`true` 时始终铺满文件页,`false` 时遵循预览所在分栏的偏好与可用宽度。 +用 `FileNavigatorInput` 渲染 `sidebar.files.navigator`:`{ useTabInfo, page, onOpen }`。必填的 `onOpen: (address: string) => void` 回调由容纳它的插件提供;导航栏构造文件地址,不决定落位。`page` 只控制呈现:`true` 时始终铺满文件页,`false` 时遵循预览所在分栏的偏好与可用宽度。Factory 要作为它与正文共用的那一行的直接子元素渲染,并给该行加上 `data-files-navigator-row`:铺满整行的布局只在带这个属性的行里隐藏其他子元素,宿主不加时,被盖住的正文仍可用键盘访问。 -导航栏画在横跨分栏的预览标题行下方,位于它与正文共用的那一行的右侧。在预览旁,是否显示由其分栏的记录决定:分栏默认隐藏,这一选择对分栏内的每个文件 tab 都有效,直到开关、Escape、工作区命令,或导航到被目录树遮住的预览改变它。自身没有记录的分栏(例如 tab 拖出后所在的浮窗)从隐藏、默认宽度开始。点击目录树以外的地方不会隐藏它;在另一分栏打开内容也不会隐藏它。在文件页上,目录树铺满标题行下方的整页,停靠与浮动时都一样,不显示分隔条,且始终显示:文件页不画开关,Escape 也不关闭它。文件页打开的文件沿用落定分栏自己的选择,尚未做过选择的分栏为隐藏。 +导航栏画在横跨分栏的预览标题行下方,位于它与正文共用的那一行的右侧。在预览旁,是否显示由其分栏的记录决定:分栏默认隐藏,这一选择对分栏内的每个文件 tab 都有效,直到开关、Escape、工作区命令,或导航到被目录树遮住的预览改变它。自身没有记录的分栏(例如 tab 拖出后所在的浮窗)从隐藏、默认宽度开始。点击目录树以外的地方不会隐藏它;在另一分栏打开内容也不会隐藏它。在文件页上,目录树铺满标题行下方的整页,停靠与浮动时都一样,不显示分隔条,且始终显示:文件页不画导航栏开关,Escape 也不关闭它。文件页打开的文件沿用落定分栏自己的选择,尚未做过选择的分栏为隐藏。 其宽度是分栏的偏好,在读者用主键拖动左缘分隔条,或用方向键、Home(最窄)、End(最宽)调整之前为 260px,并限制在这一行内:行宽允许时至少 180px;与正文并排时至多为行宽减去 336px,悬浮时至多为行宽减去 120px。在预览旁、视口至少 768px 时,face 测得的行宽决定三种布局之一。行宽至少 560px 时,导航栏是正文旁的浮起面板,距行的上、右、下边缘各 8px,与正文相隔 8px;正文让出面板及其外边距的宽度而变窄,但至少保留 320px。行宽在 400px 到 560px 之间时,同样的面板悬浮在正文右侧之上,因此正文保持完整宽度,面板未覆盖的部分仍可滚动、可交互;正文的滚动条和渲染器的吸顶工具栏在面板下方的部分会被它遮住。两种面板都带圆角,使用第一级抬高背景层,使用共享的浮起阴影,发丝描边在深色模式下改为浅色。560px 这一界限只取决于行宽,因此调整目录树宽度不会让它在两种布局之间切换。在窄于 400px 的行中,或窄于 768px、右侧 Sidebar 以全屏呈现面板的视口中,导航栏铺满标题行下方的整行,不显示分隔条,导航到该预览后会隐藏目录树,让文件显示出来。铺满时,被覆盖的正文及其内嵌框架会隐藏,不能通过键盘进入。若行宽或视口进入此布局时正文持有焦点(包括目录树首次绘制时),焦点移到目录树内,不改变分栏的开关选择。浏览器可能在新宽度报告之前就让被隐藏的正文失焦;除非读者在报告之前移动了键盘焦点或指针,或窗口失去焦点,这一焦点同样移到目录树内。停靠与浮动分栏遵循相同规则;目录树开启时,在每种布局下浮窗的缩放手柄都仍可操作。在预览旁,从这一行内的正文或目录树传到页面 document 的不带修饰键的 Escape,在任何行宽下都会关闭导航栏,并把键盘焦点移到开关上;内嵌框架的 document 持有焦点时,按键不会冒泡到页面 document,因此导航栏保持打开。Escape 在 document 上接收,晚于这一行自己的处理器,因此行内处理器若阻止了默认行为,这次按键就留给它。 @@ -55,7 +56,7 @@ kind: "package-reference" ## 树 -根是会话的工作目录,读自 `useSessions().byId[sessionId].cwd`。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。dotfiles 与其他条目一样显示。 +根是会话的工作目录,读自 `useSessions().byId[sessionId].cwd`。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。名称以 `.` 开头的条目,在读者[显示隐藏条目](#search)之前不显示。 | 条目类型 | 行 | |---|---| @@ -63,20 +64,35 @@ kind: "package-reference" | `file` | 按[导航栏](#the-navigator)所述打开 `dsh-resource://file/session//`,地址由 `@deepseek-ai/dsh-util-workspace-path` 的 `fileAddressFor` 从条目的绝对路径与树的根生成。没有已注册的 tab 类型能打开该地址时(例如未启用 `ui-sidebar-documentpreview`),该行灰显、不可点击并说明原因;一旦有能打开它的类型注册,就变为可点击。 | | `other` | 灰显且不可点击,从而完整呈现目录内容。 | -被端点条目上限截断的层以一条标记收尾;空层如实说明;失败的层按错误码各显示一行(`workspace-file/not-found`、`outside-workspace`、`not-directory`),其他情况显示传输层自己的消息。重新读取就地刷新根与展开中的层,读取期间保留显示条目,不重置整棵树;折叠的层在下次打开时重新拉取。没有工作目录的会话只显示一行说明,而不是树。 +被端点条目上限截断的层以一条标记收尾;空层如实说明,所有条目都是隐藏条目的层说明隐藏项未显示;失败的层按错误码各显示一行(`workspace-file/not-found`、`outside-workspace`、`not-directory`),其他情况显示传输层自己的消息。重新读取就地刷新根与展开中的层,读取期间保留显示条目,不重置整棵树;折叠的层在下次打开时重新拉取。没有工作目录的会话只显示一行说明,而不是树。 -状态保存在绘制之外,以 `useTabInfo().panel` 报告的分栏 id 为键。类型自己的存储按分栏保存导航栏的 `open` 选择与 `width`,以及首次显示后的 `tree`:`root`、`levels`(每个绝对路径的 loading / ready / failed,ready 层重新列出期间标记 `refreshing`)、`expanded` 与 `autoRefresh`。分栏内的每个文件 tab 读取同一份记录,因此切换、打开或关闭 tab 时导航栏重新绘制,已加载的层、展开状态、宽度与滚动位置保持不变;切换 tab 不会重新列目录。隐藏目录树,或只显示不带目录树的 tab,会关闭其目录监听;再次显示时就地重新列出根目录与已展开的目录,期间保留的行照常显示。根目录不是 Session 当前工作目录的树会被替换,其滚动位置与已定位文件随之重置。分栏在显示导航栏、或仍有打开的 tab 最近一次在该分栏绘制导航栏时保留其目录树:移到另一分栏的文件 tab 显示那个分栏的目录树;原位替换的 tab(如选中的文件替换预览)保留它;浮动或停靠 tab 本身从不终结它。最后一个这样的 tab 关闭或在别处绘制导航栏后,分栏的目录树即被忘掉。文件页与每个预览的导航栏在同一 Session 中共用一个 face。 +状态保存在绘制之外,以 `useTabInfo().panel` 报告的分栏 id 为键。类型自己的存储按分栏保存导航栏的 `open` 选择与 `width`,以及首次显示后的 `tree`:`root`、`levels`(每个绝对路径的 loading / ready / failed,ready 层重新列出期间标记 `refreshing`)、`expanded` 与 `autoRefresh`;其 `query` 保存搜索框的文字;该文字非空时,`search` 保存是否有搜索正在进行,以及上一次已结束的结果:匹配项构成的树,或失败原因。搜索结果有自己的滚动偏移。分栏内的每个文件 tab 读取同一份记录,因此切换、打开或关闭 tab 时导航栏重新绘制,已加载的层、展开状态、宽度与滚动位置保持不变;切换 tab 不会重新列目录。隐藏目录树,或只显示不带目录树的 tab,会关闭其目录监听;再次显示时就地重新列出根目录与已展开的目录,期间保留的行照常显示。根目录不是 Session 当前工作目录的树会被替换,其滚动位置与已定位文件随之重置。分栏在显示导航栏、或仍有打开的 tab 最近一次在该分栏绘制导航栏时保留其目录树:移到另一分栏的文件 tab 显示那个分栏的目录树;原位替换的 tab(如选中的文件替换预览)保留它;浮动或停靠 tab 本身从不终结它。最后一个这样的 tab 关闭或在别处绘制导航栏后,分栏的目录树即被忘掉。文件页与每个预览的导航栏在同一 Session 中共用一个 face。 每个打开的 `DirectoryNode` 在目录树绘制期间持有自己的目标监听;折叠关闭该节点及其不可见后代。祖先恢复期间的展开状态变化会更新存储和待恢复节点,后代恢复时遵循最新展开偏好。自动刷新默认开启;独立开关暂时隐藏,状态、文案、样式与切换逻辑保留。目录读取期间或收尾时收到的变化仍会留待下一次刷新。 文件行提供共享[右键菜单](../ui-context-menu/README.zh.md),不会同时触发普通点击导航。文件夹行和根路径使用 `directory` 操作对象,提供本机显示位置和复制路径操作,不会展开目录。 + +## 搜索 + +文件页的搜索栏默认收起。标题行中位于重新读取与目录打开按钮之间的放大镜展开搜索栏并聚焦输入框;再次点击只隐藏搜索栏,保留关键词、结果和进行中的搜索。分栏在切换 tab 和重新挂载时保留这一显示选择,不会持久化。重新展开不会再次搜索。预览旁的搜索栏保持显示。搜索栏内从左到右依次是打开搜索设置的放大镜、搜索框、显示或隐藏隐藏条目的眼睛,以及搜索框有文字时出现的清空按钮。搜索框的文字按分栏保存在类型的存储中,不会持久化;正常切换 tab 或隐藏导航栏会保留它和工作区偏好。 + +文字除空白外还有内容时,face 立即调用 `SearchWorkspace`,传入 Session、去掉首尾空白的查询、已启用规则的路径、隐藏条目能否匹配,以及是否尊重忽略文件;工作区偏好变化时再次调用。插件装入 `createSearch(ctx.remote)`,它调用 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.search`;Host 遍历整个工作区,包括目录树从未展开过的目录,并应用查询与偏好:不含 `/` 的查询匹配名称,含 `/` 的查询匹配工作区相对路径,都不区分大小写;不含 `/` 的规则排除所有同名文件或目录,含 `/` 的规则排除那一个路径,被排除、隐藏或被忽略的目录不会进入。每个分栏同一时间只运行一次搜索:新的查询或偏好变化会中止正在运行的搜索,并在其答复到达时丢弃它;清空文字或忘掉该分栏也会中止它。搜索运行期间,结果数这一行后面显示一个转圈图标,结果区标记为忙碌;上一次的结果保持显示,直到新答复替换它们,分栏的第一次答复到达之前结果区保持为空。随后目录树的滚动容器改为绘制剪枝到匹配项的树:保留每一层目录,全部默认展开,每个名称高亮其中出现查询的位置(不区分大小写),上方一行报告结果数。搜索结果有自己的展开状态与滚动偏移,新结果从顶部开始,因此清空文字后目录树按原来的展开状态、滚动位置与当前文件重新绘制。这一行是常驻的 polite live region,搜索框为空时内容为空且不占高度,因此读屏软件会播报每次的新结果。匹配但没有匹配后代的目录不显示空目录提示。结果为空时如实说明;开启了过滤时,这一行旁有一个信息按钮,悬停片刻或点击固定后弹出提示,说明三种过滤中哪些略去了条目:隐藏条目、排除的文件和目录、被忽略文件(如 `.gitignore`)忽略的文件和目录,按实际开启的组合给出。无论有无结果,匹配数超过 Host 返回的上限时,结果下方有一行说明只显示了前面的结果、应缩小查询范围;结果可能不完整时(文件数超过搜索上限,或某个目录读取失败),另有一行说明。Host 无法执行的搜索在结果区显示原因和「重试」按钮,其中已分类的失败按目录树同一套文案给出,从不显示为空结果。点「重试」、输入新查询或改动偏好时,已显示的失败会被清掉,不会和转圈并存。搜索框有文字时,重新读取(控件或页面刷新快捷键)也会重新执行该分栏的搜索,因为结果只是某一次搜索的快照。 + +眼睛默认闭上。闭眼时,目录树不显示名称以 `.` 开头的条目,搜索也被要求略过它们;睁眼时两者都显示。它通过 `aria-pressed` 报告状态,名称固定为「显示隐藏项」(Show hidden entries)。 + +设置面板浮在导航栏中搜索栏的下方,列出排除的文件和目录,最新的在最前:每条规则有开关它的复选框、路径和删除按钮。不含 `/` 的规则指任意深度上所有同名的文件或目录,含 `/` 的规则指一个相对于工作区的路径;排除一个目录时其内容也一并排除。添加规则的输入框固定在列表上方,只有列表本身滚动;Enter 把输入的名称或路径添加到最上方,或在输入框下方说明拒绝的原因。默认列表先是版本控制、包管理器和构建输出目录(`.git`、`.hg`、`.next`、`.pnpm-store`、`.svn`、`.turbo`、`.yarn`、`build`、`coverage`、`dist`、`node_modules`),然后是 macOS 和 Windows 写入的元数据(`.DS_Store`、`.Spotlight-V100`、`.Trashes`、`.fseventsd`、`Thumbs.db`、`desktop.ini`、`$RECYCLE.BIN`、`System Volume Information`)。标题行末端是还原按钮和关闭按钮;列表与默认列表有任何不同(包括顺序不同)时显示还原按钮,点击后把列表重置为默认列表。列表上方的「尊重忽略文件(.gitignore 等)」(Respect ignore files (.gitignore, etc.))复选框默认勾选,此时略过 ripgrep 忽略规则忽略的条目:git 仓库内的 `.gitignore`(包括工作区根以上的)、`.ignore` 文件和全局 Git excludes;不在 git 仓库内时 `.gitignore` 不生效;它和眼睛一样,一改变就保存。规则的编辑留在面板内,直到面板通过放大镜、关闭按钮、Escape 或键盘焦点离开它(在面板外按下也是如此)而关闭;关闭即保存。排除规则只缩小搜索范围,从不影响目录树。 + +规则、眼睛与 `.gitignore` 选择按工作区根保存,即去掉尾随分隔符的 Session 工作目录(文件系统根需要的那一个除外),因此根在同一目录的每个 Session 与分栏共享它们,其他根互不影响。它们保存在浏览器存储的 `dsh.sidebar-files.workspace-search.v1` 下,读者改过的每个根各占一项,只保存与默认值不同的字段,因此读者没改过规则的根能用上后续版本的默认列表;改回默认值的根删除其条目,缺失或格式不对的字段按默认值读取。分栏的搜索文字非空时发生的变化会立即重新搜索。 + +在搜索框中按 ↓ 把键盘焦点移到第一行,↑ 与 ↓ 在目录树或搜索结果的行之间移动,搜索栏显示时在第一行按 ↑ 回到搜索框;在行上按 Enter 与单击效果相同。Escape 先关闭设置面板,再清空搜索文字(搜索栏收起时也一样),之后才交给覆盖式导航栏的关闭行为;清空隐藏的查询时,焦点留在目录树内。在已有停靠文件页或停靠预览旁,`workspace.files` 显示搜索框并把键盘焦点移给它;其他位置遵循[命令的文件页打开行为](#what-it-registers)。 + ## 复用目录树 Factory 要绘制工作区列表、变更文件或本地 diff,在模块级声明 `const TREE_OPTIONS = { slots: { accessory: ModuleLevelComponent }, fallback: null }`,再调用 `renderFactorySlot('sidebar.files.tree', input, TREE_OPTIONS)`。保持 options 及其 `slots` 对象稳定;重新创建局部选择会让整棵树随父组件渲染而重画。该 root 作用域 Factory 仅在 files 插件加载时可用;未加载时,`renderFactorySlot` 绘制传入的 `fallback`,省略时不绘制内容。从 `@deepseek-ai/dsh-client-ui-sidebar-files/client` 仅以类型方式导入声明以及 `FileTreeInput`、`TreeEntry`、`TreeEntryMeta`、`TreeEntryKind`、`TreeDirectoryState`;不导出组件值。 -`FileTreeInput` 携带 `root`、扁平 `entries`、`expanded`、`onToggle(entry, expanded)` 和 `onOpen(entry)`。可选的 `directories` 按键提供加载、本地化失败和截断状态;`current` 与 `currentRef` 标记并提供当前文件按钮。`canOpen(entry)` 可以拒绝打开文件而不禁用其附件。`rowTriggerProps(entry, kind)` 为文件夹行和可打开的文件行提供右键菜单处理器。Factory 通过 files locale 拥有加载、空目录、截断与不可用文案;调用方负责数据访问、展开、打开、祖先定位和滚动。 +`FileTreeInput` 携带 `root`、扁平 `entries`、`expanded`、`onToggle(entry, expanded)` 和 `onOpen(entry)`。可选的 `directories` 按键提供加载、本地化失败和截断状态,并通过 `omitted` 决定没有绘制条目的目录显示什么:`hidden` 说明其隐藏条目未显示,`unmatched` 用于搜索匹配这类选取结果,什么也不显示。可选的 `highlight` 在名称中标出其文字的每次出现,不区分大小写;`current` 与 `currentRef` 标记并提供当前文件按钮。`canOpen(entry)` 可以拒绝打开文件而不禁用其附件。`rowTriggerProps(entry, kind)` 为文件夹行和可打开的文件行提供右键菜单处理器。Factory 通过 files locale 拥有加载、空目录、截断与不可用文案;调用方负责数据访问、展开、打开、祖先定位和滚动。 `TreeEntry` 为 `{ path, name, meta?: { kind?, hidden?, size? } }`。只有 `/` 分隔层级;父级是最后一个 `/` 前的部分,没有 `/` 时为 `root`。名字保持调用方传入的值;重复路径保留首个条目。根键条目被忽略,包括空根。缺少的中间目录只补一次,显式条目优先。省略 kind 时,路径下有条目则为目录,否则为文件。隐藏行用弱化文字颜色显示,不过滤;大小不显示。只有可见层排序,目录优先,再按名字的自然顺序、不区分大小写排列;各层保留排序缓存,直到名字或目录类型变化。 @@ -89,12 +105,17 @@ kind: "package-reference" #### KV Cache 影响 -无;目录列表经 Remote 传输,不会组装模型请求。 +无;目录列表与搜索经 Remote 传输,不会组装模型请求。 ## 已知限制与暂缓事项 -- **只有列目录。**没有搜索、产物过滤、拖拽或重命名。 +- **只有列目录。**没有内容搜索、产物过滤、拖拽或重命名。 +- **隐藏条目不显示时,隐藏的当前文件定位不到。**目录树不显示它,因此在睁开眼睛之前无法标出该行或把它滚动到可见区域。 +- **Windows 上搜索比目录树隐藏得更多。**目录树只把 `.` 开头的名称当作隐藏项,而 Windows 上 Host 的搜索还会略去带隐藏文件属性的条目,因此眼睛关闭时,这类条目在树中可见,却搜索不到。 +- **含 `/` 的查询不会跨名称高亮。**每个名称单独高亮,因此跨越 `/` 的查询不会在任何行上标出。 +- **含通配符的名称无法排除。**规则不能包含 `* ? [ ] { } !`,因此无法写出 Next.js `app/[slug]` 这类字面路径。 +- **偏好不会同步到其他浏览器标签页。**每个标签页只在插件加载时读取一次浏览器存储,并把所有根的偏好作为一个整体写回,因此一个标签页写入时,会覆盖其他标签页在它加载之后对任何工作区偏好所做的修改,直到它重新加载。 - **只有一个根。**树以会话工作目录为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 diff --git a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx index 6ce68e82b2..dac8bb7f88 100644 --- a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx @@ -1,22 +1,31 @@ /** - * One pane's workspace navigator: the tree and the edge that resizes it. The - * `files` page draws it below its header; beside a preview the preview's own - * header is the only one. Everything it shows lives in the store and face, - * keyed by pane, so a remount on a tab switch or replacement draws it + * One pane's workspace navigator: the search bar, the tree, and the edge that + * resizes it. The `files` page draws it below its header; beside a preview the + * preview's own header is the only one. Everything it shows lives in the store + * and face, keyed by pane, so a remount on a tab switch or replacement draws it * unchanged, keyboard focus included when the tree held it. Its layout * follows `PUSH_FROM`, `FILL_BELOW`, and `FULLSCREEN_QUERY`; the package - * README describes its behavior. + * README describes its behavior, search included. */ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode } from 'react' +import type { CSSProperties, KeyboardEvent, ReactNode } from 'react' import clsx from 'clsx' +import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import type { UseSidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { TreeEntry } from './FileTree.tsx' -import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' +import type { FactoryComponentPropsOf, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { + Button, IconCloseOutlineRegular, IconEyeOffOutlineRegular, IconEyeOutlineRegular, IconInfoOutlineRegular, IconSearchOutlineRegular, + StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' import { fileAddressFor } from '@deepseek-ai/dsh-util-workspace-path' import type { FilesInjected } from './face.ts' +import type { SidebarFilesKey } from './locales.ts' +import { SearchSettings } from './SearchSettings.tsx' +import { defaultSearchPreferences, type ExclusionRule, type WorkspaceSearchPreferences } from './search-rules.ts' import { DEFAULT_NAVIGATOR_WIDTH, PUSH_FROM, locateFile, navigatorGeometry, relativeFileOf, type createFilesStore } from './store.ts' -import { parentOf, treeRootOf, workspaceDirectories, workspaceEntries } from './workspace-tree.ts' +import type { FilesSearchResult } from './store.ts' +import { failureLine, parentOf, searchDirectories, treeRootOf, workspaceDirectories, workspaceEntries } from './workspace-tree.ts' import { FILL_BELOW } from './navigator-layout.ts' import css from './FilesBody.module.css' @@ -32,7 +41,11 @@ export interface FileNavigatorInput { declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotFactoryMap { - /** One pane's workspace tree with its width and show/hide state. */ + /** + * One pane's workspace tree with its width and show/hide state. The host renders it as a direct child of + * the content row it shares with the body, and that row carries `data-files-navigator-row`, which the + * filled layout needs to hide the covered body. + */ 'sidebar.files.navigator': { scope: 'session' props: FileNavigatorInput @@ -63,18 +76,105 @@ function navigatorMode(rowWidth: number | undefined): NavigatorMode { return rowWidth >= PUSH_FROM ? 'push' : rowWidth >= FILL_BELOW ? 'overlay' : 'fill' } +/** + * Why an empty result may still hide matches. + * @param result - a settled search with no entries. + * @returns the hint's key, or `undefined` when the search left nothing out. + */ +function emptyHint(result: SearchFilters): SidebarFilesKey | undefined { + const { hiddenLeftOut: hidden, excluded, ignored } = result + if (hidden && excluded) return ignored ? 'search.emptyHint.all' : 'search.emptyHint.both' + if (hidden) return ignored ? 'search.emptyHint.hiddenIgnored' : 'search.emptyHint.hidden' + if (excluded) return ignored ? 'search.emptyHint.excludedIgnored' : 'search.emptyHint.excluded' + return ignored ? 'search.emptyHint.ignored' : undefined +} + +/** + * Move keyboard focus one step along the search field and the drawn rows, + * in document order: ↓ from the field enters the first row, and ↑ on the + * first row returns to the field. A key that composes text in an input method, + * or that something in the navigator already handled, stays where it is. + * @param event - a key pressed in the navigator. + */ +function moveAlongRows(event: KeyboardEvent): void { + if (event.defaultPrevented || event.nativeEvent.isComposing) return + if ((event.key !== 'ArrowDown' && event.key !== 'ArrowUp') || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return + const stops = [...event.currentTarget.querySelectorAll('[data-files-search], [data-files-body] [data-files-path] > div > button')] + const at = stops.findIndex(stop => stop === event.target) + const next = at === -1 ? undefined : stops[at + (event.key === 'ArrowDown' ? 1 : -1)] + if (next === undefined) return + event.preventDefault() + next.focus() +} + +/** Which filters a search applied, and so which of them an empty result may owe its emptiness to. */ +type SearchFilters = { readonly hiddenLeftOut: boolean; readonly excluded: boolean; readonly ignored: boolean } + +/** + * What the results area shows below a search's result tree: that nothing + * matched, with an information button whose tooltip names the filters that + * left entries out, that only the first matches are drawn, and that the + * result may be incomplete. + */ +function SearchNotes({ result, t }: { result: Extract; t: TranslateNS<'sidebarFiles'> }): ReactNode { + const hint = result.count > 0 ? undefined : emptyHint(result) + return ( + <> + {result.count === 0 && ( +

+ {t('search.empty')} + {hint !== undefined && ( + + + + )} +

+ )} + {result.truncated && ( +

{t('search.truncated', { count: String(result.count) })}

+ )} + {result.incomplete &&

{t('search.incomplete')}

} + + ) +} + +/** + * What the results area shows for a search the Host could not run: why, and a control that runs it again. + * @param props.failure - the failed search's Remote failure. + * @param props.onRetry - runs the search again. + * @param props.t - namespace-bound translate. + * @returns the notice. + */ +function SearchFailure({ failure, onRetry, t }: { + readonly failure: RemoteFailure + readonly onRetry: () => void + readonly t: TranslateNS<'sidebarFiles'> +}): ReactNode { + return ( +
+

{t('search.failed', { message: failureLine(t, failure) })}

+ +
+ ) +} + /** * The navigator Factory's component. * @param props - the tab it is drawn for, the pane's store records, the tree's face, and copy. * @returns the navigator, or nothing while hidden or without a workspace. */ export function FileNavigator({ - useTabInfo, page, onOpen, sessionId, useSessions, useStore, actions, useRowWidth, useCanOpen, - attach, placeBeside, hold, toggle, scrolled, bodyDrawn, currentDrawn, navigatorDrawn, t, renderFactorySlot, useContextMenu, + useTabInfo, page, onOpen, sessionId, useSessions, useStore, actions, useRowWidth, useCanOpen, useSearchPreferences, + attach, placeBeside, hold, toggle, scrolled, bodyDrawn, currentDrawn, navigatorDrawn, + setQuery, toggleSearch, retrySearch, setSearchPreferences, searchDrawn, t, renderFactorySlot, useContextMenu, }: FactoryComponentPropsOf<'sidebar.files.navigator'>): ReactNode { const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const paneId = panel.id + // A Session's working directory comes from its header and never changes once + // known, so every search result the pane's store holds is rooted at it. const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) const state = useStore(store => store.byPane[paneId]) const rowWidth = useRowWidth(paneId) @@ -83,17 +183,38 @@ export function FileNavigator({ // Measured by the face; the viewport rule is CSS's, read again when a file opens. const mode = navigatorMode(rowWidth) const tree = state?.tree?.root === cwd ? state?.tree : undefined + // The face resolves every key to a source, so the renderer never reports one unavailable. + /* v8 ignore next -- the fallback only satisfies the keyed hook's optional snapshot type. */ + const preferences: WorkspaceSearchPreferences = useSearchPreferences(cwd ?? '') ?? defaultSearchPreferences() + const { showHidden } = preferences + const query = state?.query ?? '' + const searchBarOpen = !page || state?.searchBarOpen === true + const search = state?.search + const pending = search?.pending === true + const result = search?.result + const found = result?.kind === 'found' ? result : undefined const [dragging, setDragging] = useState(false) + const [draft, setDraft] = useState(undefined) + const settings = draft !== undefined const drag = useRef<{ readonly x: number; readonly width: number } | undefined>(undefined) + const input = useRef(null) + const trigger = useRef(null) // Stable, so each element registers once per drawing rather than on every render. const navigatorRef = useCallback( (element: HTMLElement | null) => { navigatorDrawn(paneId, element, !page) }, [navigatorDrawn, paneId, page], ) + // Also new when the container switches between the tree and the results, so + // the face restores that view's scroll offset once its rows are drawn. + const resultsShown = search !== undefined const bodyRef = useCallback( (body: HTMLDivElement | null) => { bodyDrawn(paneId, tab.contentId, body) }, - [bodyDrawn, paneId, tab.contentId], + [bodyDrawn, paneId, tab.contentId, resultsShown], ) + const inputRef = useCallback((element: HTMLInputElement | null) => { + input.current = element + searchDrawn(paneId, element) + }, [searchDrawn, paneId]) const currentRef = useCallback((row: HTMLElement | null) => { currentDrawn(paneId, row) }, [currentDrawn, paneId]) useEffect(() => attach(paneId, tab.id, tab.signal), [attach, paneId, tab.id, tab.signal]) @@ -109,13 +230,23 @@ export function FileNavigator({ const root = tree?.root const levels = tree?.levels const expanded = tree?.expanded - const entries = useMemo(() => levels === undefined ? undefined : workspaceEntries(levels), [levels]) + const entries = useMemo(() => levels === undefined ? undefined : workspaceEntries(levels, showHidden), [levels, showHidden]) const directories = useMemo( () => root === undefined || levels === undefined || expanded === undefined ? undefined - : workspaceDirectories({ root, levels, expanded }, t), - [root, levels, expanded, t], + : workspaceDirectories({ root, levels, expanded }, t, showHidden), + [root, levels, expanded, t, showHidden], ) + const resultTree = found !== undefined && found.count > 0 ? found.tree : undefined + const resultCurrent = useMemo( + () => resultTree === undefined || relativePath === undefined ? undefined : locateFile(resultTree, relativePath).current, + [resultTree, relativePath], + ) + const resultEntries = useMemo( + () => resultTree === undefined ? undefined : workspaceEntries(resultTree.levels, showHidden), + [resultTree, showHidden], + ) + const resultDirectories = useMemo(() => resultTree === undefined ? undefined : searchDirectories(resultTree), [resultTree]) // Kept between renders, so the tree redraws only when what it shows changes, // not on every measure of the row or render of the host. const view = useMemo(() => { @@ -131,12 +262,27 @@ export function FileNavigator({ : { kind, value: { sessionId, path: entry.path, paneId } }), } }, [tree, paneId, sessionId, toggle, canOpen, onOpen, getTriggerProps]) + // The results keep their own expansion; every other gesture acts as on the tree. + const resultView = useMemo(() => view === undefined || resultTree === undefined ? undefined : { + ...view, + expanded: resultTree.expanded, + onToggle: (entry: TreeEntry) => { toggleSearch(paneId, entry.path) }, + }, [view, resultTree, toggleSearch, paneId]) + const closeSettings = useCallback((rules: readonly ExclusionRule[], refocus: boolean) => { + setDraft(undefined) + if (refocus) trigger.current?.focus() + if (cwd !== undefined && rules !== preferences.rules) setSearchPreferences(cwd, { rules }) + }, [cwd, preferences.rules, setSearchPreferences]) if (cwd === undefined || !open) return null const geometry = navigatorGeometry(rowWidth, state?.width ?? DEFAULT_NAVIGATOR_WIDTH) // The page's tree always fills the page; a preview's follows its row. const shown = page ? undefined : mode const clamp = (next: number): number => Math.min(Math.max(next, geometry.minimum), geometry.maximum) + const clear = (): void => { + setQuery(paneId, cwd, '') + input.current?.focus() + } return ( ) } diff --git a/packages/client/ui-sidebar-files/src/client/FileTree.module.css b/packages/client/ui-sidebar-files/src/client/FileTree.module.css index d7bd27a608..fe7cf766fc 100644 --- a/packages/client/ui-sidebar-files/src/client/FileTree.module.css +++ b/packages/client/ui-sidebar-files/src/client/FileTree.module.css @@ -111,3 +111,9 @@ color: var(--dsw-alias-label-tertiary); font-size: 12px; } + +/* The occurrences of the highlighted text in a name. */ +.match { + color: var(--dsw-alias-state-business-primary); + background: transparent; +} diff --git a/packages/client/ui-sidebar-files/src/client/FileTree.tsx b/packages/client/ui-sidebar-files/src/client/FileTree.tsx index 7a9b129896..30516ba28e 100644 --- a/packages/client/ui-sidebar-files/src/client/FileTree.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileTree.tsx @@ -5,7 +5,8 @@ * path, adds the directories the paths imply, orders every drawn level, and * draws the rows and their icons. It redraws when its * props or the occurrence's local selection change, and orders a drawn level - * again only when the names or directory kinds in that level change. + * again only when the names or directory kinds in that level change. Given a + * query to highlight, it marks each occurrence of the query inside a name. */ import { memo, useMemo } from 'react' import type { ReactNode } from 'react' @@ -14,6 +15,7 @@ import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' import type { ContextMenuTriggerProps } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { FileTypeIcon, classifyFileType, IconFolderCloseRegular, IconFolderOpenRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from './locales.ts' +import { matchRanges } from './search-tree.ts' import css from './FileTree.module.css' /** What a row is: a directory toggles, a file opens, and anything else is listed without either. */ @@ -51,6 +53,13 @@ export interface TreeDirectoryState { readonly failure?: string /** Entries are missing from the listing. */ readonly truncated?: true + /** + * The caller left entries out, which changes what the directory says while + * none is drawn: `hidden` says that its hidden entries are not shown, and + * `unmatched`, for entries that are a selection such as search matches, says + * nothing instead of that it is empty. + */ + readonly omitted?: 'hidden' | 'unmatched' } /** The `sidebar.files.tree` Factory's input: data and callbacks only. */ @@ -70,6 +79,8 @@ export interface FileTreeInput { readonly expanded: readonly string[] /** Listing state by directory key, root included; a directory absent here is listed and complete. */ readonly directories?: Readonly> | undefined + /** Text whose occurrences inside each name are highlighted, ignoring case; nothing is highlighted without it. */ + readonly highlight?: string | undefined /** Key of the file to mark as current, when it is drawn. */ readonly current?: string | undefined /** Receives the current file's main button while drawn. @param row - the button, or `null` once it goes. */ @@ -190,12 +201,27 @@ interface TreeContext { readonly Accessory: ReturnType['useFactorySlot']> } +/** One entry's name, with the occurrences of the text to highlight marked. */ +function Name({ name, highlight }: { name: string; highlight: string | undefined }): ReactNode { + const ranges = highlight === undefined ? [] : matchRanges(name, highlight) + if (ranges.length === 0) return {name} + const parts: ReactNode[] = [] + let at = 0 + for (const [start, end] of ranges) { + if (start > at) parts.push(name.slice(at, start)) + parts.push({name.slice(start, end)}) + at = end + } + if (at < name.length) parts.push(name.slice(at)) + return {parts} +} + /** One entry's row, and its children when it is an expanded directory. */ function Entry({ node, tree }: { node: TreeNode; tree: TreeContext }): ReactNode { const { input, Accessory } = tree const { entry, kind } = node const hidden = entry.meta?.hidden === true && css.hidden - const label = {entry.name} + const label = if (kind === 'directory') { const expanded = tree.expanded.has(entry.path) return ( @@ -260,7 +286,11 @@ function Level({ path, tree }: { path: string; tree: TreeContext }): ReactNode { return ( <> {state?.failure !== undefined &&
  • {state.failure}
  • } - {level.length === 0 && state?.failure === undefined &&
  • {t('empty')}
  • } + {level.length === 0 && state?.failure === undefined && state?.omitted !== 'unmatched' && ( + state?.omitted === 'hidden' + ?
  • {t('emptyHidden')}
  • + :
  • {t('empty')}
  • + )} {order.map(index => level[index]).filter(node => node !== undefined) .map(node => )} {state?.truncated === true &&
  • {t('truncated')}
  • } diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css index 383ecfa47d..315d5afae8 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css @@ -36,6 +36,8 @@ height: 100%; min-width: 0; min-height: 0; + /* The search bar's height, which also places the settings panel below it. */ + --files-search-bar-height: 42px; color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size-secondary, 13px); line-height: 1.5; @@ -72,14 +74,16 @@ border-left: 0; } -/* Covered content stays laid out but cannot receive keyboard focus. */ -:has(> .navigator.fill) > :not(.navigator) { +/* Covered content stays laid out but cannot receive keyboard focus. The rule + names its row through `data-files-navigator-row`: a `:has()` without a + subject makes the browser restyle the whole document after any DOM change. */ +[data-files-navigator-row]:has(> .navigator.fill) > :not(.navigator) { visibility: hidden; } /* navigator-layout `FULLSCREEN_QUERY`: every layout fills the row. */ @media (width < 768px) { - :has(> .navigator:not(.wholePage)) > :not(.navigator) { + [data-files-navigator-row]:has(> .navigator:not(.wholePage)) > :not(.navigator) { visibility: hidden; } @@ -198,6 +202,23 @@ font-size: 12px; } +/* "No matches" with the information button whose tooltip names the filters. */ +.emptyNote { + display: flex; + align-items: center; + gap: 2px; +} + +/* The information button keeps the note's line height. */ +.infoButton { + flex: none; + width: 20px; + height: 20px; + margin-block: -2px; + padding: 0; + color: var(--dsw-alias-label-caption); +} + .status { display: flex; flex-direction: column; @@ -252,3 +273,262 @@ .titleIcon { flex: none; } + +/* The navigator's search bar above the tree: the settings control, the + field, the hidden-entry control, and the clear control in one bordered box, + drawn like the shared `Input` atom. */ +.searchBar { + flex: 0 0 auto; + box-sizing: border-box; + height: var(--files-search-bar-height); + padding: 8px 8px 4px; +} + +.searchField { + display: flex; + gap: 2px; + align-items: center; + box-sizing: border-box; + height: 100%; + padding: 0 2px; + background: var(--dsw-alias-bg-layer-1); + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); +} + +.searchField:focus-within { + border-color: var(--dsw-alias-state-business-primary); +} + +/* The bar's icon controls: the header tool at a size that fits inside the field. */ +.searchTool { + width: 24px; + height: 24px; + padding: 4px; +} + +.searchTool svg { + width: 14px; + height: 14px; +} + +.searchInput { + flex: 1 1 auto; + min-width: 0; + padding: 0 4px; + color: var(--dsw-alias-label-primary); + font: inherit; + background: transparent; + border: none; + outline: none; +} + +.searchInput::placeholder { + color: var(--dsw-alias-label-dimmed); +} + +/* The bar's own clear control replaces the browser's. */ +.searchInput::-webkit-search-cancel-button { + display: none; +} + +/* The results status between the bar and the results: the count, and a spinner while a search is under way. */ +.searchStatus { + display: flex; + flex: 0 0 auto; + gap: 6px; + align-items: center; + min-height: 18px; + margin: 0; + padding: 2px 18px 0; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); +} + +/* One sentence of the results status: the count. */ +.searchStatusLine { + display: block; + min-width: 0; +} + +.searchSpinner { + flex: none; +} + +/* A failed search in the results' place: the reason, and the retry control below it on the note's inset. */ +.searchFailure { + display: flex; + flex-direction: column; + gap: 6px; + align-items: flex-start; + padding-bottom: 6px; +} + +.searchRetry { + margin-left: 10px; +} + +/* The `.gitignore` choice above the add field, at a rule's height. */ +.settingsOption { + border-top: none; +} + +/* The live region stays mounted while the query is blank, without taking room. */ +.searchStatusIdle { + min-height: 0; + padding: 0; +} + +/* The settings panel floats over the tree below the search bar, inside the navigator. */ +.settings { + position: absolute; + top: var(--files-search-bar-height); + right: 8px; + bottom: 8px; + left: 8px; + z-index: 3; + display: flex; + flex-direction: column; + min-height: 0; + padding: 6px 4px 6px 10px; + background: var(--dsw-alias-bg-base); + border-radius: var(--dsw-radius-lg); + outline: none; + box-shadow: var(--dsw-elevation-prominent); +} + +.settingsHeader { + display: flex; + flex: 0 0 auto; + gap: 2px; + align-items: center; +} + +.settingsTitle { + flex: 1 1 auto; + min-width: 0; + font-weight: 500; +} + +.settingsDescription { + flex: 0 0 auto; + margin: 0 0 4px; + padding-right: 6px; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); +} + +/* One rule, and the add field above them at the same height. */ +.rule { + display: flex; + flex: 0 0 auto; + gap: 6px; + align-items: center; + box-sizing: border-box; + min-height: 32px; + margin: 0; + padding: 0 0 0 2px; + border-top: 0.5px solid var(--dsw-alias-border-l3); +} + +.addRule { + padding-right: 6px; +} + +/* The add row's plus glyph rides the tertiary ink, as the tree's folder glyph does. */ +.addRule .icon { + flex: 0 0 auto; + color: var(--dsw-alias-label-tertiary); +} + +/* The add field draws no box of its own, so its row's rule marks where typing goes. */ +.addRule:focus-within { + border-top-color: var(--dsw-alias-state-business-primary); +} + +.ruleInput { + flex: 1 1 auto; + min-width: 0; + padding: 0; + color: var(--dsw-alias-label-primary); + font: inherit; + background: transparent; + border: none; + outline: none; +} + +.ruleInput::placeholder { + color: var(--dsw-alias-label-dimmed); +} + +.settingsError { + flex: 0 0 auto; + margin: 0 0 4px; + color: var(--dsw-alias-state-error-primary); + font: var(--dsw-font-xxs-12); +} + +/* Only the list scrolls; the header and the add field stay put. */ +.rules { + flex: 1 1 auto; + min-height: 0; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; + overscroll-behavior: contain; +} + +.ruleLabel { + display: flex; + flex: 1 1 auto; + gap: 6px; + align-items: center; + min-width: 0; + cursor: pointer; +} + +.ruleCheck { + flex: 0 0 auto; + width: 14px; + height: 14px; + margin: 0 1px; + accent-color: var(--dsw-alias-state-business-primary); +} + +.ruleCheck:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} + +.ruleName { + min-width: 0; + padding: 6px 0; + overflow-wrap: anywhere; +} + +/* A rule the reader turned off stays listed, in the tertiary ink. */ +.ruleOff .ruleName { + color: var(--dsw-alias-label-tertiary); +} + +@media (pointer: coarse) { + .searchTool { + width: 32px; + height: 32px; + } + + .navigator { + --files-search-bar-height: 50px; + } + + .rule { + min-height: 44px; + } + + /* Below 16px, mobile browsers zoom the page when a field takes focus. */ + .searchInput, + .ruleInput { + font-size: 16px; + } +} diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx index b1361cf415..0f6b26d7f6 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx @@ -1,10 +1,9 @@ /** * The `files` page: a file browser with no file chosen yet. * - * Its header spans the page: the workspace root's path, the tree's reload and - * the directory actions, in the order a preview's header ends with its own - * reload and file actions. The pane's navigator fills the page below it and - * stays shown, so the page draws no toggle; picking a file leaves this page as + * Its header spans the page: the workspace root's path, the tree's reload, + * the search-bar toggle, and the directory actions. The pane's navigator fills the page below it and + * stays shown, so the page draws no navigator toggle; picking a file leaves this page as * it is and opens the file where the right Sidebar places it by default * (`FileNavigator`). */ @@ -15,7 +14,7 @@ import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore, } from '@deepseek-ai/dsh-client-ui-slots' import { - IconPauseOutlineRegular, IconPlayOutlineRegular, IconRefreshOutlineRegular, PathLabel, Tooltip, + IconPauseOutlineRegular, IconPlayOutlineRegular, IconRefreshOutlineRegular, IconSearchOutlineRegular, PathLabel, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { FilesInjected } from './face.ts' import type {} from './FileNavigator.tsx' @@ -38,7 +37,10 @@ export type FilesBodyProps = * @returns the header above the pane's navigator, or the workspace line. */ export function FilesBody(props: FilesBodyProps): ReactNode { - const { useTabInfo, sessionId, useSessions, useStore, refresh, setAutoRefresh, renderSlot, renderFactorySlot, t, useContextMenu } = props + const { + useTabInfo, sessionId, useSessions, useStore, actions, refresh, focus, placeBeside, + setAutoRefresh, renderSlot, renderFactorySlot, t, useContextMenu, + } = props const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const onOpen = useCallback((address: string): void => { @@ -55,6 +57,8 @@ export function FilesBody(props: FilesBodyProps): ReactNode { const tree = store.byPane[panel.id]?.tree return tree?.root === cwd ? tree?.autoRefresh : undefined }) + const searchBarOpen = useStore(store => store.byPane[panel.id]?.searchBarOpen) === true + useEffect(() => cwd === undefined ? undefined : placeBeside(tab.id), [cwd, placeBeside, tab.id]) if (cwd === undefined) { return ( @@ -90,9 +94,26 @@ export function FilesBody(props: FilesBodyProps): ReactNode { + + + {renderSlot('sidebar.right.tab.files.actions', { absolutePath: cwd })}
    -
    {navigator}
    +
    {navigator}
    ) } diff --git a/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx b/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx new file mode 100644 index 0000000000..8ab9bd5ef6 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx @@ -0,0 +1,155 @@ +/** + * The search settings panel edits the navigator's draft of excluded directories. + * The navigator saves it when the panel closes, including through the magnifier. + * The `.gitignore` choice above the list is saved as soon as it changes, as + * the hidden-entry control in the search bar is. + * + * It floats over the navigator below the search field. The field that adds a + * directory stays above the list, which alone scrolls; a new rule goes to the + * top. The header's restore control appears while the list differs from the + * default list in any way, order included, and replaces it with that list. The close control, Escape, and focus leaving the panel request + * closure; focus moving to the magnifier leaves closure to its click. + */ +import { useId, useRef, useState } from 'react' +import type { ReactNode, RefObject } from 'react' +import clsx from 'clsx' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { + IconCloseOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconTrashOutlineRegular, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type {} from './locales.ts' +import { + addRule, defaultRules, isDefaultRules, removeRule, setRuleEnabled, type ExclusionRule, type RuleInvalidReason, +} from './search-rules.ts' +import css from './FilesBody.module.css' + +/** + * The settings panel. + * @param props.rules - the navigator's current draft. + * @param props.respectGitignore - whether the workspace's search leaves out entries `.gitignore` ignores. + * @param props.onRespectGitignore - saves a new `.gitignore` choice at once. + * @param props.trigger - the control that opens and closes the panel; focus moving to it leaves the closing to its click. + * @param props.onChange - replaces the draft without saving preferences. + * @param props.onClose - saves and closes the draft, returning focus to the trigger when requested. + * @param props.t - namespace-bound translate. + * @returns the panel. + */ +export function SearchSettings({ rules, respectGitignore, onRespectGitignore, trigger, onChange, onClose, t }: { + readonly rules: readonly ExclusionRule[] + readonly respectGitignore: boolean + readonly onRespectGitignore: (respectGitignore: boolean) => void + readonly trigger: RefObject + readonly onChange: (rules: readonly ExclusionRule[]) => void + readonly onClose: (refocus: boolean) => void + readonly t: TranslateNS<'sidebarFiles'> +}): ReactNode { + const [text, setText] = useState('') + const [invalid, setInvalid] = useState(undefined) + const add = useRef(null) + const title = useId() + const error = useId() + // A control that is about to disappear hands the keyboard to the add field first, so the panel keeps it. + const keepFocus = (): void => { add.current?.focus() } + return ( +
    { + if (event.key !== 'Escape' || event.nativeEvent.isComposing) return + // Kept from the navigator's own Escape and the overlay's close on the document. + event.preventDefault() + event.stopPropagation() + onClose(true) + }} + onBlur={(event) => { + const next = event.relatedTarget + if (next instanceof Node && (event.currentTarget.contains(next) || trigger.current?.contains(next) === true)) return + onClose(false) + }} + > +
    + {t('settings.title')} + {!isDefaultRules(rules) && ( + + + + )} + + + +
    +

    {t('settings.description')}

    +
    + +
    +
    + + { + setText(event.target.value) + setInvalid(undefined) + }} + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) return + event.preventDefault() + const added = addRule(rules, text) + if (added.kind === 'invalid') { + setInvalid(added.reason) + return + } + onChange(added.rules) + setText('') + }} + /> +
    + {invalid !== undefined && } +
      + {rules.map(rule => ( +
    • + + + + +
    • + ))} +
    +
    + ) +} diff --git a/packages/client/ui-sidebar-files/src/client/face.ts b/packages/client/ui-sidebar-files/src/client/face.ts index 0957339723..3bdccb9337 100644 --- a/packages/client/ui-sidebar-files/src/client/face.ts +++ b/packages/client/ui-sidebar-files/src/client/face.ts @@ -1,11 +1,17 @@ /** * The navigator's half outside React. The injected face (`filesFace`) lists * directories into the store through its own actions, reveals the tab's file, - * carries scroll and keyboard focus between drawings of a pane's tree, and - * measures the navigator's row. The component never awaits or observes - * anything: it registers what it draws and calls the face. The per-pane - * lifetimes are stated on `attach` and `hold`. Beside the face live its - * inputs: the Remote listing and watch bindings and `canOpenOf`. + * carries scroll and keyboard focus between drawings of a pane's tree, runs + * each pane's search, and measures the navigator's row. The component never + * awaits or observes anything: it registers what it draws and calls the face. + * The per-pane lifetimes are stated on `attach` and `hold`. A search asks the + * Host whenever the query or the workspace's search preferences change; each + * pane runs one search at a time, a newer one aborting the older, whose answer + * is dropped. It writes its pending state and its result to the store, and the + * results keep a scroll offset apart from the tree's. The workspace's search + * preferences come from a book shared by every Session. Beside the face live + * its inputs: the Remote listing and watch bindings, and `canOpenOf`; the + * search's binding lives in `search-workspace.ts`. */ import type { ClientRemote, RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -13,11 +19,15 @@ import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { SidebarRightTabDefinition, SidebarRightTabNavigation } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { childPath, locateFile, relativeFileOf, type DirLevel, type FilesStoreInstance } from './store.ts' +import { childPath, locateFile, relativeFileOf, type DirLevel, type FilesSearchResult, type FilesStoreInstance } from './store.ts' import type { WorkspaceFileWatchFrame } from '@deepseek-ai/dsh-api-workspace-files/types' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { DirectoryNode } from './directory-node.ts' import { FILL_BELOW, FULLSCREEN_QUERY } from './navigator-layout.ts' +import type { WorkspaceSearchPreferenceBook } from './search-preferences.ts' +import { enabledPaths, type WorkspaceSearchPreferences } from './search-rules.ts' +import type { SearchWorkspace } from './search-workspace.ts' +import { buildSearchTree } from './search-tree.ts' /** * The box an element is laid out in: its nearest ancestor that generates one, @@ -140,7 +150,11 @@ export interface FilesInjected { * @returns the release; the listing closes once no hold remains when the current task ends. */ readonly hold: (paneId: PaneId, root: string) => () => void - /** Refresh the open directory tree. @param paneId - owning pane. */ + /** + * Refresh the open directory tree, and run the pane's search again when it + * has a query, since its results are a snapshot of one search. + * @param paneId - owning pane. + */ readonly refresh: (paneId: PaneId) => void /** Control automatic rereads without closing watches. @param paneId - owning pane. @param enabled - automatic-refresh setting. */ readonly setAutoRefresh: (paneId: PaneId, enabled: boolean) => void @@ -153,7 +167,8 @@ export interface FilesInjected { */ readonly toggle: (paneId: PaneId, parentPath: string, path: string, expanded: readonly string[]) => void /** - * Record where a pane's tree is scrolled to, without rendering anything. + * Record where a pane's tree, or its search results while they are shown, + * is scrolled to, without rendering anything. * @param paneId - the pane being drawn. * @param scrollTop - the scroll offset in px. */ @@ -165,17 +180,61 @@ export interface FilesInjected { */ readonly hide: (paneId: PaneId) => void /** - * Show a pane's navigator and give its tree keyboard focus now, or when it - * is next drawn; a pane drawn but not yet attached shows it once attached. + * Show a pane's navigator and its search bar, and give the field keyboard focus now, + * or when it is next drawn; a pane drawn but not yet attached shows it once attached. + * Focusing the always-visible files page leaves the pane's preview-navigator show choice unchanged. * A pane with no drawing recorded is left alone. - * @param paneId - the pane whose tree takes focus. + * @param paneId - the pane whose search field takes focus. */ readonly focus: (paneId: PaneId) => void + /** + * Record an attached pane's search text. Text with more than whitespace + * searches the whole workspace with the workspace's current preferences, + * aborting the pane's running search and dropping its answer; while it holds + * such text, a change to those preferences searches again. Blank text ends + * the search, aborting a running one, and the pane draws its tree again. + * @param paneId - the pane being drawn. + * @param cwd - the Session's working directory, the search's root; fixed for the Session once known, so a + * result always shares the pane's tree root. + * @param query - the text as typed. + */ + readonly setQuery: (paneId: PaneId, cwd: string, query: string) => void + /** + * Open or collapse one directory of a pane's search results, leaving the tree's own expansion alone. + * @param paneId - the pane being drawn. + * @param path - absolute directory path. + */ + readonly toggleSearch: (paneId: PaneId, path: string) => void + /** + * Run an attached pane's search again with its current query and the + * workspace's current preferences, as after a failure; a pane without a + * query is left alone. + * @param paneId - the pane being drawn. + */ + readonly retrySearch: (paneId: PaneId) => void + /** + * Change the search preferences of a workspace for every Session and pane + * rooted there. Only the fields the patch names change; the others keep + * their value at the time of the call, not at the time the caller read them. + * @param cwd - the Session's working directory. + * @param patch - any of the exclusion rules, the hidden-entry choice, and the `.gitignore` choice. + */ + readonly setSearchPreferences: (cwd: string, patch: Partial) => void + /** + * Register the drawn search field, or with `null` as gone. Drawing takes + * keyboard focus that `focus` asked for, or that the previous drawing's + * field held when it went in the same task. + * @param paneId - the pane being drawn. + * @param input - the field, or `null` once it is removed. + */ + readonly searchDrawn: (paneId: PaneId, input: HTMLElement | null) => void /** * Register the tree's scroll container as drawn for one tab, or with `null` - * as gone. Drawing restores the pane's scroll offset, takes keyboard focus - * that the previous drawing held when it went or that `focus` asked for, and - * reveals the tab's file unless the pane revealed it last. + * as gone. Drawing restores the pane's scroll offset for what it shows — the + * tree, or the search results, each with its own offset — takes keyboard + * focus that the previous drawing held when it went, and reveals the tab's + * file in the tree unless the pane revealed it last. A drawing registers + * again when it switches between the tree and the results. * @param paneId - the pane being drawn. * @param address - the tab's content address. * @param body - the scroll container, or `null` once it is removed. @@ -216,6 +275,8 @@ export interface FilesInjected { readonly keyedHooks: { /** The measured width of the row a pane's navigator is laid out in, in CSS pixels, keyed by pane id; `undefined` until measured. */ readonly rowWidth: (paneId: string) => HostObservable + /** A workspace's search preferences, keyed by the Session's working directory; shared by every Session rooted there. */ + readonly searchPreferences: (cwd: string) => HostObservable } } @@ -264,6 +325,16 @@ interface PaneRecord { root: DirectoryNode | undefined /** Where the tree was last scrolled to, in px. */ scrollTop: number + /** Where the search results were last scrolled to, in px. */ + searchScrollTop: number + /** The trimmed query the pane's search asks for; empty while no search is shown. */ + searchQuery: string + /** The preferences the pane's search follows, while its query is not blank. */ + following: { readonly cwd: string; readonly stop: () => void } | undefined + /** The running search, whose answer the pane draws only while it is still this one. */ + searching: AbortController | undefined + /** The drawn search field. */ + input: HTMLElement | undefined /** The file whose row was revealed last, so a remount does not reveal it again. */ revealed: string | undefined /** The file whose row a reveal is walking to. */ @@ -274,8 +345,8 @@ interface PaneRecord { current: HTMLElement | undefined /** A completed reveal waits for its row to be drawn. */ scrollToCurrent: boolean - /** Who asked for keyboard focus at the tree's next drawing. */ - focus: object | undefined + /** Who asked for keyboard focus at the next drawing, and whether the tree or the search field takes it. */ + focus: { readonly target: 'tree' | 'search' } | undefined /** `focus` asked to show the navigator before the pane attached; attaching shows it. */ show: boolean /** The measured width of the row the navigator shares with the preview or the page's line. */ @@ -299,8 +370,8 @@ interface TabHome { readonly navigation: HostObservable } -/** `focus` asked for the tree's keyboard focus. */ -const REQUESTED = {} +/** `focus` asked for the search field's keyboard focus. */ +const REQUESTED = { target: 'search' } as const /** * Place a face beside a tab's content, where the workspace command finds it, @@ -312,11 +383,13 @@ const REQUESTED = {} export type PlaceFace = (tabId: TabId, face: FilesInjected) => () => void /** - * Bind the tree's face to one directory listing. + * Bind the tree's face to one directory listing and one workspace search. * @param list - the bound `workspaceFiles.list` call. * @param watch - target-scoped directory observation. * @param canOpen - whether some tab type can open an address. * @param navigationOf - the attached tab's navigation; subscriptions end with this plugin or their disposer. + * @param search - the workspace search. + * @param preferences - every workspace's search preferences, shared by every Session. * @returns the face factory: session, its store instance, and where to place the face beside tabs in, face out. */ export function filesFace( @@ -324,6 +397,8 @@ export function filesFace( watch: WatchWorkspaceDirectory, canOpen: HostObservable<(address: string) => boolean>, navigationOf: (sessionId: SessionId, tabId: TabId) => HostObservable, + search: SearchWorkspace, + preferences: WorkspaceSearchPreferenceBook, ): ( sessionId: SessionId, store: Pick, @@ -337,6 +412,7 @@ export function filesFace( if (pane === undefined) { pane = { lifetime: undefined, mounts: 0, tabs: new Set(), holds: 0, root: undefined, scrollTop: 0, + searchScrollTop: 0, searchQuery: '', following: undefined, searching: undefined, input: undefined, revealed: undefined, revealing: undefined, drawn: undefined, current: undefined, scrollToCurrent: false, focus: undefined, show: false, width: createSnapshotStore(undefined), @@ -353,6 +429,7 @@ export function filesFace( void pane.root?.close() pane.root = undefined pane.unobserve?.() + endSearch(pane) panes.delete(paneId) actions.forget(paneId) } @@ -425,8 +502,73 @@ export function filesFace( }) reveal() } + const resultsShown = (paneId: PaneId): boolean => store.getSnapshot().byPane[paneId]?.search !== undefined + const endSearch = (pane: PaneRecord): void => { + pane.searchQuery = '' + // The next search's results start at their top, even before its answer arrives. + pane.searchScrollTop = 0 + pane.following?.stop() + pane.following = undefined + pane.searching?.abort() + pane.searching = undefined + } + const runSearch = (paneId: PaneId, pane: PaneRecord, cwd: string): void => { + pane.searching?.abort() + const controller = new AbortController() + pane.searching = controller + const query = pane.searchQuery + const { rules, showHidden, respectGitignore } = preferences.source(cwd).getSnapshot() + const excludedPaths = enabledPaths(rules) + actions.searching(paneId) + const settle = (result: FilesSearchResult): void => { + // A newer search, the end of the search, or the pane's end replaced this one. + if (pane.searching !== controller) return + pane.searching = undefined + // New results start at their top; the tree drawn in their place keeps its offset. + pane.searchScrollTop = 0 + if (pane.drawn !== undefined) pane.drawn.body.scrollTop = 0 + actions.searched(paneId, result) + } + search(sessionId, { query, excludedPaths, includeHidden: showHidden, respectGitignore }, controller.signal).then((answer) => { + settle(answer.ok + ? { + kind: 'found', query, tree: buildSearchTree(cwd, answer.value.matches), count: answer.value.matches.length, + truncated: answer.value.truncated, incomplete: answer.value.incomplete, + hiddenLeftOut: !showHidden, excluded: excludedPaths.length > 0, ignored: respectGitignore, + } + : { kind: 'failed', query, failure: answer.error }) + }).catch((error: unknown) => { + // A Remote call rejects only on an assembly fault, and drawing the answer + // fails only on a defect; the pane reports either rather than wait forever. + settle({ kind: 'failed', query, failure: new RemoteError('gateway/internal', error instanceof Error ? error.message : String(error), {}) }) + }) + } + /** Run an attached pane's search again with its current query; a pane without a query is left alone. */ + const searchAgain = (paneId: PaneId): void => { + const pane = panes.get(paneId) + if (pane?.following === undefined) return + runSearch(paneId, pane, pane.following.cwd) + } + const follow = (paneId: PaneId, pane: PaneRecord, cwd: string): void => { + if (pane.following?.cwd === cwd) return + pane.following?.stop() + const source = preferences.source(cwd) + let seen = source.getSnapshot() + const stop = source.subscribe(() => { + const now = source.getSnapshot() + if (now === seen) return + seen = now + runSearch(paneId, pane, cwd) + }) + pane.following = { cwd, stop } + } + const focusInput = (pane: PaneRecord): void => { + pane.focus = undefined + // As for the tree: the dock's inert host lifts later in this commit. + queueMicrotask(() => { pane.input?.focus() }) + } const focusTree = (pane: PaneRecord): void => { - const handoff = {} + const handoff = { target: 'tree' } as const pane.focus = handoff // The dock keeps a newly shown tab's host inert until its own layout // effect, later in this drawing's commit, and the tab's body may draw the @@ -521,7 +663,8 @@ export function filesFace( pane.lifetime ??= new AbortController() if (pane.show) { pane.show = false - actions.shown(paneId, true) + if (pane.navigator === undefined || pane.closable) actions.shown(paneId, true) + else actions.searchBarShown(paneId, true) } pane.mounts += 1 let home = homes.get(tabId) @@ -571,7 +714,11 @@ export function filesFace( }) } }, - refresh: (paneId) => { void panes.get(paneId)?.root?.refreshTree() }, + refresh: (paneId) => { + const pane = panes.get(paneId) + void pane?.root?.refreshTree() + searchAgain(paneId) + }, setAutoRefresh: (paneId, enabled) => { actions.autoRefresh(paneId, enabled) panes.get(paneId)?.root?.setAutomatic(enabled) @@ -579,7 +726,9 @@ export function filesFace( toggle: (paneId, parentPath, path, expanded) => { expand(paneId, parentPath, path, expanded, true) }, scrolled: (paneId, scrollTop) => { const pane = panes.get(paneId) - if (pane?.lifetime !== undefined) pane.scrollTop = scrollTop + if (pane?.lifetime === undefined) return + if (resultsShown(paneId)) pane.searchScrollTop = scrollTop + else pane.scrollTop = scrollTop }, hide(paneId) { const pane = panes.get(paneId) @@ -600,9 +749,46 @@ export function filesFace( const pane = panes.get(paneId) if (pane === undefined) return if (pane.lifetime === undefined) pane.show = true - else actions.shown(paneId, true) - if (pane.drawn === undefined) pane.focus = REQUESTED - else focusTree(pane) + else { + if (pane.navigator === undefined || pane.closable) actions.shown(paneId, true) + else actions.searchBarShown(paneId, true) + } + if (pane.input === undefined) pane.focus = REQUESTED + else focusInput(pane) + }, + setQuery(paneId, cwd, query) { + const pane = panes.get(paneId) + if (pane?.lifetime === undefined) return + actions.queried(paneId, query) + const trimmed = query.trim() + if (trimmed === '') { + endSearch(pane) + return + } + // Whitespace around the text does not change what the search matches. + if (pane.searchQuery === trimmed && pane.following?.cwd === cwd) return + pane.searchQuery = trimmed + follow(paneId, pane, cwd) + runSearch(paneId, pane, cwd) + }, + toggleSearch: (paneId, path) => { actions.searchToggled(paneId, path) }, + retrySearch: searchAgain, + setSearchPreferences: (cwd, patch) => { preferences.update(cwd, patch) }, + searchDrawn(paneId, input) { + if (input === null) { + const pane = panes.get(paneId) + if (pane === undefined) return + const gone = pane.input + pane.input = undefined + if (gone === undefined || gone.ownerDocument.activeElement !== gone) return + const handoff = { target: 'search' } as const + pane.focus = handoff + queueMicrotask(() => { if (pane.focus === handoff) pane.focus = undefined }) + return + } + const pane = record(paneId) + pane.input = input + if (pane.focus?.target === 'search') focusInput(pane) }, bodyDrawn(paneId, address, body) { if (body === null) { @@ -616,15 +802,15 @@ export function filesFace( drop(paneId) if (gone?.contains(gone.ownerDocument.activeElement) !== true) return // Only a drawing in the same commit, the next tab's, takes the keyboard over. - const handoff = {} + const handoff = { target: 'tree' } as const pane.focus = handoff queueMicrotask(() => { if (pane.focus === handoff) pane.focus = undefined }) return } const pane = record(paneId) pane.drawn = { body, address } - body.scrollTop = pane.scrollTop - if (pane.focus !== undefined) focusTree(pane) + body.scrollTop = resultsShown(paneId) ? pane.searchScrollTop : pane.scrollTop + if (pane.focus?.target === 'tree') focusTree(pane) pane.revealing = pane.revealed === address ? undefined : address step(paneId, pane) }, @@ -762,7 +948,7 @@ export function filesFace( drop(paneId) }, hooks: { canOpen }, - keyedHooks: { rowWidth: paneId => record(paneId as PaneId).width }, + keyedHooks: { rowWidth: paneId => record(paneId as PaneId).width, searchPreferences: cwd => preferences.source(cwd) }, } return face } diff --git a/packages/client/ui-sidebar-files/src/client/index.ts b/packages/client/ui-sidebar-files/src/client/index.ts index 050f59caae..95acbdde1b 100644 --- a/packages/client/ui-sidebar-files/src/client/index.ts +++ b/packages/client/ui-sidebar-files/src/client/index.ts @@ -3,7 +3,9 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' * Browser half: register `files` as a right-Sidebar tab type, and the * workspace navigator beside every file preview. The navigator, the page body, * and the toggle share one store and one face per store instance. The package - * README lists the registrations. + * README lists the registrations. Search lives in `search-workspace.ts`, which + * binds the Host's workspace search, `search-rules.ts`, `search-tree.ts`, + * `search-preferences.ts`, and `SearchSettings.tsx`. */ import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' @@ -11,22 +13,27 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' -import type { BoundActions } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import type { TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { FILES_ID, FILES_KIND, filesDefinition } from './definition.tsx' import { canOpenOf, createList, createWatch, filesFace, type FilesInjected } from './face.ts' +import { createSearch } from './search-workspace.ts' import { FileTree } from './FileTree.tsx' import { FileNavigator } from './FileNavigator.tsx' import { FilesBody } from './FilesBody.tsx' import { FilesTitle } from './FilesTitle.tsx' import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts' import { NavigatorToggle } from './NavigatorToggle.tsx' +import { createSearchPreferenceBook, SEARCH_PREFERENCES_KEY } from './search-preferences.ts' import { createFilesStore } from './store.ts' export type { SidebarFilesKey } from './locales.ts' -export type { DirLevel, FilesPaneState, FilesState, FilesTreeState, LevelState } from './store.ts' +export type { DirLevel, FilesPaneState, FilesSearchResult, FilesSearchState, FilesState, FilesTreeState, LevelState } from './store.ts' export type { FilesInjected, ListWorkspaceDirectory, WorkspaceFilesListRemote } from './face.ts' +export type { SearchWorkspace, WorkspaceFilesSearchRemote, WorkspaceSearchAnswer, WorkspaceSearchRequest } from './search-workspace.ts' +export type { SearchMatch } from './search-tree.ts' +export type { ExclusionRule, WorkspaceSearchPreferences } from './search-rules.ts' export type { FilesBodyProps } from './FilesBody.tsx' // Also keeps the Factory declaration in this entry's emitted types, which an `import type {}` would not. export type { TreeEntry, TreeEntryMeta, TreeEntryKind, TreeDirectoryState, FileTreeInput } from './FileTree.tsx' @@ -65,6 +72,8 @@ export const inject = ['slots', 'locale', 'sidebarRightTabs', 'sidebarRight', 'r export function apply(ctx: ClientContext): void { const t = ctx.locale.bind(NS) const handle = createFilesStore() + // One book for the plugin, not per Session: Sessions rooted at the same workspace share its preferences. + const preferences = createSearchPreferenceBook(createSnapshotStore({}, { persist: { name: SEARCH_PREFERENCES_KEY } })) const face = filesFace(createList(ctx.remote), createWatch(ctx.remote), canOpenOf(ctx.sidebarRightTabs), (sessionId, tabId) => { const source = ctx.sidebarRight.tabDomain.occurrence(sessionId, { id: tabId }).navigation return { @@ -78,7 +87,7 @@ export function apply(ctx: ClientContext): void { return () => { active = false; unsubscribe() } }, 'ui-sidebar-files: tab navigation'), } - }) + }, createSearch(ctx.remote), preferences) // A Factory runs its inject per occurrence, so each store instance gets its // one face when it is minted. The shortcut, which acts outside any body, finds // the face placed beside the target tab; a tab's loading and loaded drawings @@ -136,7 +145,8 @@ export function apply(ctx: ClientContext): void { if (target === undefined) return { status: 'blocked', reason: t('shortcut.noSession') } /* jscpd:ignore-end */ return { status: 'handled', run: () => { - // A docked tab with a navigator beside its content that can draw a tree keeps it: the navigator is shown and takes the keyboard. + // A docked tab with a navigator beside its content that can draw a tree keeps it: + // the navigator is shown and its search field takes the keyboard. const placed = target.tabId === undefined ? undefined : beside.get(target.sessionId)?.get(target.tabId) if (target.host === 'dock' && placed !== undefined) { if (!ctx.sidebarRight.isExpanded()) ctx.sidebarRight.toggleExpanded() diff --git a/packages/client/ui-sidebar-files/src/client/locales.ts b/packages/client/ui-sidebar-files/src/client/locales.ts index 065d408e65..968d61ead9 100644 --- a/packages/client/ui-sidebar-files/src/client/locales.ts +++ b/packages/client/ui-sidebar-files/src/client/locales.ts @@ -26,6 +26,7 @@ export const zh = { 'guide.description': '浏览会话工作区的文件', loading: '正在读取…', empty: '空目录', + emptyHidden: '隐藏项未显示', truncated: '条目太多,只显示了一部分。', noWorkspace: '这个会话没有工作区目录。', reload: '重新读取', @@ -41,6 +42,37 @@ export const zh = { 'error.outsideWorkspace': '这个目录在工作区之外,侧栏不会读取它。', 'error.notDirectory': '这不是一个目录。', 'error.unavailable': '读取失败:{message}', + 'search.placeholder': '搜索文件', + 'search.settings': '搜索设置', + 'search.clear': '清空搜索', + 'search.showHidden': '显示隐藏项', + 'search.results': '{count} 个结果', + 'search.empty': '没有匹配项', + 'search.emptyHint.hidden': '隐藏项不会显示。', + 'search.emptyHint.excluded': '排除的文件和目录不会显示。', + 'search.emptyHint.both': '隐藏项以及排除的文件和目录不会显示。', + 'search.emptyHint.ignored': '被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.hiddenIgnored': '隐藏项,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.excludedIgnored': '排除的文件和目录,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.all': '隐藏项、排除的文件和目录,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.label': '为什么没有匹配项', + 'search.truncated': '只显示前 {count} 个结果,请缩小搜索范围。', + 'search.incomplete': '文件数超过搜索上限,或部分目录未能读取,因此结果可能不完整。', + 'search.failed': '搜索失败:{message}', + 'search.retry': '重试', + 'settings.title': '排除的文件和目录', + 'settings.description': '只影响搜索结果,不影响文件树。', + 'settings.respectGitignore': '尊重忽略文件(.gitignore 等)', + 'settings.add': '添加文件或目录', + 'settings.close': '关闭', + 'settings.restore': '还原默认列表', + 'settings.remove': '删除 {path}', + 'settings.toggle': '排除 {path}', + 'settings.invalid.empty': '请输入名称或相对路径。', + 'settings.invalid.nul': '路径不能包含 NUL 字符。', + 'settings.invalid.absolute': '请使用相对于工作区的路径。', + 'settings.invalid.parent': '路径不能包含 . 或 .. 段。', + 'settings.invalid.glob': '路径不能包含通配符 * ? [ ] { } !。', } satisfies Record /** Files dictionary key union. */ @@ -54,6 +86,7 @@ export const en = { 'guide.description': 'Browse files in this session\'s workspace', loading: 'Reading…', empty: 'Empty directory', + emptyHidden: 'Hidden entries are not shown', truncated: 'Too many entries, showing only some of them.', noWorkspace: 'This session has no workspace directory.', reload: 'Reload', @@ -69,6 +102,37 @@ export const en = { 'error.outsideWorkspace': 'That directory is outside the workspace, so the sidebar will not read it.', 'error.notDirectory': 'That is not a directory.', 'error.unavailable': 'Read failed: {message}', + 'search.placeholder': 'Search files', + 'search.settings': 'Search settings', + 'search.clear': 'Clear search', + 'search.showHidden': 'Show hidden entries', + 'search.results': 'Results: {count}', + 'search.empty': 'No matches', + 'search.emptyHint.hidden': 'Hidden entries are not shown.', + 'search.emptyHint.excluded': 'Excluded files and directories are not shown.', + 'search.emptyHint.both': 'Hidden entries and excluded files and directories are not shown.', + 'search.emptyHint.ignored': 'Files and directories ignored by ignore files such as .gitignore are not shown.', + 'search.emptyHint.hiddenIgnored': 'Hidden entries, and files and directories ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.excludedIgnored': 'Excluded files and directories, and those ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.all': 'Hidden entries, excluded files and directories, and those ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.label': 'Why there are no matches', + 'search.truncated': 'Showing only the first {count} results. Narrow the search to see the rest.', + 'search.incomplete': 'The search passed its file limit, or some directories could not be read, so results may be incomplete.', + 'search.failed': 'Search failed: {message}', + 'search.retry': 'Retry', + 'settings.title': 'Excluded files and directories', + 'settings.description': 'Only affects search results, not the file tree.', + 'settings.respectGitignore': 'Respect ignore files (.gitignore, etc.)', + 'settings.add': 'Add file or directory', + 'settings.close': 'Close', + 'settings.restore': 'Restore default list', + 'settings.remove': 'Remove {path}', + 'settings.toggle': 'Exclude {path}', + 'settings.invalid.empty': 'Enter a name or relative path.', + 'settings.invalid.nul': 'The path cannot contain a NUL character.', + 'settings.invalid.absolute': 'Use a path relative to the workspace.', + 'settings.invalid.parent': 'The path cannot contain . or .. segments.', + 'settings.invalid.glob': 'The path cannot contain wildcards * ? [ ] { } !.', } satisfies Record /** Japanese copy, checked against the English keys. */ @@ -79,6 +143,7 @@ export const ja = { 'guide.description': 'このセッションのワークスペース内のファイルを参照', 'loading': '読み取り中…', 'empty': '空のディレクトリ', + 'emptyHidden': '隠し項目は表示されていません', 'truncated': 'エントリが多すぎるため、一部のみ表示しています。', 'noWorkspace': 'このセッションにはワークスペースディレクトリがありません。', 'reload': '再読み込み', @@ -94,6 +159,37 @@ export const ja = { 'error.outsideWorkspace': 'そのディレクトリはワークスペース外のため、サイドバーでは読み取りません。', 'error.notDirectory': 'それはディレクトリではありません。', 'error.unavailable': '読み取りに失敗しました: {message}', + 'search.placeholder': 'ファイルを検索', + 'search.settings': '検索設定', + 'search.clear': '検索をクリア', + 'search.showHidden': '隠し項目を表示', + 'search.results': '結果: {count} 件', + 'search.empty': '一致する項目はありません', + 'search.emptyHint.hidden': '隠し項目は表示されません。', + 'search.emptyHint.excluded': '除外したファイルとディレクトリは表示されません。', + 'search.emptyHint.both': '隠し項目と、除外したファイルとディレクトリは表示されません。', + 'search.emptyHint.ignored': '.gitignore などの無視ファイルで無視されたファイルとディレクトリは表示されません。', + 'search.emptyHint.hiddenIgnored': '隠し項目と、.gitignore などの無視ファイルで無視されたファイルとディレクトリは表示されません。', + 'search.emptyHint.excludedIgnored': '除外したファイルとディレクトリ、および .gitignore などの無視ファイルで無視された項目は表示されません。', + 'search.emptyHint.all': '隠し項目、除外したファイルとディレクトリ、および .gitignore などの無視ファイルで無視された項目は表示されません。', + 'search.emptyHint.label': '一致する項目がない理由', + 'search.truncated': '最初の {count} 件のみ表示しています。検索範囲を絞り込んでください。', + 'search.incomplete': 'ファイル数が検索上限を超えたか、一部のディレクトリを読み取れなかったため、結果が不完全な可能性があります。', + 'search.failed': '検索に失敗しました: {message}', + 'search.retry': '再試行', + 'settings.title': '除外するファイルとディレクトリ', + 'settings.description': '検索結果にのみ適用され、ファイルツリーには影響しません。', + 'settings.respectGitignore': '無視ファイル(.gitignore など)に従う', + 'settings.add': 'ファイルまたはディレクトリを追加', + 'settings.close': '閉じる', + 'settings.restore': '既定のリストに戻す', + 'settings.remove': '{path} を削除', + 'settings.toggle': '{path} を除外', + 'settings.invalid.empty': '名前または相対パスを入力してください。', + 'settings.invalid.nul': 'パスに NUL 文字は使用できません。', + 'settings.invalid.absolute': 'ワークスペースからの相対パスを使用してください。', + 'settings.invalid.parent': 'パスに . や .. のセグメントは使用できません。', + 'settings.invalid.glob': 'パスにワイルドカード * ? [ ] { } ! は使用できません。', } satisfies Record /** Spanish dictionary, checked against the English keys. */ @@ -103,10 +199,11 @@ export const es = { 'guide.title': 'Archivos de espacio de trabajo', 'guide.description': 'Explorar archivos en el espacio de trabajo de esta sesión', loading: 'Leyendo…', - empty: 'directorio vacio', + empty: 'Directorio vacío', + emptyHidden: 'Las entradas ocultas no se muestran', truncated: 'Demasiadas entradas y solo se muestran algunas de ellas.', noWorkspace: 'Esta sesión no tiene ningún directorio de espacio de trabajo.', - reload: 'recargar', + reload: 'Recargar', autoRefresh: 'Actualización automática', 'autoRefresh.enable': 'Habilitar actualización automática', 'autoRefresh.disable': 'Deshabilitar la actualización automática', @@ -119,6 +216,37 @@ export const es = { 'error.outsideWorkspace': 'Ese directorio está fuera del espacio de trabajo, por lo que la barra lateral no lo leerá.', 'error.notDirectory': 'Eso no es un directorio.', 'error.unavailable': 'Error de lectura: {message}', + 'search.placeholder': 'Buscar archivos', + 'search.settings': 'Configuración de búsqueda', + 'search.clear': 'Borrar búsqueda', + 'search.showHidden': 'Mostrar entradas ocultas', + 'search.results': 'Resultados: {count}', + 'search.empty': 'Sin coincidencias', + 'search.emptyHint.hidden': 'No se muestran las entradas ocultas.', + 'search.emptyHint.excluded': 'No se muestran los archivos ni los directorios excluidos.', + 'search.emptyHint.both': 'No se muestran las entradas ocultas ni los archivos y directorios excluidos.', + 'search.emptyHint.ignored': 'No se muestran los archivos ni los directorios que ignoran los archivos de exclusión como .gitignore.', + 'search.emptyHint.hiddenIgnored': 'No se muestran las entradas ocultas ni los archivos y directorios que ignoran los archivos de exclusión como .gitignore.', + 'search.emptyHint.excludedIgnored': 'No se muestran los archivos ni los directorios excluidos o ignorados por archivos de exclusión como .gitignore.', + 'search.emptyHint.all': 'No se muestran las entradas ocultas, los archivos y directorios excluidos ni los ignorados por archivos de exclusión como .gitignore.', + 'search.emptyHint.label': 'Por qué no hay coincidencias', + 'search.truncated': 'Solo se muestran los primeros {count} resultados. Acote la búsqueda para ver el resto.', + 'search.incomplete': 'La búsqueda superó su límite de archivos o no se pudieron leer algunos directorios, por lo que los resultados pueden estar incompletos.', + 'search.failed': 'Error de búsqueda: {message}', + 'search.retry': 'Reintentar', + 'settings.title': 'Archivos y directorios excluidos', + 'settings.description': 'Solo afecta a los resultados de búsqueda, no al árbol de archivos.', + 'settings.respectGitignore': 'Respetar archivos de exclusión (.gitignore, etc.)', + 'settings.add': 'Añadir archivo o directorio', + 'settings.close': 'Cerrar', + 'settings.restore': 'Restaurar la lista predeterminada', + 'settings.remove': 'Eliminar {path}', + 'settings.toggle': 'Excluir {path}', + 'settings.invalid.empty': 'Introduzca un nombre o una ruta relativa.', + 'settings.invalid.nul': 'La ruta no puede contener el carácter NUL.', + 'settings.invalid.absolute': 'Use una ruta relativa al espacio de trabajo.', + 'settings.invalid.parent': 'La ruta no puede contener segmentos «.» ni «..».', + 'settings.invalid.glob': 'La ruta no puede contener comodines * ? [ ] { } !.', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -129,6 +257,7 @@ export const fr = { 'guide.description': "Parcourir les fichiers dans l'espace de travail de cette session", loading: 'Lecture…', empty: 'Répertoire vide', + emptyHidden: 'Les entrées masquées ne sont pas affichées', truncated: "Trop d'entrées, n'en affichant que certaines.", noWorkspace: "Cette session n'a pas de répertoire d'espace de travail.", reload: 'Recharger', @@ -144,6 +273,37 @@ export const fr = { 'error.outsideWorkspace': 'Ce répertoire se trouve en dehors de l’espace de travail, donc la barre latérale ne le lira pas.', 'error.notDirectory': "Ce n'est pas un répertoire.", 'error.unavailable': 'Échec de lecture : {message}', + 'search.placeholder': 'Rechercher des fichiers', + 'search.settings': 'Paramètres de recherche', + 'search.clear': 'Effacer la recherche', + 'search.showHidden': 'Afficher les entrées masquées', + 'search.results': 'Résultats : {count}', + 'search.empty': 'Aucune correspondance', + 'search.emptyHint.hidden': 'Les entrées masquées ne sont pas affichées.', + 'search.emptyHint.excluded': 'Les fichiers et répertoires exclus ne sont pas affichés.', + 'search.emptyHint.both': 'Les entrées masquées et les fichiers et répertoires exclus ne sont pas affichés.', + 'search.emptyHint.ignored': 'Les fichiers et répertoires ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.hiddenIgnored': 'Les entrées masquées et les fichiers et répertoires ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.excludedIgnored': 'Les fichiers et répertoires exclus ou ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.all': 'Les entrées masquées, les fichiers et répertoires exclus et ceux ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.label': 'Pourquoi aucune correspondance', + 'search.truncated': 'Seuls les {count} premiers résultats sont affichés. Affinez la recherche pour voir les autres.', + 'search.incomplete': 'La recherche a dépassé sa limite de fichiers, ou certains répertoires n’ont pas pu être lus, les résultats peuvent donc être incomplets.', + 'search.failed': 'Échec de la recherche : {message}', + 'search.retry': 'Réessayer', + 'settings.title': 'Fichiers et répertoires exclus', + 'settings.description': 'Concerne uniquement les résultats de recherche, pas l’arborescence des fichiers.', + 'settings.respectGitignore': 'Respecter les fichiers d’exclusion (.gitignore, etc.)', + 'settings.add': 'Ajouter un fichier ou un répertoire', + 'settings.close': 'Fermer', + 'settings.restore': 'Restaurer la liste par défaut', + 'settings.remove': 'Supprimer {path}', + 'settings.toggle': 'Exclure {path}', + 'settings.invalid.empty': 'Saisissez un nom ou un chemin relatif.', + 'settings.invalid.nul': 'Le chemin ne peut pas contenir de caractère NUL.', + 'settings.invalid.absolute': 'Utilisez un chemin relatif à l’espace de travail.', + 'settings.invalid.parent': 'Le chemin ne peut pas contenir de segments « . » ou « .. ».', + 'settings.invalid.glob': 'Le chemin ne peut pas contenir les caractères génériques * ? [ ] { } !.', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -154,6 +314,7 @@ export const de = { 'guide.description': 'Durchsuchen Sie die Dateien im Arbeitsbereich dieser Sitzung', loading: 'Lesen…', empty: 'Leeres Verzeichnis', + emptyHidden: 'Versteckte Einträge werden nicht angezeigt', truncated: 'Zu viele Einträge, es werden nur einige davon angezeigt.', noWorkspace: 'Diese Sitzung hat kein Arbeitsbereichsverzeichnis.', reload: 'Neu laden', @@ -169,6 +330,37 @@ export const de = { 'error.outsideWorkspace': 'Dieses Verzeichnis liegt außerhalb des Arbeitsbereichs und wird daher von der Seitenleiste nicht gelesen.', 'error.notDirectory': 'Das ist kein Verzeichnis.', 'error.unavailable': 'Lesen fehlgeschlagen: {message}', + 'search.placeholder': 'Dateien suchen', + 'search.settings': 'Sucheinstellungen', + 'search.clear': 'Suche löschen', + 'search.showHidden': 'Versteckte Einträge anzeigen', + 'search.results': 'Ergebnisse: {count}', + 'search.empty': 'Keine Treffer', + 'search.emptyHint.hidden': 'Versteckte Einträge werden nicht angezeigt.', + 'search.emptyHint.excluded': 'Ausgeschlossene Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.both': 'Versteckte Einträge sowie ausgeschlossene Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.ignored': 'Von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.hiddenIgnored': 'Versteckte Einträge sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.excludedIgnored': 'Ausgeschlossene sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.all': 'Versteckte Einträge, ausgeschlossene sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.label': 'Warum es keine Treffer gibt', + 'search.truncated': 'Nur die ersten {count} Ergebnisse werden angezeigt. Grenzen Sie die Suche ein, um weitere zu sehen.', + 'search.incomplete': 'Die Suche hat ihr Dateilimit überschritten oder einige Verzeichnisse konnten nicht gelesen werden, daher sind die Ergebnisse möglicherweise unvollständig.', + 'search.failed': 'Suche fehlgeschlagen: {message}', + 'search.retry': 'Erneut versuchen', + 'settings.title': 'Ausgeschlossene Dateien und Verzeichnisse', + 'settings.description': 'Wirkt sich nur auf Suchergebnisse aus, nicht auf den Dateibaum.', + 'settings.respectGitignore': 'Ignore-Dateien beachten (.gitignore usw.)', + 'settings.add': 'Datei oder Verzeichnis hinzufügen', + 'settings.close': 'Schließen', + 'settings.restore': 'Standardliste wiederherstellen', + 'settings.remove': '{path} entfernen', + 'settings.toggle': '{path} ausschließen', + 'settings.invalid.empty': 'Geben Sie einen Namen oder relativen Pfad ein.', + 'settings.invalid.nul': 'Der Pfad darf kein NUL-Zeichen enthalten.', + 'settings.invalid.absolute': 'Verwenden Sie einen Pfad relativ zum Arbeitsbereich.', + 'settings.invalid.parent': 'Der Pfad darf keine Segmente . oder .. enthalten.', + 'settings.invalid.glob': 'Der Pfad darf keine Platzhalter * ? [ ] { } ! enthalten.', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -179,6 +371,7 @@ export const ru = { 'guide.description': 'Просмотр файлов в рабочей области этого сеанса', loading: 'Чтение…', empty: 'Пустой каталог', + emptyHidden: 'Скрытые записи не показаны', truncated: 'Слишком много записей, показаны только некоторые из них.', noWorkspace: 'В этом сеансе нет каталога рабочей области.', reload: 'Перезагрузить', @@ -194,6 +387,37 @@ export const ru = { 'error.outsideWorkspace': 'Этот каталог находится за пределами рабочей области, поэтому боковая панель его не читает.', 'error.notDirectory': 'Это не каталог.', 'error.unavailable': 'Не удалось прочитать: {message}.', + 'search.placeholder': 'Поиск файлов', + 'search.settings': 'Настройки поиска', + 'search.clear': 'Очистить поиск', + 'search.showHidden': 'Показывать скрытые записи', + 'search.results': 'Результаты: {count}', + 'search.empty': 'Совпадений нет', + 'search.emptyHint.hidden': 'Скрытые записи не показываются.', + 'search.emptyHint.excluded': 'Исключённые файлы и каталоги не показываются.', + 'search.emptyHint.both': 'Скрытые записи, а также исключённые файлы и каталоги не показываются.', + 'search.emptyHint.ignored': 'Файлы и каталоги, игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.hiddenIgnored': 'Скрытые записи, а также файлы и каталоги, игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.excludedIgnored': 'Исключённые файлы и каталоги, а также игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.all': 'Скрытые записи, исключённые файлы и каталоги, а также игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.label': 'Почему нет совпадений', + 'search.truncated': 'Показаны только первые {count} результатов. Уточните запрос, чтобы увидеть остальные.', + 'search.incomplete': 'Поиск превысил лимит файлов или часть каталогов не удалось прочитать, поэтому результаты могут быть неполными.', + 'search.failed': 'Не удалось выполнить поиск: {message}', + 'search.retry': 'Повторить', + 'settings.title': 'Исключённые файлы и каталоги', + 'settings.description': 'Влияет только на результаты поиска, не на дерево файлов.', + 'settings.respectGitignore': 'Учитывать файлы исключений (.gitignore и др.)', + 'settings.add': 'Добавить файл или каталог', + 'settings.close': 'Закрыть', + 'settings.restore': 'Восстановить список по умолчанию', + 'settings.remove': 'Удалить {path}', + 'settings.toggle': 'Исключить {path}', + 'settings.invalid.empty': 'Введите имя или относительный путь.', + 'settings.invalid.nul': 'Путь не может содержать символ NUL.', + 'settings.invalid.absolute': 'Укажите путь относительно рабочей области.', + 'settings.invalid.parent': 'Путь не может содержать сегменты «.» или «..».', + 'settings.invalid.glob': 'Путь не может содержать подстановочные знаки * ? [ ] { } !.', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -204,6 +428,7 @@ export const pt = { 'guide.description': 'Procure arquivos no espaço de trabalho desta sessão', loading: 'Lendo…', empty: 'Diretório vazio', + emptyHidden: 'Entradas ocultas não são mostradas', truncated: 'Muitas entradas, mostrando apenas algumas delas.', noWorkspace: 'Esta sessão não possui diretório de espaço de trabalho.', reload: 'Recarregar', @@ -219,4 +444,35 @@ export const pt = { 'error.outsideWorkspace': 'Esse diretório está fora da área de trabalho, portanto a barra lateral não o lerá.', 'error.notDirectory': 'Isso não é um diretório.', 'error.unavailable': 'Falha na leitura: {message}', + 'search.placeholder': 'Pesquisar arquivos', + 'search.settings': 'Configurações de pesquisa', + 'search.clear': 'Limpar pesquisa', + 'search.showHidden': 'Mostrar entradas ocultas', + 'search.results': 'Resultados: {count}', + 'search.empty': 'Nenhuma correspondência', + 'search.emptyHint.hidden': 'Entradas ocultas não são mostradas.', + 'search.emptyHint.excluded': 'Arquivos e diretórios excluídos não são mostrados.', + 'search.emptyHint.both': 'Entradas ocultas e arquivos e diretórios excluídos não são mostrados.', + 'search.emptyHint.ignored': 'Arquivos e diretórios ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.hiddenIgnored': 'Entradas ocultas e arquivos e diretórios ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.excludedIgnored': 'Arquivos e diretórios excluídos ou ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.all': 'Entradas ocultas, arquivos e diretórios excluídos e os ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.label': 'Por que não há correspondências', + 'search.truncated': 'Mostrando apenas os primeiros {count} resultados. Refine a pesquisa para ver o restante.', + 'search.incomplete': 'A pesquisa ultrapassou seu limite de arquivos ou alguns diretórios não puderam ser lidos, então os resultados podem estar incompletos.', + 'search.failed': 'Falha na pesquisa: {message}', + 'search.retry': 'Tentar novamente', + 'settings.title': 'Arquivos e diretórios excluídos', + 'settings.description': 'Afeta apenas os resultados da pesquisa, não a árvore de arquivos.', + 'settings.respectGitignore': 'Respeitar arquivos de exclusão (.gitignore etc.)', + 'settings.add': 'Adicionar arquivo ou diretório', + 'settings.close': 'Fechar', + 'settings.restore': 'Restaurar a lista padrão', + 'settings.remove': 'Remover {path}', + 'settings.toggle': 'Excluir {path}', + 'settings.invalid.empty': 'Digite um nome ou um caminho relativo.', + 'settings.invalid.nul': 'O caminho não pode conter o caractere NUL.', + 'settings.invalid.absolute': 'Use um caminho relativo ao espaço de trabalho.', + 'settings.invalid.parent': 'O caminho não pode conter segmentos “.” ou “..”.', + 'settings.invalid.glob': 'O caminho não pode conter curingas * ? [ ] { } !.', } satisfies Record diff --git a/packages/client/ui-sidebar-files/src/client/search-preferences.ts b/packages/client/ui-sidebar-files/src/client/search-preferences.ts new file mode 100644 index 0000000000..6afb25a0e0 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-preferences.ts @@ -0,0 +1,116 @@ +/** + * The search preferences of every workspace, kept in browser storage and + * shared by every Session and pane whose workspace root is the same. + * + * The storage value maps a normalized workspace root to the fields the reader + * changed there. A field equal to its default is left out of the entry, a root + * the reader never changed has no entry, and a change back to the defaults + * removes its entry, so the defaults of a later build reach every field the + * reader left alone. Storage + * holds whatever an earlier build or the reader wrote: each entry is read + * through {@link readSearchPreferences} rather than trusted. + */ +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import { + changedSearchPreferences, defaultSearchPreferences, readSearchPreferences, type WorkspaceSearchPreferences, +} from './search-rules.ts' + +/** + * The localStorage key the preferences of every workspace are stored under. + * + * Each entry holds whichever of `rules`, `showHidden`, and `respectGitignore` + * differ from their defaults. Every field is optional on read: + * {@link readSearchPreferences} gives a missing or mistyped one its current + * default and reads the others as usual. A change that an earlier build would + * misread takes a new key. + */ +export const SEARCH_PREFERENCES_KEY = 'dsh.sidebar-files.workspace-search.v1' + +/** + * The storage key of one workspace root: the root as the Host reports it, with + * trailing `/` and `\` removed except the one that makes a filesystem root + * (`/`, `C:\`, `C:/`). Case and separators are otherwise kept, so two + * spellings of one directory keep separate preferences. + * @param cwd - the Session's working directory. + * @returns the key its preferences are stored under. + */ +export function workspaceKey(cwd: string): string { + const trimmed = cwd.replace(/[/\\]+$/, '') + if (trimmed === '') return cwd.slice(0, 1) + if (/^[A-Za-z]:$/.test(trimmed) && cwd.length > trimmed.length) return cwd.slice(0, 3) + return trimmed +} + +/** + * One stored entry, without trusting the stored value's type. + * @param stored - the storage value, as rehydrated. + * @param key - a workspace key. + * @returns the entry's value, or `undefined` when the value is not an object or has no such entry. + */ +function storedEntry(stored: unknown, key: string): unknown { + if (typeof stored !== 'object' || stored === null || Array.isArray(stored) || !Object.hasOwn(stored, key)) return undefined + return Object.getOwnPropertyDescriptor(stored, key)?.value +} + +/** The search preferences of every workspace root. */ +export interface WorkspaceSearchPreferenceBook { + /** + * Observe one root's preferences. The same root, by its {@link workspaceKey}, + * gets the same source, and its snapshot keeps its reference until that + * root's preferences change. + * @param cwd - the Session's working directory. + * @returns the source. + */ + readonly source: (cwd: string) => HostObservable + /** + * Change the reader's choice for one root: the fields the patch names + * replace those of the root's current preferences, read at the call; the + * entry keeps only the fields that differ from the defaults, and is removed + * when none does. + * @param cwd - the Session's working directory. + * @param patch - any of the exclusion rules, the hidden-entry choice, and the `.gitignore` choice. + */ + readonly update: (cwd: string, patch: Partial) => void +} + +/** + * Keep the preferences of every workspace root in one persisted store. + * @param store - the persisted store; its rehydrated value may be anything JSON can hold. + * @returns the preferences by workspace root. + */ +export function createSearchPreferenceBook(store: SnapshotStore): WorkspaceSearchPreferenceBook { + const sources = new Map>() + const source = (cwd: string): HostObservable => { + const key = workspaceKey(cwd) + const known = sources.get(key) + if (known !== undefined) return known + let seen: { readonly raw: unknown; readonly preferences: WorkspaceSearchPreferences } | undefined + const created: HostObservable = { + getSnapshot: () => { + const raw = storedEntry(store.getSnapshot(), key) + if (seen === undefined || seen.raw !== raw) { + seen = { raw, preferences: raw === undefined ? defaultSearchPreferences() : readSearchPreferences(raw) } + } + return seen.preferences + }, + subscribe: listener => store.subscribe(listener), + } + sources.set(key, created) + return created + } + return { + source, + update(cwd, patch) { + const preferences = { ...source(cwd).getSnapshot(), ...patch } + const key = workspaceKey(cwd) + const stored = store.getSnapshot() + const entries = typeof stored === 'object' && stored !== null && !Array.isArray(stored) + ? Object.entries(stored).filter(([name]) => name !== key) + : [] + const changed = changedSearchPreferences(preferences) + if (changed !== undefined) entries.push([key, changed]) + store.set(Object.fromEntries(entries)) + }, + } +} diff --git a/packages/client/ui-sidebar-files/src/client/search-rules.ts b/packages/client/ui-sidebar-files/src/client/search-rules.ts new file mode 100644 index 0000000000..6751a7a3bc --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-rules.ts @@ -0,0 +1,233 @@ +/** + * Search exclusion rules and the search preferences that carry them. + * + * A rule names files and directories the workspace search leaves out, by name + * or by path. A path without `/` is a name and matches every file or directory + * of that name at any depth; a path with `/` is relative to the workspace root + * and matches that one file or directory. An excluded directory's contents are + * left out with it. This module keeps the editable list, checks what the + * reader types, and reads the list back from a stored value; the Host's + * workspace search applies the rules. + * + * The list records no origin: a default path the reader removed and then + * added again by hand counts as a default that is present. + */ + +/** One exclusion rule as the settings list shows and stores it. */ +export interface ExclusionRule { + /** Normalized name or `/`-separated workspace-relative path of a file or directory. */ + readonly path: string + /** Whether the search leaves this path out now. */ + readonly enabled: boolean +} + +/** Why a typed rule path was refused; each reason has its own `settings.invalid.*` line. */ +export type RuleInvalidReason = 'empty' | 'nul' | 'absolute' | 'parent' | 'glob' + +/** A typed rule path after normalization, or why it was refused. */ +export type RulePathResult = + | { readonly kind: 'ok'; readonly path: string } + | { readonly kind: 'invalid'; readonly reason: RuleInvalidReason } + +/** The search panel's persisted choices. */ +export interface WorkspaceSearchPreferences { + /** Exclusion rules, newest first. */ + readonly rules: readonly ExclusionRule[] + /** Whether results include hidden entries. */ + readonly showHidden: boolean + /** Whether the search leaves out entries the workspace's `.gitignore` files ignore. */ + readonly respectGitignore: boolean +} + +/** + * Names excluded until the reader changes the list, in the order a restore + * lists them: version-control, package-manager, and build output directories, + * then the metadata files and directories macOS and Windows write into folders + * and volumes. + */ +const DEFAULT_EXCLUDED_PATHS: readonly string[] = [ + '.git', '.hg', '.next', '.pnpm-store', '.svn', '.turbo', '.yarn', 'build', 'coverage', 'dist', 'node_modules', + '.DS_Store', '.Spotlight-V100', '.Trashes', '.fseventsd', 'Thumbs.db', 'desktop.ini', '$RECYCLE.BIN', 'System Volume Information', +] + +/** Characters that would make a literal path read as a pattern. */ +const GLOB = /[*?[\]{}!]/ + +/** + * Normalize a typed rule path: trim it, turn `\` into `/`, merge repeated + * `/`, and drop leading `./`, trailing `/`, and whitespace exposed at either + * edge. Internal whitespace stays unchanged. + * + * Refuses an empty path, one containing NUL, an absolute one (leading `/`, a + * drive letter such as `C:`, or `~`, including prefixes exposed by dropping + * leading `./` and whitespace), one with a `.` or `..` segment, and one + * containing a glob character (`* ? [ ] { } !`). Other characters, such as + * `$` and spaces, are kept literally. + * @param input - the text the reader typed. + * @returns the normalized path, unchanged by normalization again, or why it was refused. + */ +export function normalizeRulePath(input: string): RulePathResult { + const slashed = input.trim().replace(/\\/g, '/') + if (slashed === '') return { kind: 'invalid', reason: 'empty' } + if (slashed.includes('\0')) return { kind: 'invalid', reason: 'nul' } + const relative = slashed.replace(/\/{2,}/g, '/').replace(/^(?:\s|\.\/)+/, '') + if (slashed.startsWith('/') || /^(?:\/|~|[A-Za-z]:)/.test(relative)) return { kind: 'invalid', reason: 'absolute' } + // Anchor the suffix scan at the start so long internal whitespace is not scanned repeatedly. + const path = relative.replace(/^(.*[^\s/])?[\s/]*$/s, '$1') + if (GLOB.test(path)) return { kind: 'invalid', reason: 'glob' } + if (path === '') return { kind: 'invalid', reason: 'empty' } + if (path.split('/').some(segment => segment === '.' || segment === '..')) return { kind: 'invalid', reason: 'parent' } + return { kind: 'ok', path } +} + +/** + * The default rule list, every rule enabled. + * @returns a new list in default order. + */ +export function defaultRules(): ExclusionRule[] { + return DEFAULT_EXCLUDED_PATHS.map(path => ({ path, enabled: true })) +} + +/** + * The preferences before the reader changes anything. + * @returns the default rules, hidden entries not shown, and `.gitignore` respected. + */ +export function defaultSearchPreferences(): WorkspaceSearchPreferences { + return { rules: defaultRules(), showHidden: false, respectGitignore: true } +} + +/** + * Add a typed rule at the top of the list, enabled. + * + * A rule whose normalized path is already listed, enabled or not, is enabled + * and moved to the top instead of being listed twice. Paths compare exactly. + * @param rules - the current list. + * @param input - the text the reader typed. + * @returns the new list, or why the text was refused. + */ +export function addRule( + rules: readonly ExclusionRule[], + input: string, +): { readonly kind: 'ok'; readonly rules: readonly ExclusionRule[] } | { readonly kind: 'invalid'; readonly reason: RuleInvalidReason } { + const normalized = normalizeRulePath(input) + if (normalized.kind === 'invalid') return normalized + const { path } = normalized + return { kind: 'ok', rules: [{ path, enabled: true }, ...rules.filter(rule => rule.path !== path)] } +} + +/** + * Remove one rule. + * @param rules - the current list. + * @param path - the rule's normalized path. + * @returns the list without it; an unlisted path leaves the list as it was. + */ +export function removeRule(rules: readonly ExclusionRule[], path: string): readonly ExclusionRule[] { + return rules.filter(rule => rule.path !== path) +} + +/** + * Enable or disable one rule in place. + * @param rules - the current list. + * @param path - the rule's normalized path. + * @param enabled - whether the search leaves the path out. + * @returns the list with that rule changed; an unlisted path leaves the list as it was. + */ +export function setRuleEnabled(rules: readonly ExclusionRule[], path: string, enabled: boolean): readonly ExclusionRule[] { + return rules.map(rule => rule.path === path && rule.enabled !== enabled ? { path, enabled } : rule) +} + +/** + * The paths the search leaves out. + * @param rules - the current list. + * @returns the enabled rules' paths, in list order. + */ +export function enabledPaths(rules: readonly ExclusionRule[]): string[] { + return rules.filter(rule => rule.enabled).map(rule => rule.path) +} + +/** + * Whether a rule list equals the default list: the same paths in the same + * order, every rule enabled. + * @param rules - the current list. + * @returns `true` when nothing differs from {@link defaultRules}. + */ +export function isDefaultRules(rules: readonly ExclusionRule[]): boolean { + return rules.length === DEFAULT_EXCLUDED_PATHS.length + && rules.every((rule, index) => rule.path === DEFAULT_EXCLUDED_PATHS[index] && rule.enabled) +} + +/** + * Read preferences back from a value browser storage holds, which any earlier + * build or the reader may have written, after its JSON text was parsed. + * + * Each field is read on its own: a missing or mistyped `rules` array, + * `showHidden`, or `respectGitignore` takes the current default, so an entry + * that stores only the fields the reader changed keeps the defaults of the + * running build for the rest. A value that is not an object gives the + * defaults. Inside a `rules` array, a rule that is not an object with a string + * `path` and a boolean `enabled`, or whose path `normalizeRulePath` refuses, + * is dropped; a rule whose normalized path repeats an earlier one is dropped + * too. A stored empty list stays empty. + * @param value - the parsed stored value. + * @returns the preferences to use. + */ +export function readSearchPreferences(value: unknown): WorkspaceSearchPreferences { + const defaults = defaultSearchPreferences() + if (typeof value !== 'object' || value === null || Array.isArray(value)) return defaults + const field = (name: string): unknown => Object.hasOwn(value, name) ? Object.getOwnPropertyDescriptor(value, name)?.value : undefined + const rules = field('rules') + const showHidden = field('showHidden') + const respectGitignore = field('respectGitignore') + return { + rules: Array.isArray(rules) ? readRules(rules) : defaults.rules, + showHidden: typeof showHidden === 'boolean' ? showHidden : defaults.showHidden, + respectGitignore: typeof respectGitignore === 'boolean' ? respectGitignore : defaults.respectGitignore, + } +} + +/** + * The well-formed rules of a stored list, normalized, in stored order. + * @param rules - the stored list. + * @returns the rules to use. + */ +function readRules(rules: readonly unknown[]): ExclusionRule[] { + const parsed: ExclusionRule[] = [] + for (const rule of rules) { + if (typeof rule !== 'object' || rule === null || !('path' in rule) || !('enabled' in rule)) continue + const { path, enabled } = rule + if (typeof path !== 'string' || typeof enabled !== 'boolean') continue + const normalized = normalizeRulePath(path) + if (normalized.kind === 'invalid' || parsed.some(kept => kept.path === normalized.path)) continue + parsed.push({ path: normalized.path, enabled }) + } + return parsed +} + +/** + * The fields of preferences that differ from the defaults, as browser storage + * keeps them: a field equal to its default is left out, so a later build's + * default reaches it. + * @param preferences - the preferences to store. + * @returns the differing fields, or `undefined` when nothing differs from {@link defaultSearchPreferences}. + */ +export function changedSearchPreferences(preferences: WorkspaceSearchPreferences): Partial | undefined { + const defaults = defaultSearchPreferences() + const changed: { -readonly [K in keyof WorkspaceSearchPreferences]?: WorkspaceSearchPreferences[K] } = {} + if (!isDefaultRules(preferences.rules)) changed.rules = preferences.rules.map(rule => ({ path: rule.path, enabled: rule.enabled })) + if (preferences.showHidden !== defaults.showHidden) changed.showHidden = preferences.showHidden + if (preferences.respectGitignore !== defaults.respectGitignore) changed.respectGitignore = preferences.respectGitignore + return Object.keys(changed).length === 0 ? undefined : changed +} + +/** + * Whether the tree treats an entry as hidden: its name starts with `.`. The + * Host's search judges names the same way, except on a Windows Host, where + * ripgrep also treats an entry with the hidden file attribute as hidden. The + * tree lists names one level at a time under the workspace root, so a name is + * judged on its own. + * @param entry - a listed entry. + * @returns `true` for a hidden entry. + */ +export function isHiddenEntry(entry: { readonly name: string }): boolean { + return entry.name.startsWith('.') +} diff --git a/packages/client/ui-sidebar-files/src/client/search-tree.ts b/packages/client/ui-sidebar-files/src/client/search-tree.ts new file mode 100644 index 0000000000..06b51dafe2 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-tree.ts @@ -0,0 +1,74 @@ +/** + * The search results drawn as a tree, and the highlights in its names. + * + * A search answers with the workspace-relative paths of its matches, and not + * necessarily with their ancestors. The tree the navigator draws + * needs every level from the root down, so this module synthesizes the levels + * the results pass through, keyed by absolute path as the listed tree keys them. + */ +import { childPath } from './store.ts' +import type { DirLevel, FilesTreeState } from './store.ts' + +/** One entry a search matched. */ +export interface SearchMatch { + /** `/`-separated path relative to the workspace root, without leading or trailing `/`. */ + readonly path: string + /** Whether the entry is a file, a directory, or something else. */ + readonly type: DirLevel['entries'][number]['type'] +} + +/** + * Draw search results as a fully expanded tree. + * + * Every directory the results pass through gets a ready level: the root, each + * result's ancestors, and each result that is itself a directory. A level lists + * the children the results put there, once each, in first-seen order; a name + * that is an ancestor anywhere is a directory. A directory that matched but + * holds no matching descendant has a level with no entries, which the + * navigator draws differently from an empty listed directory. Every level is + * expanded, no level is truncated, and the tree does not refresh itself. + * @param root - absolute path of the workspace root, as `FilesTreeState.root` holds it. + * @param entries - the search's entries. + * @returns the tree to draw. + */ +export function buildSearchTree(root: string, entries: readonly SearchMatch[]): FilesTreeState { + type Names = Map + const children = new Map([[root, new Map()]]) + const directory = (path: string): Names => { + const names = children.get(path) ?? new Map() + children.set(path, names) + return names + } + for (const entry of entries) { + const parts = entry.path.split('/') + let parent = root + for (const [index, name] of parts.entries()) { + const type = index === parts.length - 1 ? entry.type : 'directory' + const names = directory(parent) + if (type === 'directory' || !names.has(name)) names.set(name, type) + parent = childPath(parent, name) + if (type === 'directory') directory(parent) + } + } + const levels: FilesTreeState['levels'] = {} + for (const [path, names] of children) { + const level: DirLevel = { entries: [...names].map(([name, type]) => ({ name, type })), truncated: false } + levels[path] = { kind: 'ready', level } + } + return { autoRefresh: false, root, levels, expanded: [...children.keys()] } +} + +/** + * Where the query occurs in one name, for highlighting. + * + * Matching ignores case by Unicode simple case folding; the ranges index the + * name as given. An empty query has no occurrence. + * @param name - the drawn name. + * @param query - the search text. + * @returns non-overlapping `[start, end)` UTF-16 ranges, left to right. + */ +export function matchRanges(name: string, query: string): readonly (readonly [number, number])[] { + if (query === '') return [] + const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu') + return [...name.matchAll(pattern)].map(match => [match.index, match.index + match[0].length] as const) +} diff --git a/packages/client/ui-sidebar-files/src/client/search-workspace.ts b/packages/client/ui-sidebar-files/src/client/search-workspace.ts new file mode 100644 index 0000000000..a3f90efa93 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-workspace.ts @@ -0,0 +1,67 @@ +/** + * The workspace search, bound to the Host's `workspaceFiles.search` call. + * + * The Host walks the whole workspace of the Session and applies the query, + * the exclusion rules, the hidden-entry choice, and `.gitignore`; the Client + * only draws the matches it returns. + */ +import type { ClientRemote, RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SearchMatch } from './search-tree.ts' + +/** What one search asks the Host for. */ +export interface WorkspaceSearchRequest { + /** The query without surrounding whitespace; never empty. */ + readonly query: string + /** The paths of the enabled exclusion rules, in list order, as `search-rules.ts` defines them. */ + readonly excludedPaths: readonly string[] + /** Whether hidden entries may match: names starting with `.`, and on a Windows Host also entries with the hidden file attribute. */ + readonly includeHidden: boolean + /** Whether entries the workspace's `.gitignore` files ignore are left out. */ + readonly respectGitignore: boolean +} + +/** One settled search's matches. */ +export interface WorkspaceSearchAnswer { + /** The matches, in the Host's order. */ + readonly matches: readonly SearchMatch[] + /** The Host returned only its first matches because more matched than it returns. */ + readonly truncated: boolean + /** + * Part of the workspace was not searched: the Host's search passed its file + * limit, or a directory could not be read. + */ + readonly incomplete: boolean +} + +/** + * One workspace search. The session travels with the call because the Host + * resolves the workspace root from it. A failure settles the result's error + * branch; aborting `signal` lets the caller drop the answer. + * @param sessionId - Session whose workspace is searched. + * @param request - the query and the preferences it follows. + * @param signal - the search's lifetime; the face aborts it when a newer search or the end of the search replaces it. + * @returns the matches, or why the Host could not search. + */ +export type SearchWorkspace = ( + sessionId: SessionId, + request: WorkspaceSearchRequest, + signal: AbortSignal, +) => Promise> + +/** + * The slice of the Client Remote face the search calls: the `workspaceFiles` + * namespace's `search`, exactly as the Host's generated client declares it. + */ +export type WorkspaceFilesSearchRemote = { + readonly workspaceFiles: Pick +} + +/** + * Bind the workspace search to one Remote face. + * @param remote - the Client Remote face carrying the `workspaceFiles` namespace. + * @returns the search the tree's face performs. + */ +export function createSearch(remote: WorkspaceFilesSearchRemote): SearchWorkspace { + return (sessionId, request, signal) => remote.workspaceFiles.search(sessionId, request, signal) +} diff --git a/packages/client/ui-sidebar-files/src/client/store.ts b/packages/client/ui-sidebar-files/src/client/store.ts index 182a142208..0019d90636 100644 --- a/packages/client/ui-sidebar-files/src/client/store.ts +++ b/packages/client/ui-sidebar-files/src/client/store.ts @@ -1,11 +1,12 @@ /** * The file tree's view state, one record per right-Sidebar pane: which - * directories are expanded, what each loaded level contains, and how the - * navigator is shown. A Slot-standard exclusive store (one instance per - * Session) keyed by pane, so every file tab of a pane draws the same tree; - * the face decides when a pane's record is forgotten (`FilesInjected.attach`). - * Beside it live pure reads shared by the face and the drawings: path keys, - * where a tab's file sits in the listed tree, and the navigator's geometry. + * directories are expanded, what each loaded level contains, how the + * navigator is shown, and the pane's search. A Slot-standard exclusive store + * (one instance per Session) keyed by pane, so every file tab of a pane draws + * the same tree; the face decides when a pane's record is forgotten + * (`FilesInjected.attach`). Beside it live pure reads shared by the face and + * the drawings: path keys, where a tab's file sits in the listed tree, and the + * navigator's geometry. */ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' @@ -98,7 +99,50 @@ export interface FilesTreeState { expanded: string[] } -/** One pane's navigator: whether and how wide it is shown, and its tree once started. */ +/** + * One settled search, as the pane draws it instead of the tree: the matches, + * or why the Host could not search. + */ +export type FilesSearchResult = + | { + readonly kind: 'found' + /** The trimmed query the search answered, which the rows highlight. */ + readonly query: string + /** The matches as a tree; its `expanded` is the search's own and starts with every level. */ + readonly tree: FilesTreeState + /** How many entries the search returned. */ + readonly count: number + /** More entries matched than the Host returns, so only its first `count` are drawn. */ + readonly truncated: boolean + /** + * Part of the workspace was not searched: the Host's search passed its file + * limit, or a directory could not be read. + */ + readonly incomplete: boolean + /** Whether the search was asked to leave out hidden entries; it does not say that any were. */ + readonly hiddenLeftOut: boolean + /** Whether the search was given at least one enabled exclusion rule; it does not say that a rule matched. */ + readonly excluded: boolean + /** Whether the search was asked to respect ignore files; it does not say that one ignored anything. */ + readonly ignored: boolean + } + | { + readonly kind: 'failed' + /** The trimmed query the failed search asked for. */ + readonly query: string + /** Why the Host could not search. */ + readonly failure: RemoteFailure + } + +/** One pane's search while its query is not blank. */ +export interface FilesSearchState { + /** A search is running; the last settled result stays drawn until its answer replaces it. */ + readonly pending: boolean + /** The last settled search; `undefined` until the pane's first search settles. */ + readonly result: FilesSearchResult | undefined +} + +/** One pane's navigator: whether and how wide it is shown, its tree once started, and its search. */ export interface FilesPaneState { /** * Whether a preview's navigator is shown; `undefined`, hidden, until the @@ -109,6 +153,12 @@ export interface FilesPaneState { width: number /** The tree, listed once the navigator is first shown. */ tree: FilesTreeState | undefined + /** The search field's text, as typed; not persisted. */ + query: string + /** Whether the files page draws its search bar; hiding it retains the query and results. */ + searchBarOpen: boolean + /** The pane's search, which the navigator draws instead of the tree; `undefined` while the query is blank. */ + search: FilesSearchState | undefined } /** Every pane's navigator, keyed by pane id. */ @@ -216,7 +266,7 @@ function underRoot(path: string, root: string): string | undefined { * @returns the pane's record. */ function pane(state: FilesState, paneId: PaneId): FilesPaneState { - state.byPane[paneId] ??= { open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, tree: undefined } + state.byPane[paneId] ??= { open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, tree: undefined, query: '', searchBarOpen: false, search: undefined } return state.byPane[paneId] } @@ -242,8 +292,13 @@ type FilesActions = { failed: (draft: FilesState, paneId: PaneId, path: string, failure: RemoteFailure) => void toggled: (draft: FilesState, paneId: PaneId, path: string) => void shown: (draft: FilesState, paneId: PaneId, open: boolean) => void + searchBarShown: (draft: FilesState, paneId: PaneId, open: boolean) => void resized: (draft: FilesState, paneId: PaneId, width: number) => void forget: (draft: FilesState, paneId: PaneId) => void + queried: (draft: FilesState, paneId: PaneId, query: string) => void + searching: (draft: FilesState, paneId: PaneId) => void + searched: (draft: FilesState, paneId: PaneId, result: FilesSearchResult) => void + searchToggled: (draft: FilesState, paneId: PaneId, path: string) => void } /** @@ -344,6 +399,13 @@ export function createFilesStore(): EngineStoreHandle * @param open - whether the navigator is shown. */ shown: (d, paneId: PaneId, open: boolean) => { pane(d, paneId).open = open }, + /** + * Show or hide the files page's search bar without changing its search. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param open - whether the search bar is shown. + */ + searchBarShown: (d, paneId: PaneId, open: boolean) => { pane(d, paneId).searchBarOpen = open }, /** * Record one pane's navigator width preference. * @param d - draft state. @@ -359,6 +421,55 @@ export function createFilesStore(): EngineStoreHandle forget: (d, paneId: PaneId) => { d.byPane = Object.fromEntries(Object.entries(d.byPane).filter(([id]) => id !== paneId)) }, + /** + * Record the search field's text. A blank query ends the search, and the + * pane draws its tree again; otherwise the last result stays drawn until + * the next is recorded. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param query - the text as typed. + */ + queried: (d, paneId: PaneId, query: string) => { + const state = pane(d, paneId) + state.query = query + if (query.trim() === '') state.search = undefined + }, + /** + * Record that a search started, keeping the last result drawn; ignored while the query is blank. + * @param d - draft state. + * @param paneId - the pane being drawn. + */ + searching: (d, paneId: PaneId) => { + const state = d.byPane[paneId] + const result = state?.search?.result + if (state !== undefined && state.query.trim() !== '') { + state.search = { pending: true, result: result?.kind === 'failed' ? undefined : result } + } + }, + /** + * Record a search's result, ending the pending search; ignored while the query is blank. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param result - what the search found, or why it failed. + */ + searched: (d, paneId: PaneId, result: FilesSearchResult) => { + const state = d.byPane[paneId] + if (state !== undefined && state.query.trim() !== '') state.search = { pending: false, result } + }, + /** + * Open a collapsed directory of the search's tree, or collapse an open + * one; the listed tree's expansion stays as it was. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param path - absolute directory path. + */ + searchToggled: (d, paneId: PaneId, path: string) => { + const result = d.byPane[paneId]?.search?.result + if (result?.kind !== 'found') return + const at = result.tree.expanded.indexOf(path) + if (at >= 0) result.tree.expanded.splice(at, 1) + else result.tree.expanded.push(path) + }, }, }) } diff --git a/packages/client/ui-sidebar-files/src/client/workspace-tree.ts b/packages/client/ui-sidebar-files/src/client/workspace-tree.ts index 80eb21ae98..fe43fe1286 100644 --- a/packages/client/ui-sidebar-files/src/client/workspace-tree.ts +++ b/packages/client/ui-sidebar-files/src/client/workspace-tree.ts @@ -8,12 +8,17 @@ * key drops its trailing separators too, so `/` becomes the empty key and a * Windows drive root `C:\` becomes `C:`, and a top-level child's key still * ends at its parent's last `/`. + * + * Unless the reader shows them, hidden entries are left out, and a directory + * whose every entry is hidden says so. The same conversion draws a search's + * results, whose directories hold only the matches. */ import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import type { TreeDirectoryState, TreeEntry } from './FileTree.tsx' import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import type {} from './locales.ts' -import { childPath, type FilesTreeState } from './store.ts' +import { isHiddenEntry } from './search-rules.ts' +import { childPath, type DirLevel, type FilesTreeState } from './store.ts' /** * Say why a directory could not be listed, in terms of the directory. @@ -52,27 +57,48 @@ export function parentOf(tree: FilesTreeState, path: string): string { return parent === treeRootOf(tree.root) ? tree.root : parent } +/** + * A listing's entries as drawn. + * @param level - one ready listing. + * @param showHidden - whether hidden entries are drawn. + * @returns the entries, without hidden ones unless they are shown. + */ +function drawnEntries(level: DirLevel, showHidden: boolean): DirLevel['entries'] { + return showHidden ? level.entries : level.entries.filter(entry => !isHiddenEntry(entry)) +} + /** * Every listed entry of a pane's tree, collapsed levels included, each named - * as its listing spells it. + * as its listing spells it. Unless hidden entries are drawn, the kept levels + * below a hidden directory are left out with it, so a directory listed while + * hidden entries were shown is not drawn again through its descendants. * @param levels - the pane's level states. + * @param showHidden - whether hidden entries are drawn. * @returns the entries keyed as the tree draws them. */ -export function workspaceEntries(levels: FilesTreeState['levels']): TreeEntry[] { - return Object.entries(levels).flatMap(([path, level]) => level.kind !== 'ready' ? [] : level.level.entries - .map(entry => ({ path: childPath(path, entry.name), name: entry.name, meta: { kind: entry.type } }))) +export function workspaceEntries(levels: FilesTreeState['levels'], showHidden: boolean): TreeEntry[] { + const ready = Object.entries(levels).flatMap(([path, level]) => level.kind === 'ready' ? [{ path, level: level.level }] : []) + const hiddenPrefixes = showHidden ? [] : ready.flatMap(({ path, level }) => level.entries + .filter(entry => entry.type === 'directory' && isHiddenEntry(entry)).map(entry => childPath(childPath(path, entry.name), ''))) + return ready + .filter(({ path }) => !hiddenPrefixes.some(prefix => `${path}/`.startsWith(prefix))) + .flatMap(({ path, level }) => drawnEntries(level, showHidden) + .map(entry => ({ path: childPath(path, entry.name), name: entry.name, meta: { kind: entry.type } }))) } /** * Each directory's listing state: loading until its first listing settles, then - * its latest failure and whether its listing is truncated. + * its latest failure, whether its listing is truncated, and whether it holds + * only hidden entries that are not drawn. * @param tree - the pane's root, level states, and expanded directories. * @param t - namespace-bound translate, for failure lines. + * @param showHidden - whether hidden entries are drawn. * @returns the states keyed as the tree draws them. */ export function workspaceDirectories( tree: Pick, t: TranslateNS<'sidebarFiles'>, + showHidden: boolean, ): Record { const { root, levels, expanded } = tree const directories: Record = {} @@ -83,11 +109,23 @@ export function workspaceDirectories( if (level.kind === 'loading') directories[key] = { loading: true } else if (level.kind === 'failed') directories[key] = { failure: failureLine(t, level.failure) } else { - const state: { failure?: string; truncated?: true } = {} + const state: { failure?: string; truncated?: true; omitted?: 'hidden' } = {} if (level.failure !== undefined) state.failure = failureLine(t, level.failure) if (level.level.truncated) state.truncated = true + if (level.level.entries.length > 0 && drawnEntries(level.level, showHidden).length === 0) state.omitted = 'hidden' directories[key] = state } } return directories } + +/** + * Each directory of a search's results, which holds only the matches below it, + * so a matched directory without matched descendants draws no empty line. + * @param tree - the results as a tree. + * @returns the states keyed as the tree draws them. + */ +export function searchDirectories(tree: Pick): Record { + return Object.fromEntries(Object.keys(tree.levels) + .map(path => [path === tree.root ? treeRootOf(path) : path, { omitted: 'unmatched' } as const])) +} diff --git a/packages/client/ui-sidebar-files/tests/face.client.spec.ts b/packages/client/ui-sidebar-files/tests/face.client.spec.ts index 8502a8d348..15542328af 100644 --- a/packages/client/ui-sidebar-files/tests/face.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/face.client.spec.ts @@ -10,6 +10,7 @@ import { childPath } from '../src/client/store.ts' import { createFilesStore } from '../src/client/store.ts' import type { DirLevel } from '../src/client/store.ts' import { DirectoryNode } from '../src/client/directory-node.ts' +import { memoryBook, scriptedSearch } from './search-fixture.client.ts' import { scriptedList } from './scripted-list.client.ts' import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' @@ -29,7 +30,7 @@ function mount() { const script = scriptedList() /** The tabs the face placed itself beside, with each placement's release. */ const placed: { readonly tabId: TabId; readonly face: FilesInjected; readonly release: Mock<() => void> }[] = [] - const face = filesFace(script.list, script.watch, CAN_OPEN, () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }))(SESSION, instance, (tabId, bound) => { + const face = filesFace(script.list, script.watch, CAN_OPEN, () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }), scriptedSearch().search, memoryBook())(SESSION, instance, (tabId, bound) => { const release = vi.fn<() => void>() placed.push({ tabId, face: bound, release }) return release @@ -228,11 +229,15 @@ describe('filesFace', () => { onTestFinished(() => { tab.abort() }) face.attach(moved, 'tab-moved' as TabId, tab.signal) expect(instance.getSnapshot().byPane[moved]?.open).toBe(true) - // The tree drawn there next takes the keyboard. + expect(instance.getSnapshot().byPane[moved]?.searchBarOpen).toBe(false) + // The search field drawn there next takes the keyboard, not the tree. const body = { scrollTop: 0, focus: vi.fn() } face.bodyDrawn(moved, `${ROOT}/a.ts`, body as Partial as HTMLElement) + const input = { focus: vi.fn() } + face.searchDrawn(moved, input as Partial as HTMLInputElement) await Promise.resolve() - expect(body.focus).toHaveBeenCalledTimes(1) + expect(body.focus).not.toHaveBeenCalled() + expect(input.focus).toHaveBeenCalledTimes(1) face.hide('pane-never' as PaneId) expect(instance.getSnapshot().byPane['pane-never' as PaneId]).toBeUndefined() }) diff --git a/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx b/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx index aaebe5e72b..c812f9a287 100644 --- a/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx @@ -288,3 +288,26 @@ describe('FileTree', () => { expect(currentRef).toHaveBeenLastCalledWith(null) }) }) + +describe('caller-narrowed entries', () => { + it('highlights each occurrence of the given text in a name, ignoring case', () => { + const { view } = draw({ entries: CHANGES, expanded: ['pr/src'], highlight: 'FILE' }) + const marks = [...view.container.querySelectorAll('mark')].map(mark => mark.textContent) + expect(marks).toEqual(['file', 'file']) + expect(row(view.container, 'pr/src/file2.ts').textContent).toBe('file2.ts') + expect(row(view.container, 'pr/README.md').querySelector('mark')).toBeNull() + }) + + it('says a directory left without entries holds hidden ones, or nothing for a selection', () => { + const entries: readonly TreeEntry[] = [ + { path: 'pr/hidden', name: 'hidden', meta: { kind: 'directory' } }, + { path: 'pr/unmatched', name: 'unmatched', meta: { kind: 'directory' } }, + ] + const { view } = draw({ + entries, expanded: ['pr/hidden', 'pr/unmatched'], + directories: { 'pr/hidden': { omitted: 'hidden' }, 'pr/unmatched': { omitted: 'unmatched' } }, + }) + const notes = [...view.container.querySelectorAll('[data-files-row]')].map(note => [note.getAttribute('data-files-row'), note.textContent]) + expect(notes).toEqual([['hidden-only', en.emptyHidden]]) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx b/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx index ddb3dd2dfa..2cd0aa3d5a 100644 --- a/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx @@ -6,9 +6,11 @@ import { makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import { fileAddressFor } from '@deepseek-ai/dsh-util-workspace-path' import { failureLine } from '../src/client/workspace-tree.ts' +import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { DirLevel } from '../src/client/store.ts' import { zh } from '../src/client/locales.ts' -import { mountBody, PANE, ROOT, SESSION } from './mount.client.tsx' +import { mountBody, PANE, ROOT, SESSION, TAB } from './mount.client.tsx' +import { answer, searchesSettled } from './search-fixture.client.ts' const ROOT_LEVEL: DirLevel = { entries: [ @@ -52,8 +54,10 @@ describe('FilesBody', () => { const header = page.firstElementChild! expect(header.querySelector('[data-files-path]')?.getAttribute('title')).toBe(ROOT) expect([...header.querySelectorAll('button:not([data-files-auto-refresh])')].map(button => button.getAttribute('aria-label'))) - .toEqual([zh.reload]) + .toEqual([zh.reload, zh['search.placeholder']]) const content = page.querySelector('[data-files-content]')! + // The filled layout's rule finds the row the navigator covers by this attribute. + expect(content.hasAttribute('data-files-navigator-row')).toBe(true) expect(content.children).toHaveLength(1) const navigator = content.firstElementChild! expect(navigator.getAttribute('data-files-navigator')).toBe(PANE) @@ -71,7 +75,122 @@ describe('FilesBody', () => { expect(typeof bound?.refresh).toBe('function') }) - it('lists the root on mount, heads it with its path split at the last segment, and draws directories first with dotfiles kept', async () => { + it('defers a files-page focus request until its pane attaches without changing the preview-tree choice', () => { + const h = mountBody() + const paneId = 'pane-before-attach' as PaneId + const navigator = document.createElement('aside') + h.view.container.append(navigator) + const controller = new AbortController() + onTestFinished(() => { controller.abort() }) + h.face.navigatorDrawn(paneId, navigator, false) + h.face.focus(paneId) + expect(h.instance.getSnapshot().byPane[paneId]).toBeUndefined() + h.face.attach(paneId, 'tab-before-attach' as TabId, controller.signal) + expect(h.instance.getSnapshot().byPane[paneId]).toMatchObject({ open: undefined, searchBarOpen: true }) + h.face.navigatorDrawn(paneId, null, false) + navigator.remove() + }) + + it('starts with the search bar collapsed and retains the query and results through collapse and remount', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(h.beside(TAB)).toBe(true) + await act(async () => { fireEvent.click(toggle) }) + const input = h.view.container.querySelector('[data-files-search]')! + expect(document.activeElement).toBe(input) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(h.instance.getSnapshot().byPane[PANE]?.open).toBeUndefined() + h.searches.answerWith(answer(['src/target.ts'])) + await act(async () => { + fireEvent.change(input, { target: { value: 'target' } }) + await searchesSettled() + }) + const search = h.instance.getSnapshot().byPane[PANE]!.search + const body = h.view.container.querySelector('[data-files-body]')! + expect(body.getAttribute('data-files-view')).toBe('search') + expect(names(h.view.container)).toContain(`${ROOT}/src/target.ts`) + fireEvent.click(toggle) + expect(document.activeElement).toBe(toggle) + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(h.instance.getSnapshot().byPane[PANE]!.query).toBe('target') + expect(h.instance.getSnapshot().byPane[PANE]!.search).toBe(search) + expect(h.view.container.querySelector('[data-files-body]')).toBe(body) + h.view.unmount() + const back = h.remount() + expect(back.queryByRole('searchbox')).toBeNull() + expect(names(back.container)).toContain(`${ROOT}/src/target.ts`) + await act(async () => { fireEvent.click(back.getByRole('button', { name: zh['search.placeholder'] })) }) + expect(back.container.querySelector('[data-files-search]')?.value).toBe('target') + expect(h.search).toHaveBeenCalledTimes(1) + }) + + it('keeps focus in the tree when Escape clears results while the search bar is collapsed', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + h.searches.answerWith(answer(['src/target.ts'])) + await act(async () => { + fireEvent.change(h.view.getByRole('searchbox'), { target: { value: 'target' } }) + await searchesSettled() + }) + fireEvent.click(toggle) + const result = h.view.container.querySelector(`[data-files-path="${ROOT}/src/target.ts"] button`)! + result.focus() + await act(async () => { fireEvent.keyDown(result, { key: 'Escape' }) }) + const body = h.view.container.querySelector('[data-files-body]')! + expect(body.getAttribute('data-files-view')).toBe('tree') + expect(h.instance.getSnapshot().byPane[PANE]!.query).toBe('') + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(document.activeElement).toBe(body) + }) + + it('keeps a search running and draws its answer while the search bar is collapsed', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + h.searches.answerWith(undefined) + fireEvent.change(h.view.getByRole('searchbox'), { target: { value: 'target' } }) + const running = h.searches.started[0]! + fireEvent.click(toggle) + expect(running.signal.aborted).toBe(false) + expect(h.view.container.querySelector('[data-files-body]')?.getAttribute('aria-busy')).toBe('true') + await act(async () => { + running.settle(answer(['src/target.ts'])) + await searchesSettled() + }) + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(names(h.view.container)).toContain(`${ROOT}/src/target.ts`) + expect(h.view.container.querySelector('[data-files-body]')?.getAttribute('aria-busy')).toBe('false') + await act(async () => { h.face.focus(PANE) }) + expect(h.view.container.querySelector('[data-files-search]')?.value).toBe('target') + expect(document.activeElement).toBe(h.view.getByRole('searchbox')) + expect(h.search).toHaveBeenCalledTimes(1) + }) + + it('closes search settings when the toolbar collapses the search bar', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + fireEvent.click(h.view.getByRole('button', { name: zh['search.settings'] })) + expect(h.view.queryByRole('dialog')).not.toBeNull() + fireEvent.click(toggle) + expect(h.view.queryByRole('dialog')).toBeNull() + await act(async () => { fireEvent.click(toggle) }) + expect(h.view.queryByRole('dialog')).toBeNull() + }) + + it('lists the root on mount, heads it with its path split at the last segment, and draws directories first with dotfiles shown once the reader asks', async () => { const { view, script } = mountBody() expect(script.list).not.toHaveBeenCalled() await act(() => script.watches.ready(ROOT)) @@ -82,6 +201,9 @@ describe('FilesBody', () => { const path = view.container.querySelector('[data-files-path]') expect(path?.getAttribute('title')).toBe(ROOT) expect([...path?.firstElementChild?.children ?? []].map(span => span.textContent)).toEqual(['/work/', 'app']) + expect(names(view.container)).toEqual([`${ROOT}/src`, `${ROOT}/pipe`, `${ROOT}/README.md`]) + await act(async () => { fireEvent.click(view.getByRole('button', { name: zh['search.placeholder'] })) }) + act(() => { fireEvent.click(view.getByRole('button', { name: zh['search.showHidden'] })) }) expect(names(view.container)).toEqual([`${ROOT}/src`, `${ROOT}/.env`, `${ROOT}/pipe`, `${ROOT}/README.md`]) const envIcon = view.container.querySelector(`[data-files-path="${ROOT}/.env"] svg`)?.innerHTML const readmeIcon = view.container.querySelector(`[data-files-path="${ROOT}/README.md"] svg`)?.innerHTML @@ -94,7 +216,7 @@ describe('FilesBody', () => { await act(() => script.settle({ ok: true, value: ROOT_LEVEL })) const path = view.container.querySelector('[data-files-path]') expect([...path?.firstElementChild?.children ?? []].map(span => span.textContent)).toEqual(['/']) - expect(names(view.container)).toEqual(['/src', '/.env', '/pipe', '/README.md']) + expect(names(view.container)).toEqual(['/src', '/pipe', '/README.md']) }) it('marks the root path clipped while its text is wider than its box, re-reading on resize', async () => { diff --git a/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx b/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx index baaa8e2d53..60bb8667f7 100644 --- a/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx @@ -610,6 +610,17 @@ describe('FileNavigator beside a preview', () => { expect(document.activeElement).toBe(document.body) }) + it('carries keyboard focus on the tree\'s scroll container, with no current row, to the next drawing', async () => { + const h = mountNavigator('sidebar://files') + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + act(() => { h.view.container.querySelector('[data-files-body]')!.focus() }) + h.view.unmount() + const back = h.remount() + await endTask() + expect(document.activeElement).toBe(back.container.querySelector('[data-files-body]')) + }) + it('gives the carried focus to the drawing in place when the task ends, after the tab draws the tree again', async () => { const h = mountNavigator(A) await revealSrc(h) @@ -629,15 +640,15 @@ describe('FileNavigator beside a preview', () => { expect(document.activeElement).toBe(document.body) }) - it('takes keyboard focus when asked, at its next drawing or at once', async () => { + it('gives its search field keyboard focus when asked, at its next drawing or at once', async () => { const h = mountNavigator('sidebar://files') act(() => { h.face.focus(PANE) }) await act(() => h.script.watches.ready(ROOT)) - expect(document.activeElement?.hasAttribute('data-files-body')).toBe(true) + expect(document.activeElement).toBe(h.view.getByRole('searchbox', { name: zh['search.placeholder'] })) act(() => { (document.activeElement as HTMLElement).blur() }) act(() => { h.face.focus(PANE) }) await endTask() - expect(document.activeElement?.hasAttribute('data-files-body')).toBe(true) + expect(document.activeElement).toBe(h.view.getByRole('searchbox', { name: zh['search.placeholder'] })) }) it('keeps the pane\'s tree when a preview is replaced in place by the file it opened', async () => { diff --git a/packages/client/ui-sidebar-files/tests/mount.client.tsx b/packages/client/ui-sidebar-files/tests/mount.client.tsx index 35a660f264..32a4cc14aa 100644 --- a/packages/client/ui-sidebar-files/tests/mount.client.tsx +++ b/packages/client/ui-sidebar-files/tests/mount.client.tsx @@ -27,10 +27,12 @@ import { FilesBody } from '../src/client/FilesBody.tsx' import type { FilesBodyProps } from '../src/client/FilesBody.tsx' import { NavigatorToggle } from '../src/client/NavigatorToggle.tsx' import { zh } from '../src/client/locales.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' import { createFilesStore } from '../src/client/store.ts' import type { FilesStoreInstance } from '../src/client/store.ts' import { scriptedList } from './scripted-list.client.ts' import type { ScriptedList } from './scripted-list.client.ts' +import { memoryBook, scriptedSearch, type ScriptedSearch } from './search-fixture.client.ts' export const SESSION = 's-test' as SessionId export const ROOT = '/work/app' @@ -71,6 +73,12 @@ export interface Mounted { readonly view: RenderResult readonly instance: FilesStoreInstance readonly script: ScriptedList + /** The search the face calls; it matches nothing until a spec gives it matches. */ + readonly search: ScriptedSearch['search'] + /** That search's script: the searches it started, and how it answers later ones. */ + readonly searches: ScriptedSearch + /** The search preferences of every workspace, which another mount may share. */ + readonly book: WorkspaceSearchPreferenceBook readonly face: FilesInjected /** The first tab's lifetime. */ readonly controller: AbortController @@ -93,9 +101,11 @@ export interface Mounted { } /** One store instance, one face, one owner share. */ -function harness(placement: Placement, controller: AbortController) { +function harness(placement: Placement, controller: AbortController, book: WorkspaceSearchPreferenceBook) { const instance = createFilesStore().create() const script = scriptedList() + const searches = scriptedSearch() + const search = searches.search // Whether some tab type opens files: one predicate per answer, as registrations change it. const listeners = new Set<() => void>() let check = (_address: string): boolean => true @@ -115,7 +125,7 @@ function harness(placement: Placement, controller: AbortController) { // The owner's count of drawings that placed the face beside each tab. const placed = new Map() const navigation = createSnapshotStore({ address: placement.contentId, params: undefined, revision: 0 }) - const face = filesFace(script.list, script.watch, canOpen, () => navigation)(SESSION, instance, (tabId) => { + const face = filesFace(script.list, script.watch, canOpen, () => navigation, search, book)(SESSION, instance, (tabId) => { placed.set(tabId, (placed.get(tabId) ?? 0) + 1) return () => { placed.set(tabId, placed.get(tabId)! - 1) } }) @@ -164,9 +174,13 @@ function harness(placement: Placement, controller: AbortController) { }, useCanOpen: (sel: (check: (address: string) => boolean) => S) => sel(useSyncExternalStore(listener => hooks.canOpen.subscribe(listener), () => hooks.canOpen.getSnapshot())), + useSearchPreferences: (cwd: string) => { + const source = keyedHooks.searchPreferences(cwd) + return useSyncExternalStore(listener => source.subscribe(listener), () => source.getSnapshot()) + }, t, } - return { instance, script, face, controller, viewers, tabActions, onOpen, beside, shared } + return { instance, script, search, searches, book, face, controller, viewers, tabActions, onOpen, beside, shared } } /** @@ -278,16 +292,18 @@ function bodyProps(shared: object): FilesBodyProps { * @param placement - the tab's address, the pane's presentation, and the session's working directory. * @param draw - the drawing over the shared props. * @param recordObservers - capture navigator measurement notifications. + * @param book - the search preferences, shared with another mount when given. * @returns the mounted hands. */ function mount( given: Omit, draw: (shared: ReturnType['shared']) => ReactNode, recordObservers = false, + book: WorkspaceSearchPreferenceBook = memoryBook(), ): Mounted { const controller = new AbortController() const placement: Placement = { ...given, tabId: TAB, signal: controller.signal } - const { shared, ...hands } = harness(placement, controller) + const { shared, ...hands } = harness(placement, controller, book) const { row, viewport } = measureRows(recordObservers) const element = (): ReactNode =>
    {draw(shared)}
    const view = render(element()) @@ -319,9 +335,15 @@ export function mountBody(cwd: string | null = ROOT, placement: Partial = {}, cwd: string | null = ROOT): Mounted { +export function mountNavigator( + contentId: string, + placement: Partial = {}, + cwd: string | null = ROOT, + book?: WorkspaceSearchPreferenceBook, +): Mounted { return mount({ contentId, ...placement, cwd }, shared => ( <> @@ -330,5 +352,5 @@ export function mountNavigator(contentId: string, placement: Partial
    - ), true) + ), true, book) } diff --git a/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx b/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx index 7aee76c1fc..06aec36122 100644 --- a/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx @@ -9,7 +9,9 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import { filesFace } from '../src/client/face.ts' import type { ListWorkspaceDirectory, WatchWorkspaceDirectory } from '../src/client/face.ts' +import type { SearchWorkspace } from '../src/client/search-workspace.ts' import { createFilesStore } from '../src/client/store.ts' +import { memoryBook } from './search-fixture.client.ts' const SESSION = 'navigation-session' as SessionId const LEFT = 'pane-left' as PaneId @@ -73,7 +75,7 @@ function harness() { return () => { unsubscribe(); tab.listeners.delete(listener) } }, } - })(SESSION, instance, () => () => {}) + }, vi.fn(() => { throw new Error('Navigation must not search') }), memoryBook())(SESSION, instance, () => () => {}) const tab = (id: TabId, revision = 0): TestTab => { const address = sessionFileAddress(SESSION, `${id}.ts`) diff --git a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts new file mode 100644 index 0000000000..2436eac12e --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts @@ -0,0 +1,224 @@ +/** The face's search: when it runs, the preferences it follows, what it aborts and drops, and the store writes it makes. */ +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { filesFace } from '../src/client/face.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' +import { defaultSearchPreferences, enabledPaths } from '../src/client/search-rules.ts' +import { createSearch } from '../src/client/search-workspace.ts' +import type { WorkspaceFilesSearchRemote } from '../src/client/search-workspace.ts' +import { createFilesStore } from '../src/client/store.ts' +import { scriptedList } from './scripted-list.client.ts' +import { answer, memoryBook, scriptedSearch, searchesSettled } from './search-fixture.client.ts' + +const ROOT = '/work/app' +const PANE = 'pane-1' as PaneId +const CAN_OPEN = { getSnapshot: () => () => true, subscribe: () => () => {} } +/** No tab navigates. */ +const NO_NAVIGATION = () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }) + +/** One Session's face over a shared book, with its pane attached. */ +function session(id: string, book: WorkspaceSearchPreferenceBook) { + const instance = createFilesStore().create() + const script = scriptedList() + const searches = scriptedSearch(['src/a.ts']) + const face = filesFace(script.list, script.watch, CAN_OPEN, NO_NAVIGATION, searches.search, book)( + id as SessionId, instance, () => () => {}, + ) + const tab = new AbortController() + const release = face.attach(PANE, 'tab-1' as TabId, tab.signal) + onTestFinished(async () => { + release() + tab.abort() + await script.dispose() + }) + return { + instance, searches, search: searches.search, face, release, tab, + state: () => instance.getSnapshot().byPane[PANE]?.search, + result: () => instance.getSnapshot().byPane[PANE]?.search?.result, + } +} + +describe('the face\'s search', () => { + it('searches nothing for a pane no navigator attached', () => { + const h = session('s-1', memoryBook()) + h.face.setQuery('pane-2' as PaneId, ROOT, 'a') + h.face.retrySearch('pane-2' as PaneId) + expect(h.search).not.toHaveBeenCalled() + expect(h.instance.getSnapshot().byPane['pane-2' as PaneId]).toBeUndefined() + // A search field that goes after its pane was forgotten leaves nothing to record. + h.face.searchDrawn('pane-2' as PaneId, null) + expect(h.instance.getSnapshot().byPane['pane-2' as PaneId]).toBeUndefined() + }) + + it('asks the Host with the trimmed query and the workspace\'s preferences, pending until the answer draws the matches as a tree', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, ' a ') + expect(h.search).toHaveBeenCalledExactlyOnceWith('s-1', { + query: 'a', excludedPaths: enabledPaths(defaultSearchPreferences().rules), includeHidden: false, respectGitignore: true, + }, expect.any(AbortSignal)) + expect(h.state()).toEqual({ pending: true, result: undefined }) + h.searches.started[0]!.settle(answer(['src/a.ts'], { truncated: true, incomplete: true })) + await searchesSettled() + expect(h.state()?.pending).toBe(false) + expect(h.result()).toMatchObject({ + kind: 'found', query: 'a', count: 1, truncated: true, incomplete: true, hiddenLeftOut: true, excluded: true, + tree: { expanded: [ROOT, `${ROOT}/src`] }, + }) + // Whitespace around the same text searches nothing new. + h.face.setQuery(PANE, ROOT, 'a') + expect(h.search).toHaveBeenCalledOnce() + expect(h.instance.getSnapshot().byPane[PANE]?.query).toBe('a') + }) + + it('aborts the running search when a newer one starts, keeping the last result drawn and dropping the older answer', async () => { + const h = session('s-1', memoryBook()) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + const first = h.result() + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'ab') + h.face.setQuery(PANE, ROOT, 'abc') + const [, older, newer] = h.searches.started + expect(older?.signal.aborted).toBe(true) + expect(newer?.signal.aborted).toBe(false) + expect(h.state()).toEqual({ pending: true, result: first }) + // The newer answer draws; the older one, arriving later, is dropped. + newer!.settle(answer(['abc.ts'])) + await searchesSettled() + older!.settle(answer(['ab.ts'])) + await searchesSettled() + expect(h.result()).toMatchObject({ query: 'abc', count: 1 }) + expect(h.state()?.pending).toBe(false) + }) + + it('aborts a running search when the query is cleared or the pane is forgotten, and writes nothing for it', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'a') + const cleared = h.searches.started[0]! + h.face.setQuery(PANE, ROOT, '') + expect(cleared.signal.aborted).toBe(true) + // Typing the same text again searches anew, and the dropped answer does not draw. + h.face.setQuery(PANE, ROOT, 'a') + cleared.settle(answer(['old.ts'])) + await searchesSettled() + expect(h.state()).toEqual({ pending: true, result: undefined }) + + const running = h.searches.started[1]! + h.release() + h.tab.abort() + await searchesSettled() + expect(running.signal.aborted).toBe(true) + running.settle(answer(['late.ts'])) + await searchesSettled() + expect(h.instance.getSnapshot().byPane[PANE]).toBeUndefined() + }) + + it('records a failed search as a failure, and searches again on retry', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'a') + const failure = new RemoteError('gateway/internal', 'host is gone', {}) + h.searches.started[0]!.settle({ ok: false, error: failure }) + await searchesSettled() + expect(h.state()).toEqual({ pending: false, result: { kind: 'failed', query: 'a', failure } }) + h.face.retrySearch(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + // A failure belongs to the query that failed, so a new search drops it instead of drawing it beside the spinner. + expect(h.state()).toEqual({ pending: true, result: undefined }) + // A rejected call, which only an assembly fault causes, is reported rather than left pending. + h.searches.started[1]!.reject(new Error('no search method')) + await searchesSettled() + expect(h.state()).toMatchObject({ + pending: false, result: { kind: 'failed', query: 'a', failure: { code: 'gateway/internal', message: 'no search method' } }, + }) + h.face.retrySearch(PANE) + h.searches.started[2]!.reject('refused') + await searchesSettled() + expect(h.result()).toMatchObject({ kind: 'failed', failure: { message: 'refused' } }) + // Without a query there is nothing to retry. + h.face.setQuery(PANE, ROOT, '') + h.face.retrySearch(PANE) + expect(h.search).toHaveBeenCalledTimes(3) + }) + + it('searches again on refresh while the pane has a query, and not once the query is blank', async () => { + const h = session('s-1', memoryBook()) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + expect(h.search).toHaveBeenCalledTimes(1) + h.face.refresh(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + expect(h.search).toHaveBeenLastCalledWith('s-1', expect.objectContaining({ query: 'a' }), expect.anything()) + h.face.setQuery(PANE, ROOT, '') + h.face.refresh(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + }) + + it('follows one workspace\'s preferences, shared by every Session rooted there, until the query is blank', async () => { + const book = memoryBook() + const one = session('s-1', book) + const two = session('s-2', book) + const elsewhere = session('s-3', book) + expect(two.face.keyedHooks.searchPreferences(ROOT)).toBe(one.face.keyedHooks.searchPreferences(`${ROOT}/`)) + two.face.setQuery(PANE, ROOT, 'a') + elsewhere.face.setQuery(PANE, '/work/other', 'a') + const before = one.face.keyedHooks.searchPreferences('/work/other').getSnapshot() + one.face.setSearchPreferences(ROOT, { rules: [], showHidden: true }) + expect(two.search).toHaveBeenLastCalledWith( + 's-2', { query: 'a', excludedPaths: [], includeHidden: true, respectGitignore: true }, expect.any(AbortSignal), + ) + await searchesSettled() + expect(two.result()).toMatchObject({ hiddenLeftOut: false, excluded: false }) + expect(elsewhere.search).toHaveBeenCalledOnce() + expect(one.face.keyedHooks.searchPreferences('/work/other').getSnapshot()).toBe(before) + // The `.gitignore` choice is a preference like the others. + one.face.setSearchPreferences(ROOT, { respectGitignore: false }) + expect(two.search).toHaveBeenLastCalledWith('s-2', expect.objectContaining({ respectGitignore: false }), expect.any(AbortSignal)) + // A change to another root's entry leaves this root's search alone. + one.face.setSearchPreferences('/work/other', { ...defaultSearchPreferences(), rules: [] }) + expect(two.search).toHaveBeenCalledTimes(3) + + // A pane that moves to another root follows that root instead. + two.face.setQuery(PANE, '/work/other', 'a') + expect(two.search).toHaveBeenCalledTimes(4) + one.face.setSearchPreferences(ROOT, defaultSearchPreferences()) + expect(two.search).toHaveBeenCalledTimes(4) + + two.face.setQuery(PANE, '/work/other', ' ') + expect(two.state()).toBeUndefined() + one.face.setSearchPreferences('/work/other', { ...defaultSearchPreferences(), showHidden: true }) + expect(two.search).toHaveBeenCalledTimes(4) + }) + + it('does not search again when the listed levels change under shown results', async () => { + const h = session('s-1', memoryBook()) + h.instance.actions.start(PANE, ROOT) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + const shown = h.result() + h.instance.actions.loaded(PANE, ROOT, { entries: [{ name: 'src', type: 'directory' }], truncated: false }) + await searchesSettled() + expect(h.search).toHaveBeenCalledOnce() + expect(h.result()).toBe(shown) + }) +}) + +describe('createSearch', () => { + it('passes the session, the request, and the signal through, and returns the Host\'s answer or failure as it is', async () => { + const search = vi.fn() + const value = { matches: [{ path: 'src/a.ts', type: 'file' as const }], truncated: false, incomplete: true } + search.mockResolvedValueOnce({ ok: true, value }) + const request = { query: 'a', excludedPaths: ['dist'], includeHidden: false, respectGitignore: true } + const signal = new AbortController().signal + const bound = createSearch({ workspaceFiles: { search } }) + expect(await bound('s-1' as SessionId, request, signal)).toEqual({ ok: true, value }) + expect(search).toHaveBeenCalledWith('s-1', request, signal) + const error = new RemoteError('gateway/internal', 'down', {}) + search.mockResolvedValueOnce({ ok: false, error }) + expect(await bound('s-1' as SessionId, request, signal)).toEqual({ ok: false, error }) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-fixture.client.ts b/packages/client/ui-sidebar-files/tests/search-fixture.client.ts new file mode 100644 index 0000000000..2b7fc0c35d --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-fixture.client.ts @@ -0,0 +1,91 @@ +/** Scripted search answers and in-memory preferences for the search specs. */ +import { vi } from 'vitest' +import type { Mock } from 'vitest' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSearchPreferenceBook } from '../src/client/search-preferences.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' +import type { SearchMatch } from '../src/client/search-tree.ts' +import type { SearchWorkspace, WorkspaceSearchAnswer, WorkspaceSearchRequest } from '../src/client/search-workspace.ts' + +/** + * Matches as a search answers them. + * @param paths - matched paths, files unless they end with `/`. + * @returns the matches. + */ +export function found(paths: readonly string[]): SearchMatch[] { + return paths.map(path => path.endsWith('/') ? { path: path.slice(0, -1), type: 'directory' as const } : { path, type: 'file' as const }) +} + +/** Whether an answer is cut at the Host's match limit, or missed some directories. */ +export interface AnswerFlags { + readonly truncated?: boolean + readonly incomplete?: boolean +} + +/** + * A settled answer. + * @param paths - the matches, as {@link found} takes them. + * @param flags - whether the answer is truncated or incomplete; neither when omitted. + * @returns the answer. + */ +export function answer(paths: readonly string[], flags: AnswerFlags = {}): RemoteResult { + return { ok: true, value: { matches: found(paths), truncated: flags.truncated ?? false, incomplete: flags.incomplete ?? false } } +} + +/** One search the face started. */ +export interface StartedSearch { + /** What the face asked for. */ + readonly request: WorkspaceSearchRequest + /** The signal the face passed. */ + readonly signal: AbortSignal + /** Answer it, unless it is already answered. @param result - the answer. */ + readonly settle: (result: RemoteResult) => void + /** Reject it, as an assembly fault does. @param error - the rejection. */ + readonly reject: (error: unknown) => void +} + +/** A search the face calls: it answers at once with a fixed answer, or leaves each call open for the spec to settle. */ +export interface ScriptedSearch { + /** The mock the face receives. */ + readonly search: Mock + /** Every search started, oldest first. */ + readonly started: readonly StartedSearch[] + /** + * Answer every later search at once, or leave later searches open. + * @param result - the answer, or `undefined` to leave them open. + */ + readonly answerWith: (result: RemoteResult | undefined) => void +} + +/** + * A search that answers every request with the same matches until the spec + * changes them. + * @param paths - the matches, as {@link found} takes them. + * @returns the scripted search. + */ +export function scriptedSearch(paths: readonly string[] = []): ScriptedSearch { + const started: StartedSearch[] = [] + let fixed: RemoteResult | undefined = answer(paths) + const search = vi.fn((_sessionId, request, signal) => new Promise((resolve, reject) => { + started.push({ request, signal, settle: resolve, reject }) + if (fixed !== undefined) resolve(fixed) + })) + return { search, started, answerWith: (result) => { fixed = result } } +} + +/** + * Let settled searches reach the face: a search's answer takes two microtasks to be written. + * @returns once they have. + */ +export async function searchesSettled(): Promise { + for (let turn = 0; turn < 3; turn += 1) await Promise.resolve() +} + +/** + * A preference book over an in-memory store, as the plugin keeps one over browser storage. + * @returns the book. + */ +export function memoryBook(): WorkspaceSearchPreferenceBook { + return createSearchPreferenceBook(createSnapshotStore({})) +} diff --git a/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts new file mode 100644 index 0000000000..f093c16185 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts @@ -0,0 +1,119 @@ +// @vitest-environment jsdom +/** The workspace search preferences kept in browser storage, read back without trusting what storage holds. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSearchPreferenceBook, SEARCH_PREFERENCES_KEY, workspaceKey } from '../src/client/search-preferences.ts' +import { defaultSearchPreferences } from '../src/client/search-rules.ts' + +/** A book over browser storage, as the plugin's `apply` builds it. */ +function persisted() { + return createSearchPreferenceBook(createSnapshotStore({}, { persist: { name: SEARCH_PREFERENCES_KEY } })) +} +const stored = (): unknown => JSON.parse(localStorage.getItem(SEARCH_PREFERENCES_KEY) ?? 'null') + +afterEach(() => { + localStorage.clear() + vi.restoreAllMocks() +}) + +describe('workspaceKey', () => { + it.each([ + ['/work/app', '/work/app'], + ['/work/app/', '/work/app'], + ['/work/app//', '/work/app'], + ['/', '/'], + ['C:\\work\\', 'C:\\work'], + ['C:\\', 'C:\\'], + ['C:/', 'C:/'], + ['C:', 'C:'], + ])('keys %s as %s', (cwd, key) => { + expect(workspaceKey(cwd)).toBe(key) + }) +}) + +describe('createSearchPreferenceBook', () => { + it('writes only the roots the reader changed, and drops a root changed back to the defaults', () => { + const book = persisted() + const chosen = { rules: [{ path: 'out', enabled: false }], showHidden: true, respectGitignore: false } + book.update('/work/app/', chosen) + book.update('/work/lib', { ...defaultSearchPreferences(), showHidden: true }) + expect(stored()).toEqual({ '/work/app': chosen, '/work/lib': { showHidden: true } }) + expect(book.source('/work/app').getSnapshot()).toEqual(chosen) + book.update('/work/lib', defaultSearchPreferences()) + expect(stored()).toEqual({ '/work/app': chosen }) + expect(book.source('/work/never').getSnapshot()).toEqual(defaultSearchPreferences()) + }) + + it('changes only the fields a patch names, over the root\'s preferences at the time of the change', () => { + const book = persisted() + book.update('/work/app', { showHidden: true }) + book.update('/work/app', { rules: [{ path: 'out', enabled: true }] }) + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: true, respectGitignore: true }) + book.update('/work/app', { showHidden: false }) + book.update('/work/app', { respectGitignore: false }) + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: false, respectGitignore: false }) + // A `.gitignore` choice alone differs from the defaults, so only it is stored. + book.update('/work/app', { rules: defaultSearchPreferences().rules }) + expect(stored()).toEqual({ '/work/app': { respectGitignore: false } }) + }) + + it('leaves the rules out of an entry whose rules the reader did not change, so the running build\'s default list applies', () => { + persisted().update('/work/app', { showHidden: true }) + expect(stored()).toEqual({ '/work/app': { showHidden: true } }) + // An entry another build stored without rules reads the default list of this build. + localStorage.setItem(SEARCH_PREFERENCES_KEY, JSON.stringify({ '/work/app': { showHidden: true, respectGitignore: false } })) + expect(persisted().source('/work/app').getSnapshot()).toEqual({ ...defaultSearchPreferences(), showHidden: true, respectGitignore: false }) + }) + + it('keeps each root\'s snapshot until that root changes', () => { + const book = persisted() + const app = book.source('/work/app') + const first = app.getSnapshot() + expect(app.getSnapshot()).toBe(first) + const heard = vi.fn() + const stop = app.subscribe(heard) + book.update('/work/other', { rules: [], showHidden: false }) + expect(heard).toHaveBeenCalledTimes(1) + expect(app.getSnapshot()).toBe(first) + book.update('/work/app', { rules: [], showHidden: false }) + expect(app.getSnapshot()).not.toBe(first) + stop() + }) + + it('reads back what an earlier session stored, and the default for each missing or malformed field', () => { + localStorage.setItem(SEARCH_PREFERENCES_KEY, JSON.stringify({ + '/work/app': { rules: [{ path: 'out', enabled: true }, { path: '../x', enabled: true }], showHidden: true }, + '/work/lib': { rules: [], showHidden: false, respectGitignore: false }, + '/work/full': { ...defaultSearchPreferences(), showHidden: true }, + '/work/bad': { rules: 'dist', showHidden: true }, + '/work/odd': 7, + })) + const book = persisted() + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: true, respectGitignore: true }) + expect(book.source('/work/lib').getSnapshot()).toEqual({ rules: [], showHidden: false, respectGitignore: false }) + // Saving an entry that stored every field keeps only those that differ from the defaults. + book.update('/work/full', { showHidden: true }) + expect(stored()).toMatchObject({ '/work/full': { showHidden: true } }) + expect(book.source('/work/bad').getSnapshot()).toEqual({ ...defaultSearchPreferences(), showHidden: true }) + expect(book.source('/work/odd').getSnapshot()).toEqual(defaultSearchPreferences()) + }) + + it.each([ + ['a JSON array', '[]'], + ['a JSON string', '"oops"'], + ['a JSON null', 'null'], + ])('reads %s in storage as no preferences, and replaces it on the first change', (_label, raw) => { + localStorage.setItem(SEARCH_PREFERENCES_KEY, raw) + const book = persisted() + expect(book.source('/work/app').getSnapshot()).toEqual(defaultSearchPreferences()) + book.update('/work/app', { rules: [], showHidden: false }) + expect(stored()).toEqual({ '/work/app': { rules: [] } }) + }) + + it('reads storage that is not JSON as no preferences', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + localStorage.setItem(SEARCH_PREFERENCES_KEY, '{nope') + expect(persisted().source('/work/app').getSnapshot()).toEqual(defaultSearchPreferences()) + expect(report).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts new file mode 100644 index 0000000000..19addd7423 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts @@ -0,0 +1,239 @@ +/** Exclusion rule editing, default restoration, stored preferences, and hidden entries. */ +import { describe, expect, it } from 'vitest' +import { + addRule, changedSearchPreferences, defaultRules, defaultSearchPreferences, enabledPaths, isDefaultRules, isHiddenEntry, + normalizeRulePath, readSearchPreferences, removeRule, setRuleEnabled, type ExclusionRule, +} from '../src/client/search-rules.ts' + +const DEFAULTS = [ + '.git', '.hg', '.next', '.pnpm-store', '.svn', '.turbo', '.yarn', 'build', 'coverage', 'dist', 'node_modules', + '.DS_Store', '.Spotlight-V100', '.Trashes', '.fseventsd', 'Thumbs.db', 'desktop.ini', '$RECYCLE.BIN', 'System Volume Information', +] + +describe('normalizeRulePath', () => { + it.each([ + ['node_modules', 'node_modules'], + ['$RECYCLE.BIN', '$RECYCLE.BIN'], + [' System Volume Information ', 'System Volume Information'], + ['a/$b c/.DS_Store', 'a/$b c/.DS_Store'], + [' dist ', 'dist'], + ['packages\\app\\dist', 'packages/app/dist'], + ['./a/', 'a'], + ['././a', 'a'], + ['.//a', 'a'], + ['a//b///c', 'a/b/c'], + ['a/b//', 'a/b'], + ['.hidden', '.hidden'], + ['a..b', 'a..b'], + ['./././/cache///', 'cache'], + [' .\\.\\cache\\ ', 'cache'], + ['./parent/~cache', 'parent/~cache'], + ['./parent/C:/cache', 'parent/C:/cache'], + ['./ cache', 'cache'], + ['./ ./\t./\ncache', 'cache'], + ['cache /', 'cache'], + ['cache/ /\t/\n/', 'cache'], + [' ./ \t./cache / / ', 'cache'], + ['./\u00a0cache\ufeff/\u00a0/', 'cache'], + ['./ cache dir / nested folder / ', 'cache dir / nested folder'], + ['./ cache\t name/ next folder / ', 'cache\t name/ next folder'], + ])('normalizes %j to %j and keeps the result stable', (input, path) => { + expect(normalizeRulePath(input)).toEqual({ kind: 'ok', path }) + expect(normalizeRulePath(path)).toEqual({ kind: 'ok', path }) + const preferences = { rules: [{ path, enabled: true }], showHidden: false, respectGitignore: true } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it('normalizes long mixed edge chains while preserving internal whitespace', () => { + const path = 'cache dir / nested folder' + const input = `${'./ \t'.repeat(10_000)}${path}${' / \t'.repeat(10_000)}` + const normalized = normalizeRulePath(input) + expect(normalized.kind === 'ok' && normalized.path.length).toBe(path.length) + expect(normalized).toEqual({ kind: 'ok', path }) + expect(normalizeRulePath(path)).toEqual({ kind: 'ok', path }) + const preferences = { rules: [{ path, enabled: false }], showHidden: true, respectGitignore: false } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it.each([ + ['', 'empty'], + [' ', 'empty'], + ['./', 'empty'], + ['.//', 'empty'], + ['./ \t./ \n', 'empty'], + ['./ . / ', 'parent'], + ['a\0b', 'nul'], + ['\0', 'nul'], + ['/abs', 'absolute'], + ['/', 'absolute'], + ['///', 'absolute'], + ['\\\\server\\share', 'absolute'], + ['C:\\x', 'absolute'], + ['c:x', 'absolute'], + ['~/x', 'absolute'], + ['~', 'absolute'], + ['./~cache', 'absolute'], + ['././~cache/', 'absolute'], + ['.//./~/cache', 'absolute'], + ['./C:/cache', 'absolute'], + ['././c:cache/', 'absolute'], + ['.\\.\\C:\\cache', 'absolute'], + ['./ ~cache', 'absolute'], + ['./ C:/cache', 'absolute'], + ['./ ./\t~cache / /', 'absolute'], + ['.\\ .\\ c:cache \\ ', 'absolute'], + ['./ /cache', 'absolute'], + [' ./ ./ / ', 'absolute'], + [' \t/ ./ cache/ ', 'absolute'], + ['./ ./ /\t/', 'absolute'], + ['..', 'parent'], + ['a/../b', 'parent'], + ['a/..', 'parent'], + ['.', 'parent'], + ['a/./b', 'parent'], + ['a/.', 'parent'], + ['*.log', 'glob'], + ['a?', 'glob'], + ['[ab]', 'glob'], + ['a]', 'glob'], + ['{a,b}', 'glob'], + ['a}', 'glob'], + ['!dist', 'glob'], + ])('refuses %j as %s', (input, reason) => { + expect(normalizeRulePath(input)).toEqual({ kind: 'invalid', reason }) + }) +}) + +describe('rule list', () => { + it('starts from every default, enabled, in default order', () => { + expect(defaultRules()).toEqual(DEFAULTS.map(path => ({ path, enabled: true }))) + expect(enabledPaths(defaultRules())).toEqual(DEFAULTS) + expect(defaultSearchPreferences()).toEqual({ rules: defaultRules(), showHidden: false, respectGitignore: true }) + expect(defaultRules()).not.toBe(defaultRules()) + // Every default is a path the reader could type, unchanged by normalization. + expect(DEFAULTS.map(path => normalizeRulePath(path))).toEqual(DEFAULTS.map(path => ({ kind: 'ok', path }))) + }) + + it('adds a normalized rule at the top, enabled', () => { + const rules: ExclusionRule[] = [{ path: 'dist', enabled: true }] + expect(addRule(rules, ' ./out/ ')).toEqual({ kind: 'ok', rules: [{ path: 'out', enabled: true }, { path: 'dist', enabled: true }] }) + expect(rules).toEqual([{ path: 'dist', enabled: true }]) + }) + + it('refuses an invalid rule without changing the list', () => { + expect(addRule([], 'a/../b')).toEqual({ kind: 'invalid', reason: 'parent' }) + }) + + it('enables and moves an existing rule to the top instead of listing it twice', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: true }, { path: 'dist', enabled: false }] + expect(addRule(rules, 'dist/')).toEqual({ + kind: 'ok', rules: [{ path: 'dist', enabled: true }, { path: 'a', enabled: true }, { path: 'b', enabled: true }], + }) + expect(addRule(rules, 'b')).toEqual({ + kind: 'ok', rules: [{ path: 'b', enabled: true }, { path: 'a', enabled: true }, { path: 'dist', enabled: false }], + }) + }) + + it('removes one rule and leaves others', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: false }] + expect(removeRule(rules, 'b')).toEqual([{ path: 'a', enabled: true }]) + expect(removeRule(rules, 'c')).toEqual(rules) + }) + + it('switches one rule on or off in place', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: true }] + const off = setRuleEnabled(rules, 'a', false) + expect(off).toEqual([{ path: 'a', enabled: false }, { path: 'b', enabled: true }]) + expect(off[1]).toBe(rules[1]) + expect(setRuleEnabled(off, 'a', true)).toEqual(rules) + expect(setRuleEnabled(rules, 'a', true)[0]).toBe(rules[0]) + expect(setRuleEnabled(rules, 'c', false)).toEqual(rules) + expect(enabledPaths(off)).toEqual(['b']) + }) + + it('treats only the default list, in default order and fully enabled, as the defaults', () => { + expect(isDefaultRules(defaultRules())).toBe(true) + expect(isDefaultRules(removeRule(defaultRules(), 'dist'))).toBe(false) + expect(isDefaultRules(setRuleEnabled(defaultRules(), '.git', false))).toBe(false) + const added = addRule(defaultRules(), 'out') + expect(added.kind === 'ok' && isDefaultRules(added.rules)).toBe(false) + // Adding a listed default again moves it to the top, which differs from the default order. + const moved = addRule(defaultRules(), 'dist') + expect(moved.kind === 'ok' && isDefaultRules(moved.rules)).toBe(false) + expect(isDefaultRules([])).toBe(false) + }) +}) + +describe('readSearchPreferences', () => { + it('reads stored preferences back', () => { + const preferences = { rules: [{ path: 'out', enabled: false }, { path: 'dist', enabled: true }], showHidden: true, respectGitignore: false } + expect(readSearchPreferences(JSON.parse(JSON.stringify(preferences)))).toEqual(preferences) + }) + + it('keeps a stored empty list', () => { + const preferences = { rules: [], showHidden: false, respectGitignore: true } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it.each([ + ['no rules', { showHidden: true, respectGitignore: false }, { showHidden: true, respectGitignore: false }], + ['rules that are not an array', { rules: {}, showHidden: true }, { showHidden: true }], + ['no showHidden', { rules: [] }, { rules: [] }], + ['a showHidden that is not a boolean', { rules: [], showHidden: 'yes' }, { rules: [] }], + ['no .gitignore choice', { rules: [{ path: 'out', enabled: false }], showHidden: true }, { rules: [{ path: 'out', enabled: false }], showHidden: true }], + ['a .gitignore choice that is a string', { respectGitignore: 'no' }, {}], + ['a .gitignore choice that is a JSON null', { respectGitignore: null }, {}], + ])('gives %s its default alone, keeping the other fields', (_label, stored, kept) => { + expect(readSearchPreferences(stored)).toEqual({ ...defaultSearchPreferences(), ...kept }) + }) + + it.each([ + ['nothing stored', undefined], + ['a JSON null', null], + ['a JSON string', 'dist'], + ['an array', []], + ])('falls back to the defaults for %s', (_label, stored) => { + expect(readSearchPreferences(stored)).toEqual(defaultSearchPreferences()) + }) + + it('drops malformed, invalid, and repeated rules and normalizes the rest', () => { + const stored = { + rules: [ + null, 'dist', { path: 'a' }, { enabled: true }, { path: 1, enabled: true }, { path: 'b', enabled: 'yes' }, + { path: '../x', enabled: true }, { path: '*.log', enabled: true }, { path: '/abs', enabled: true }, { path: 'a\0b', enabled: true }, + { path: './out/', enabled: false }, { path: 'out', enabled: true }, { path: 'a\\b', enabled: true }, + ], + showHidden: false, + } + expect(readSearchPreferences(stored)).toEqual({ + rules: [{ path: 'out', enabled: false }, { path: 'a/b', enabled: true }], showHidden: false, respectGitignore: true, + }) + }) +}) + +describe('changedSearchPreferences', () => { + it('keeps only the fields that differ from the defaults, rule order and enabled state included', () => { + const defaults = defaultSearchPreferences() + expect(changedSearchPreferences(defaults)).toBeUndefined() + expect(changedSearchPreferences({ ...defaults, showHidden: true })).toEqual({ showHidden: true }) + expect(changedSearchPreferences({ ...defaults, respectGitignore: false })).toEqual({ respectGitignore: false }) + expect(changedSearchPreferences({ ...defaults, rules: defaults.rules.slice(1) })).toEqual({ rules: defaults.rules.slice(1) }) + const reversed = [...defaults.rules].reverse() + expect(changedSearchPreferences({ ...defaults, rules: reversed })).toEqual({ rules: reversed }) + const disabled = setRuleEnabled(defaults.rules, 'dist', false) + expect(changedSearchPreferences({ rules: disabled, showHidden: true, respectGitignore: false })) + .toEqual({ rules: disabled, showHidden: true, respectGitignore: false }) + }) +}) + +describe('isHiddenEntry', () => { + it.each([ + [{ name: '.env' }, true], + [{ name: '.git' }, true], + [{ name: 'desktop.ini' }, false], + [{ name: 'src' }, false], + [{ name: 'a.b' }, false], + ])('%j is hidden: %s', (entry, hidden) => { + expect(isHiddenEntry(entry)).toBe(hidden) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts new file mode 100644 index 0000000000..dfac89ae63 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts @@ -0,0 +1,86 @@ +/** Search results synthesized into a fully expanded tree, their count, and in-name highlights. */ +import { describe, expect, it } from 'vitest' +import { buildSearchTree, matchRanges } from '../src/client/search-tree.ts' +import type { SearchMatch } from '../src/client/search-tree.ts' + +const ROOT = '/work/app' + +describe('buildSearchTree', () => { + it('synthesizes every ancestor level and expands all of them', () => { + const tree = buildSearchTree(ROOT, [ + { path: 'src/search/index.ts', type: 'file' }, + { path: 'src/search.ts', type: 'file' }, + { path: 'notes/search.txt', type: 'file' }, + ]) + expect(tree).toEqual({ + autoRefresh: false, + root: ROOT, + levels: { + [ROOT]: { kind: 'ready', level: { entries: [{ name: 'src', type: 'directory' }, { name: 'notes', type: 'directory' }], truncated: false } }, + '/work/app/src': { kind: 'ready', level: { entries: [{ name: 'search', type: 'directory' }, { name: 'search.ts', type: 'file' }], truncated: false } }, + '/work/app/src/search': { kind: 'ready', level: { entries: [{ name: 'index.ts', type: 'file' }], truncated: false } }, + '/work/app/notes': { kind: 'ready', level: { entries: [{ name: 'search.txt', type: 'file' }], truncated: false } }, + }, + expanded: [ROOT, '/work/app/src', '/work/app/src/search', '/work/app/notes'], + }) + }) + + it('gives a matched directory without matched descendants an empty level', () => { + const tree = buildSearchTree(ROOT, [{ path: 'lib/search', type: 'directory' }, { path: 'odd', type: 'other' }]) + expect(tree.levels['/work/app/lib/search']).toEqual({ kind: 'ready', level: { entries: [], truncated: false } }) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'lib', type: 'directory' }, { name: 'odd', type: 'other' }], truncated: false } }) + expect(tree.expanded).toEqual([ROOT, '/work/app/lib', '/work/app/lib/search']) + }) + + it('lists each child once and keeps a matched directory that also has matched descendants', () => { + const entries: SearchMatch[] = [ + { path: 'search', type: 'directory' }, + { path: 'search/a.ts', type: 'file' }, + { path: 'search/a.ts', type: 'file' }, + ] + const tree = buildSearchTree(ROOT, entries) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'search', type: 'directory' }], truncated: false } }) + expect(tree.levels['/work/app/search']).toEqual({ kind: 'ready', level: { entries: [{ name: 'a.ts', type: 'file' }], truncated: false } }) + }) + + it('treats a name as a directory once any result passes through it, keeping its first position', () => { + const tree = buildSearchTree(ROOT, [{ path: 'x', type: 'file' }, { path: 'y', type: 'file' }, { path: 'x/z', type: 'file' }]) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'x', type: 'directory' }, { name: 'y', type: 'file' }], truncated: false } }) + expect(buildSearchTree(ROOT, [{ path: 'x/z', type: 'file' }, { path: 'x', type: 'file' }]).levels[ROOT]) + .toEqual({ kind: 'ready', level: { entries: [{ name: 'x', type: 'directory' }], truncated: false } }) + }) + + it('joins paths the way the listed tree does, whatever the root spelling', () => { + const windows = buildSearchTree('C:\\work\\', [{ path: 'a/b.txt', type: 'file' }]) + expect(windows.expanded).toEqual(['C:\\work\\', 'C:\\work/a']) + expect(buildSearchTree('/', [{ path: 'etc/x', type: 'file' }]).expanded).toEqual(['/', '/etc']) + }) + + it('draws no results as an expanded empty root', () => { + expect(buildSearchTree(ROOT, [])).toEqual({ + autoRefresh: false, root: ROOT, levels: { [ROOT]: { kind: 'ready', level: { entries: [], truncated: false } } }, expanded: [ROOT], + }) + }) +}) + +describe('matchRanges', () => { + it('finds every non-overlapping occurrence regardless of case', () => { + expect(matchRanges('Search-search.SEARCH', 'search')).toEqual([[0, 6], [7, 13], [14, 20]]) + expect(matchRanges('aaaa', 'aa')).toEqual([[0, 2], [2, 4]]) + }) + + it('treats the query literally', () => { + expect(matchRanges('a.b(c)*', '.b(c)*')).toEqual([[1, 7]]) + expect(matchRanges('axb', '.')).toEqual([]) + }) + + it('has no ranges for an empty query or a miss', () => { + expect(matchRanges('name', '')).toEqual([]) + expect(matchRanges('name', 'src/name')).toEqual([]) + }) + + it('indexes the name as given around non-ASCII text', () => { + expect(matchRanges('Größe.TXT', 'größe')).toEqual([[0, 5]]) + expect(matchRanges('报告-搜索.md', '搜索')).toEqual([[3, 5]]) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search.client.spec.tsx b/packages/client/ui-sidebar-files/tests/search.client.spec.tsx new file mode 100644 index 0000000000..3fb08ea2cf --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search.client.spec.tsx @@ -0,0 +1,666 @@ +// @vitest-environment jsdom +/** + * The navigator's search: the bar above the tree, the results drawn in the + * tree's place, the settings panel, the hidden-entry control, the keyboard, + * and the Escape order. A scripted search stands in for the Host's: it + * answers every query with fixed matches, or leaves a query open. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, within } from '@testing-library/react' +import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import { zh } from '../src/client/locales.ts' +import { defaultRules, enabledPaths } from '../src/client/search-rules.ts' +import type { WorkspaceSearchPreferences } from '../src/client/search-rules.ts' +import type { DirLevel } from '../src/client/store.ts' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { mountNavigator, PANE, ROOT, SESSION } from './mount.client.tsx' +import type { Mounted } from './mount.client.tsx' +import { answer, memoryBook, searchesSettled } from './search-fixture.client.ts' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' + +const ROOT_LEVEL: DirLevel = { + entries: [ + { name: 'src', type: 'directory' }, { name: 'node_modules', type: 'directory' }, + { name: '.env', type: 'file', size: 1 }, { name: 'README.md', type: 'file', size: 1 }, + ], + truncated: false, +} +const SRC_LEVEL: DirLevel = { entries: [{ name: 'a.ts', type: 'file', size: 1 }, { name: 'b.ts', type: 'file', size: 1 }], truncated: false } +const A = sessionFileAddress(SESSION, 'src/a.ts') +const t = makeTranslate(zh) + +beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn() +}) +afterEach(() => { + cleanup() + Reflect.deleteProperty(Element.prototype, 'scrollIntoView') +}) + +/** Show the navigator on a page-less tab and answer the root listing. */ +async function shown(h: Mounted): Promise { + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) +} + +/** Show the navigator beside `src/a.ts` and answer the root and `src` listings. */ +async function revealed(h: Mounted): Promise { + await shown(h) + await act(() => h.script.watches.ready(`${ROOT}/src`)) + await act(() => h.script.settle({ ok: true, value: SRC_LEVEL })) +} + +const field = (h: Mounted): HTMLInputElement => within(h.view.container).getByRole('searchbox', { name: zh['search.placeholder'] }) +const body = (h: Mounted): HTMLElement => h.view.container.querySelector('[data-files-body]')! + +/** + * The tooltip text of the empty result's information button, read by pinning + * the tooltip with a click and closing it again; `undefined` without the button. + */ +const emptyHint = (h: Mounted): string | undefined => { + const button = body(h).querySelector('[data-files-search-hint]') + if (button === null) return undefined + expect(button.getAttribute('aria-label')).toBe(zh['search.emptyHint.label']) + fireEvent.click(button) + const text = document.querySelector('[role="tooltip"]')?.textContent + fireEvent.click(button) + expect(document.querySelector('[role="tooltip"]')).toBeNull() + return text +} +const status = (h: Mounted): string | null | undefined => h.view.container.querySelector('[data-files-search-status]')?.textContent +const paths = (h: Mounted): string[] => [...body(h).querySelectorAll('[data-files-entry]')].map(li => li.getAttribute('data-files-path')!) +const dialog = (h: Mounted): HTMLElement | null => h.view.queryByRole('dialog') +const settingsButton = (h: Mounted): HTMLElement => h.view.getByRole('button', { name: zh['search.settings'] }) + +/** jsdom omits mousedown's focus default; honor its cancellation before clicking. */ +function pointerClick(target: HTMLElement): void { + act(() => { + fireEvent.pointerDown(target, { button: 0, pointerType: 'mouse' }) + if (fireEvent.mouseDown(target, { button: 0 })) target.focus() + fireEvent.pointerUp(target, { button: 0, pointerType: 'mouse' }) + fireEvent.mouseUp(target, { button: 0 }) + fireEvent.click(target, { button: 0 }) + }) +} + +/** Supply the focused button's native keyboard activation that jsdom omits. */ +function keyboardClick(target: HTMLElement, key: 'Enter' | ' '): void { + act(() => { + target.focus() + const allowed = fireEvent.keyDown(target, { key }) + if (allowed && key === 'Enter') target.click() + const released = fireEvent.keyUp(target, { key }) + if (allowed && released && key === ' ') target.click() + }) +} + +/** + * Type into the search field and let the search's answer draw. + * @param h - the mounted navigator. + * @param text - the field's new text. + * @param matches - what the search answers, as `answer` takes them; the previous answer when omitted. + */ +async function type(h: Mounted, text: string, matches?: readonly string[]): Promise { + if (matches !== undefined) h.searches.answerWith(answer(matches)) + await act(async () => { + fireEvent.change(field(h), { target: { value: text } }) + await searchesSettled() + }) +} +/** Run a store or face write and let a search it starts draw its answer. */ +async function settled(write: () => void): Promise { + await act(async () => { + write() + await searchesSettled() + }) +} +/** The requests the search received, oldest first. */ +const requests = (h: Mounted) => h.search.mock.calls.map(([, request]) => request) + +describe('the search bar', () => { + it('searches as the reader types and draws the matches as a highlighted tree with its count', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + expect(h.view.queryByRole('button', { name: zh['search.clear'] })).toBeNull() + await type(h, ' Ab ', ['src/tab.ts', 'lib/AB/', 'lib/AB/x.ts']) + expect(requests(h)).toEqual([{ query: 'Ab', excludedPaths: enabledPaths(defaultRules()), includeHidden: false, respectGitignore: true }]) + expect(status(h)).toBe(t('search.results', { count: '3' })) + expect(paths(h)).toEqual([`${ROOT}/lib`, `${ROOT}/lib/AB`, `${ROOT}/lib/AB/x.ts`, `${ROOT}/src`, `${ROOT}/src/tab.ts`]) + expect([...body(h).querySelectorAll('mark')].map(mark => mark.textContent)).toEqual(['AB', 'ab']) + expect(body(h).querySelector(`[data-files-path="${ROOT}/src/tab.ts"] button`)?.textContent).toBe('tab.ts') + expect(h.view.getByRole('button', { name: zh['search.clear'] })).toBeTruthy() + // Whitespace around the same text asks nothing new and keeps the count. + await type(h, 'Ab') + expect(requests(h)).toHaveLength(1) + expect(status(h)).toBe(t('search.results', { count: '3' })) + }) + + it('collapses result directories on their own, and opens a result like a tree row with the tab\'s file marked', async () => { + const h = mountNavigator(A) + await revealed(h) + await type(h, 'a', ['src/a.ts', 'empty/']) + // A matched directory without matched descendants is not called empty. + expect(body(h).querySelector('[data-files-row="empty"]')).toBeNull() + expect(body(h).querySelector('[aria-current="true"]')?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src/a.ts`) + const src = (): HTMLElement => body(h).querySelector(`[data-files-path="${ROOT}/src"] > div > button`)! + act(() => { fireEvent.click(src()) }) + expect(src().getAttribute('aria-expanded')).toBe('false') + expect(h.instance.getSnapshot().byPane[PANE]?.tree?.expanded).toEqual([ROOT, `${ROOT}/src`]) + act(() => { fireEvent.click(src()) }) + fireEvent.click(body(h).querySelector(`[data-files-path="${ROOT}/src/a.ts"] > div > button`)!) + expect(h.onOpen).toHaveBeenLastCalledWith(A) + }) + + it('draws the tree again as it was — expansion, scroll, and the current file — once the query is cleared', async () => { + const h = mountNavigator(A) + await revealed(h) + fireEvent.scroll(body(h), { target: { scrollTop: 64 } }) + await type(h, 'b', ['src/b.ts']) + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).scrollTop).toBe(0) + fireEvent.scroll(body(h), { target: { scrollTop: 12 } }) + act(() => { fireEvent.click(h.view.getByRole('button', { name: zh['search.clear'] })) }) + expect(document.activeElement).toBe(field(h)) + expect(status(h)).toBe('') + expect(body(h).getAttribute('data-files-view')).toBe('tree') + expect(body(h).scrollTop).toBe(64) + expect(h.instance.getSnapshot().byPane[PANE]?.tree?.expanded).toEqual([ROOT, `${ROOT}/src`]) + expect(body(h).querySelector('[aria-current="true"]')?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src/a.ts`) + await type(h, 'b') + expect(body(h).scrollTop).toBe(0) + // A remount during a search restores the results' own offset. + fireEvent.scroll(body(h), { target: { scrollTop: 30 } }) + h.view.unmount() + const back = h.remount() + expect(back.container.querySelector('[data-files-body]')?.scrollTop).toBe(30) + // New results start at their top. + await settled(() => { h.face.setQuery(PANE, ROOT, 'bb') }) + expect(back.container.querySelector('[data-files-body]')?.scrollTop).toBe(0) + }) + + it('says when nothing matched, with an information button whose tooltip names which of hidden entries, excluded paths, and ignored ones the search left out', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'zzz') + expect(body(h).textContent).toBe(zh['search.empty']) + expect(emptyHint(h)).toBe(zh['search.emptyHint.all']) + expect(status(h)).toBe(t('search.results', { count: '0' })) + const settle = async (preferences: Partial): Promise => { + await settled(() => { h.face.setSearchPreferences(ROOT, preferences) }) + expect(body(h).textContent).toBe(zh['search.empty']) + return emptyHint(h) + } + expect(await settle({ showHidden: true })).toBe(zh['search.emptyHint.excludedIgnored']) + expect(requests(h).at(-1)).toMatchObject({ excludedPaths: enabledPaths(defaultRules()), includeHidden: true }) + expect(await settle({ rules: [] })).toBe(zh['search.emptyHint.ignored']) + expect(requests(h).at(-1)).toMatchObject({ excludedPaths: [], includeHidden: true }) + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.hiddenIgnored']) + // Turning ignore files off leaves out only what the other two settings take. + expect(await settle({ respectGitignore: false })).toBe(zh['search.emptyHint.hidden']) + expect(requests(h).at(-1)).toMatchObject({ respectGitignore: false }) + // With nothing excluded, hidden entries shown, and ignore files not respected, the search left nothing out. + expect(await settle({ showHidden: true })).toBeUndefined() + // A rule that is listed but off excludes nothing. + expect(await settle({ rules: [{ path: 'dist', enabled: false }] })).toBeUndefined() + // Leaving out hidden entries is the only thing that remains. + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.hidden']) + expect(await settle({ rules: defaultRules(), showHidden: true })).toBe(zh['search.emptyHint.excluded']) + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.both']) + }) + + it('says below the results, matched or not, when only the first matches are drawn and when some directories were not searched', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const note = (row: string): string | null | undefined => body(h).querySelector(`[data-files-row="${row}"]`)?.textContent + h.searches.answerWith(answer(['src/a.ts', 'src/ab.ts'], { truncated: true })) + await type(h, 'a') + expect(note('search-truncated')).toBe(t('search.truncated', { count: '2' })) + expect(note('search-incomplete')).toBeUndefined() + expect(note('search-empty')).toBeUndefined() + h.searches.answerWith(answer(['src/a.ts'], { incomplete: true })) + await type(h, 'ab') + expect(note('search-truncated')).toBeUndefined() + expect(note('search-incomplete')).toBe(zh['search.incomplete']) + h.searches.answerWith(answer([], { truncated: true, incomplete: true })) + await type(h, 'zzz') + expect(body(h).textContent).toBe(`${zh['search.empty']}${t('search.truncated', { count: '0' })}${zh['search.incomplete']}`) + expect(emptyHint(h)).toBe(zh['search.emptyHint.all']) + }) + + it('keeps the last results drawn with a spinner while the next search runs, and draws only a spinner before the first answer', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const spinner = (): Element | null => h.view.container.querySelector('[data-files-search-status] [data-state="ongoing"]') + expect(spinner()).toBeNull() + h.searches.answerWith(undefined) + await type(h, 'a') + // Before the first answer the results area is empty: no tree, no note. + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).getAttribute('aria-busy')).toBe('true') + expect(body(h).textContent).toBe('') + expect(status(h)).toBe('') + expect(spinner()).not.toBeNull() + await settled(() => { h.searches.started[0]!.settle(answer(['src/a.ts'])) }) + expect(spinner()).toBeNull() + expect(body(h).getAttribute('aria-busy')).toBe('false') + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + // A newer search keeps those results and the count until its answer replaces them. + await type(h, 'b') + expect(spinner()).not.toBeNull() + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + expect(status(h)).toBe(t('search.results', { count: '1' })) + await settled(() => { h.searches.started[1]!.settle(answer([])) }) + expect(spinner()).toBeNull() + expect(status(h)).toBe(t('search.results', { count: '0' })) + }) + + it('says why a search failed in the results\' place, and searches again from its retry control', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + h.searches.answerWith({ ok: false, error: new RemoteError('workspace-file/not-found', 'no entry at "/work/app"', { path: '/work/app' }) }) + await type(h, 'a') + const failed = (): HTMLElement | null => body(h).querySelector('[data-files-row="search-failed"]') + // A classified failure reads as the tree's own line, not the Host's untranslated message. + expect(within(failed()!).getByRole('alert').textContent).toBe(t('search.failed', { message: t('error.notFound') })) + expect(status(h)).toBe('') + expect(paths(h)).toEqual([]) + h.searches.answerWith(answer(['src/a.ts'])) + const retry = within(failed()!).getByRole('button', { name: zh['search.retry'] }) + await settled(() => { fireEvent.click(retry) }) + expect(requests(h)).toHaveLength(2) + expect(requests(h)[1]).toEqual(requests(h)[0]) + expect(failed()).toBeNull() + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + }) + + it('keeps the status line mounted as a live region while the query is blank, so a screen reader hears the first search', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const live = h.view.container.querySelector('[data-files-search-status]') + expect(live?.getAttribute('aria-live')).toBe('polite') + expect(live?.textContent).toBe('') + await type(h, 'a', ['a.ts']) + expect(h.view.container.querySelector('[data-files-search-status]')).toBe(live) + expect(live?.textContent).toBe(t('search.results', { count: '1' })) + await type(h, '') + expect(h.view.container.querySelector('[data-files-search-status]')).toBe(live) + expect(live?.textContent).toBe('') + }) +}) + +describe('the hidden-entry control', () => { + it('leaves hidden entries out of the tree and the search until pressed, and shows them in both while pressed', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const eye = (): HTMLElement => h.view.container.querySelector('[data-files-show-hidden]')! + expect(eye().getAttribute('aria-pressed')).toBe('false') + expect(eye().getAttribute('aria-label')).toBe(zh['search.showHidden']) + // The name stays fixed; only `aria-pressed` reports the state. + expect(paths(h)).not.toContain(`${ROOT}/.env`) + act(() => { fireEvent.click(eye()) }) + expect(eye().getAttribute('aria-pressed')).toBe('true') + expect(eye().getAttribute('aria-label')).toBe(zh['search.showHidden']) + expect(paths(h)).toContain(`${ROOT}/.env`) + await type(h, 'env', ['.env']) + expect(requests(h)[0]?.includeHidden).toBe(true) + expect(paths(h)).toEqual([`${ROOT}/.env`]) + // Changing it during a search searches again at once. + act(() => { fireEvent.click(eye()) }) + expect(requests(h)[1]?.includeHidden).toBe(false) + }) + + it('says a directory holding only hidden entries holds hidden entries, not that it is empty', async () => { + const h = mountNavigator('sidebar://files') + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: { entries: [{ name: '.env', type: 'file', size: 1 }], truncated: false } })) + expect(body(h).querySelector('[data-files-row="empty"]')).toBeNull() + expect(body(h).querySelector('[data-files-row="hidden-only"]')?.textContent).toBe(zh.emptyHidden) + act(() => { fireEvent.click(h.view.container.querySelector('[data-files-show-hidden]')!) }) + expect(body(h).querySelector('[data-files-row="hidden-only"]')).toBeNull() + expect(paths(h)).toEqual([`${ROOT}/.env`]) + }) + + it('applies exclusions only to the search, so the tree still lists excluded directories', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + expect(paths(h)).toContain(`${ROOT}/node_modules`) + await type(h, 'x') + expect(requests(h)[0]?.excludedPaths).toContain('node_modules') + await type(h, '') + expect(paths(h)).toContain(`${ROOT}/node_modules`) + }) + + it('shares one workspace\'s choice across Sessions rooted there, and not with another workspace', async () => { + const book = memoryBook() + const one = mountNavigator('sidebar://files', {}, ROOT, book) + const two = mountNavigator('sidebar://files', {}, `${ROOT}/`, book) + const other = mountNavigator('sidebar://files', {}, '/work/other', book) + act(() => { + for (const h of [one, two, other]) h.instance.actions.shown(PANE, true) + }) + const eye = (h: Mounted): string | null => h.view.container.querySelector('[data-files-show-hidden]')!.getAttribute('aria-pressed') + act(() => { fireEvent.click(one.view.container.querySelector('[data-files-show-hidden]')!) }) + expect([eye(one), eye(two), eye(other)]).toEqual(['true', 'true', 'false']) + }) +}) + +describe('the settings panel', () => { + /** Open the panel from the magnifier. */ + function open(h: Mounted): HTMLElement { + pointerClick(settingsButton(h)) + expect(settingsButton(h).getAttribute('aria-expanded')).toBe('true') + return dialog(h)! + } + const stored = (h: Mounted) => h.book.source(ROOT).getSnapshot() + + it.each(['pointer', 'Enter', ' '] as const)('saves checkbox edits when the magnifier is activated with %j and searches with the saved rules', async (gesture) => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + const toggle = (): void => { + if (gesture === 'pointer') pointerClick(settingsButton(h)) + else keyboardClick(settingsButton(h), gesture) + } + toggle() + const checkbox = within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) }) + pointerClick(checkbox) + expect(document.activeElement).toBe(checkbox) + expect(checkbox.checked).toBe(false) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + expect(requests(h)).toHaveLength(1) + + toggle() + expect(dialog(h)).toBeNull() + expect(settingsButton(h).getAttribute('aria-expanded')).toBe('false') + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(document.activeElement).toBe(settingsButton(h)) + expect(requests(h)).toEqual([requests(h)[0], { + query: 'a', excludedPaths: enabledPaths(defaultRules()).filter(path => path !== 'dist'), includeHidden: false, respectGitignore: true, + }]) + + toggle() + expect(within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })).toHaveProperty('checked', false) + }) + + it('keeps added and removed paths when the magnifier closes a panel without a query', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + pointerClick(settingsButton(h)) + const panel = dialog(h)! + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + act(() => { + fireEvent.change(add, { target: { value: './cache/' } }) + fireEvent.keyDown(add, { key: 'Enter' }) + }) + pointerClick(within(panel).getByRole('button', { name: t('settings.remove', { path: 'build' }) })) + expect(document.activeElement).toBe(add) + expect(stored(h).rules.map(rule => rule.path)).not.toContain('cache') + expect(stored(h).rules.map(rule => rule.path)).toContain('build') + + pointerClick(settingsButton(h)) + expect(dialog(h)).toBeNull() + expect(stored(h).rules[0]).toEqual({ path: 'cache', enabled: true }) + expect(stored(h).rules.map(rule => rule.path)).not.toContain('build') + pointerClick(settingsButton(h)) + expect(within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'cache' }) })).toHaveProperty('checked', true) + expect(within(dialog(h)!).queryByRole('checkbox', { name: t('settings.toggle', { path: 'build' }) })).toBeNull() + expect(h.search).not.toHaveBeenCalled() + }) + + it('opens from the magnifier with the add field focused, and saves on its close control, on Escape, and when focus leaves it', async () => { + const h = mountNavigator('sidebar://files') + h.row.width = 480 + await shown(h) + // Pressing the magnifier on a closed panel takes the keyboard as any button does. + expect(fireEvent.mouseDown(settingsButton(h))).toBe(true) + let panel = open(h) + expect(within(panel).getByText(zh['settings.title'])).toBeTruthy() + expect(document.activeElement).toBe(within(panel).getByRole('textbox', { name: zh['settings.add'] })) + expect(h.view.container.querySelectorAll('[data-files-show-hidden]')).toHaveLength(1) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + // Nothing is written while the panel is open. + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(dialog(h)).toBeNull() + expect(document.activeElement).toBe(settingsButton(h)) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + + panel = open(h) + pointerClick(within(panel).getByRole('button', { name: t('settings.remove', { path: 'build' }) })) + expect(dialog(h)).not.toBeNull() + act(() => { fireEvent.keyDown(within(panel).getByRole('textbox'), { key: 'Escape' }) }) + expect(dialog(h)).toBeNull() + // The overlaying navigator stays: the panel kept the Escape. + expect(h.view.container.querySelector('[data-files-navigator]')).not.toBeNull() + expect(stored(h).rules.map(rule => rule.path)).not.toContain('build') + + panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'coverage' }) })) + act(() => { body(h).focus() }) + expect(dialog(h)).toBeNull() + expect(stored(h).rules.find(rule => rule.path === 'coverage')?.enabled).toBe(false) + + // Closing without an edit writes nothing; the magnifier closes it too. + const before = stored(h) + open(h) + pointerClick(settingsButton(h)) + expect(dialog(h)).toBeNull() + expect(stored(h)).toBe(before) + }) + + it('shows the restore control whenever the list differs from the defaults, and replaces the list with the defaults', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + const restore = (): HTMLElement | null => within(panel).queryByRole('button', { name: zh['settings.restore'] }) + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + const rules = (): string[] => [...panel.querySelectorAll('[data-files-rule]')].map(row => row.getAttribute('data-files-rule')!) + const defaults = rules() + const type = (value: string): void => { + act(() => { fireEvent.change(add, { target: { value } }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + } + expect(restore()).toBeNull() + // A custom path alone differs from the defaults. + type('out') + expect(restore()).not.toBeNull() + act(() => { fireEvent.click(within(panel).getByRole('button', { name: t('settings.remove', { path: 'out' }) })) }) + expect(document.activeElement).toBe(add) + expect(restore()).toBeNull() + // A default added again moves to the top, so the order differs. + type('dist') + expect(rules()[0]).toBe('dist') + expect(restore()).not.toBeNull() + act(() => { fireEvent.click(within(panel).getByRole('button', { name: t('settings.remove', { path: 'node_modules' }) })) }) + act(() => { fireEvent.click(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: '.git' }) })) }) + type('out') + act(() => { fireEvent.click(restore()!) }) + expect(document.activeElement).toBe(add) + expect(restore()).toBeNull() + expect(rules()).toEqual(defaults) + expect(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: '.git' }) })).toHaveProperty('checked', true) + }) + + it('refuses an invalid path where it was typed, and adds a valid one at the top', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + act(() => { fireEvent.change(add, { target: { value: '../x' } }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + expect(within(panel).getByRole('alert').textContent).toBe(zh['settings.invalid.parent']) + expect(add.getAttribute('aria-invalid')).toBe('true') + act(() => { fireEvent.change(add, { target: { value: 'tmp/' } }) }) + expect(within(panel).queryByRole('alert')).toBeNull() + act(() => { fireEvent.keyDown(add, { key: 'a' }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + expect(add.value).toBe('') + expect(panel.querySelector('[data-files-rule]')?.getAttribute('data-files-rule')).toBe('tmp') + }) + + it('saves only the rules on close, keeping a hidden-entry choice made while the panel was open', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + act(() => { h.face.setSearchPreferences(ROOT, { showHidden: true }) }) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(stored(h).showHidden).toBe(true) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + }) + + it('saves the draft when the eye is clicked without losing the hidden-entry change', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + const eye = h.view.getByRole('button', { name: zh['search.showHidden'] }) + pointerClick(eye) + expect(dialog(h)).toBeNull() + expect(document.activeElement).toBe(eye) + expect(eye.getAttribute('aria-pressed')).toBe('true') + expect(stored(h).showHidden).toBe(true) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(paths(h)).toContain(`${ROOT}/.env`) + expect(within(open(h)).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })).toHaveProperty('checked', false) + }) + + it('respects .gitignore until its checkbox is cleared, saving the choice at once and searching again with it', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + expect(requests(h)[0]?.respectGitignore).toBe(true) + const panel = open(h) + const gitignore = within(panel).getByRole('checkbox', { name: zh['settings.respectGitignore'] }) + expect(gitignore.checked).toBe(true) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(gitignore) + // Saved while the panel is open, unlike the rules, which wait for it to close. + expect(gitignore.checked).toBe(false) + expect(stored(h).respectGitignore).toBe(false) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + expect(requests(h)[1]).toMatchObject({ respectGitignore: false, excludedPaths: enabledPaths(defaultRules()) }) + expect(dialog(h)).not.toBeNull() + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(stored(h)).toMatchObject({ respectGitignore: false }) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(within(open(h)).getByRole('checkbox', { name: zh['settings.respectGitignore'] })).toHaveProperty('checked', false) + }) + + it('searches again with the saved rules when the panel closes during a search', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + const panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(requests(h)[1]?.excludedPaths).not.toContain('dist') + }) +}) + +describe('the keyboard', () => { + it('walks from the field through the rows with ↓ and ↑, back to the field from the first row', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + const rows = [...body(h).querySelectorAll('[data-files-path] > div > button')] + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(rows[0]) + act(() => { fireEvent.keyDown(rows[0]!, { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(rows[1]) + act(() => { fireEvent.keyDown(rows[1]!, { key: 'ArrowDown', shiftKey: true }) }) + expect(document.activeElement).toBe(rows[1]) + act(() => { fireEvent.keyDown(rows[1]!, { key: 'ArrowUp' }) }) + act(() => { fireEvent.keyDown(rows[0]!, { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + // Past the last row there is nowhere to go; the separator's arrows are its own. + const last = rows.at(-1)! + act(() => { last.focus() }) + act(() => { fireEvent.keyDown(last, { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(last) + act(() => { fireEvent.keyDown(h.view.getByRole('separator'), { key: 'ArrowDown' }) }) + // The rows are buttons, so Enter opens a file as a click does. + expect(last.tagName).toBe('BUTTON') + }) + + it('leaves ↓ to an input method composing text, and to a key someone in the navigator already handled', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown', isComposing: true }) }) + expect(document.activeElement).toBe(field(h)) + const keep = (event: KeyboardEvent): void => { event.preventDefault() } + field(h).addEventListener('keydown', keep) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + field(h).removeEventListener('keydown', keep) + expect(document.activeElement).toBe(field(h)) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + expect(document.activeElement).not.toBe(field(h)) + }) + + it('closes the settings on Escape first, then clears the query, and only then lets the overlay close', async () => { + const h = mountNavigator('sidebar://files') + h.row.width = 480 + await shown(h) + await type(h, 'a') + act(() => { fireEvent.click(settingsButton(h)) }) + act(() => { fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) }) + expect(dialog(h)).toBeNull() + expect(field(h).value).toBe('a') + // An Escape someone in the navigator already kept does not clear it. + const keep = (event: KeyboardEvent): void => { event.preventDefault() } + field(h).addEventListener('keydown', keep) + act(() => { fireEvent.keyDown(field(h), { key: 'Escape' }) }) + field(h).removeEventListener('keydown', keep) + expect(field(h).value).toBe('a') + act(() => { fireEvent.keyDown(body(h), { key: 'Escape' }) }) + expect(field(h).value).toBe('') + expect(document.activeElement).toBe(field(h)) + expect(h.view.container.querySelector('[data-files-navigator]')).not.toBeNull() + act(() => { fireEvent.keyDown(field(h), { key: 'Escape' }) }) + expect(h.view.container.querySelector('[data-files-navigator]')).toBeNull() + }) + + it('keeps the keyboard where the reader moved it as the view switches to the results and back, each with its own scroll', async () => { + const h = mountNavigator(A) + await revealed(h) + fireEvent.scroll(body(h), { target: { scrollTop: 64 } }) + const first = body(h).querySelector('[data-files-path] > div > button')! + act(() => { first.focus() }) + act(() => { fireEvent.keyDown(first, { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + await type(h, 'b', ['src/b.ts']) + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(field(h)) + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).scrollTop).toBe(0) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + const result = document.activeElement + expect(result?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src`) + // Escape on a result row clears the text and hands the keyboard to the field. + act(() => { fireEvent.keyDown(result!, { key: 'Escape' }) }) + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(field(h)) + expect(body(h).getAttribute('data-files-view')).toBe('tree') + expect(body(h).scrollTop).toBe(64) + }) + + it('carries the search field\'s keyboard focus to the pane\'s next drawing in the same task only', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + h.view.unmount() + const back = h.remount() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(within(back.container).getByRole('searchbox')) + back.unmount() + await act(async () => { await Promise.resolve() }) + h.remount() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(document.body) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/store.client.spec.ts b/packages/client/ui-sidebar-files/tests/store.client.spec.ts index cadf73fe6e..27df4c170a 100644 --- a/packages/client/ui-sidebar-files/tests/store.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/store.client.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { createFilesStore } from '../src/client/store.ts' import { DEFAULT_NAVIGATOR_WIDTH } from '../src/client/store.ts' -import type { DirLevel } from '../src/client/store.ts' +import type { DirLevel, FilesSearchResult } from '../src/client/store.ts' import type { PaneId } from '@deepseek-ai/dsh-client-ui-dockkit' const ROOT = '/work/app' @@ -22,13 +22,29 @@ describe('createFilesStore', () => { expect(second.getSnapshot().byPane[PANE]).toBeUndefined() }) + it('keeps each pane\'s search-bar choice independent without changing its search', () => { + const store = createFilesStore().create() + const other = 'pane-2' as PaneId + store.actions.start(PANE, ROOT) + store.actions.start(other, ROOT) + store.actions.queried(PANE, 'target') + store.actions.searching(PANE) + const search = store.getSnapshot().byPane[PANE]!.search + store.actions.searchBarShown(PANE, true) + expect(store.getSnapshot().byPane[PANE]!.searchBarOpen).toBe(true) + expect(store.getSnapshot().byPane[other]!.searchBarOpen).toBe(false) + store.actions.searchBarShown(PANE, false) + expect(store.getSnapshot().byPane[PANE]!.query).toBe('target') + expect(store.getSnapshot().byPane[PANE]!.search).toBe(search) + }) + it('seeds a pane at its root with the root expanded and nothing loaded', () => { const store = createFilesStore().create() const { actions } = store const getSnapshot = (): ReturnType => store.getSnapshot() actions.start(PANE, ROOT) expect(getSnapshot().byPane[PANE]).toEqual({ - open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, + open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, query: '', searchBarOpen: false, search: undefined, tree: { root: ROOT, levels: {}, expanded: [ROOT], autoRefresh: true }, }) }) @@ -147,12 +163,12 @@ describe('createFilesStore', () => { const { actions } = store actions.shown(PANE, true) actions.resized(PANE, 320) - expect(store.getSnapshot().byPane[PANE]).toEqual({ open: true, width: 320, tree: undefined }) + expect(store.getSnapshot().byPane[PANE]).toEqual({ open: true, width: 320, tree: undefined, query: '', searchBarOpen: false, search: undefined }) actions.start(PANE, ROOT) actions.loaded(PANE, ROOT, LEVEL) actions.start(PANE, '/work/other') expect(store.getSnapshot().byPane[PANE]).toEqual({ - open: true, width: 320, + open: true, width: 320, query: '', searchBarOpen: false, search: undefined, tree: { root: '/work/other', levels: {}, expanded: ['/work/other'], autoRefresh: true }, }) }) @@ -171,4 +187,51 @@ describe('createFilesStore', () => { actions.forget(PANE) expect(Object.keys(getSnapshot().byPane)).toEqual(['pane-2']) }) + + it('keeps a pane\'s search apart from its tree, and drops a result the query already ended', () => { + const store = createFilesStore().create() + const { actions } = store + const getSnapshot = (): ReturnType => store.getSnapshot() + const search = () => getSnapshot().byPane[PANE]?.search + const found = () => { + const result = search()?.result + return result?.kind === 'found' ? result : undefined + } + const result = (query: string): FilesSearchResult => ({ + kind: 'found', query, count: 0, truncated: false, incomplete: false, hiddenLeftOut: true, excluded: true, ignored: true, + tree: { root: ROOT, levels: {}, expanded: [ROOT, `${ROOT}/src`], autoRefresh: false }, + }) + actions.searching(PANE) + actions.searched(PANE, result('a')) + actions.searchToggled(PANE, ROOT) + expect(getSnapshot().byPane).toEqual({}) + actions.queried(PANE, ' ') + actions.searching(PANE) + actions.searched(PANE, result('a')) + expect(getSnapshot().byPane[PANE]).toMatchObject({ query: ' ', search: undefined }) + actions.queried(PANE, 'a') + expect(search()).toBeUndefined() + // A search under way before its first answer has nothing to draw yet. + actions.searching(PANE) + expect(search()).toEqual({ pending: true, result: undefined }) + actions.searchToggled(PANE, ROOT) + actions.searched(PANE, result('a')) + expect(search()?.pending).toBe(false) + actions.searchToggled(PANE, ROOT) + expect(found()?.tree.expanded).toEqual([`${ROOT}/src`]) + actions.searchToggled(PANE, ROOT) + expect(found()?.tree.expanded).toEqual([`${ROOT}/src`, ROOT]) + // Other text keeps the last result, pending, until the next is recorded. + actions.queried(PANE, 'ab') + actions.searching(PANE) + expect(search()).toMatchObject({ pending: true, result: { query: 'a' } }) + const failure = new RemoteError('gateway/internal', 'down', {}) + actions.searched(PANE, { kind: 'failed', query: 'ab', failure }) + expect(search()).toEqual({ pending: false, result: { kind: 'failed', query: 'ab', failure } }) + // A failed search has no tree to toggle. + actions.searchToggled(PANE, ROOT) + expect(search()?.result).toEqual({ kind: 'failed', query: 'ab', failure }) + actions.queried(PANE, '') + expect(search()).toBeUndefined() + }) }) diff --git a/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts b/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts index 8a95bf5ff4..09fbb72caf 100644 --- a/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { zh } from '../src/client/locales.ts' import type { FilesTreeState } from '../src/client/store.ts' -import { parentOf, treeRootOf, workspaceDirectories, workspaceEntries } from '../src/client/workspace-tree.ts' +import { parentOf, searchDirectories, treeRootOf, workspaceDirectories, workspaceEntries } from '../src/client/workspace-tree.ts' const t = makeTranslate(zh) @@ -29,14 +29,15 @@ describe('workspace tree keys', () => { ['\\\\server\\share\\', '\\\\server\\share'], ])('keys root %j as %j, its entries one slash below it, and their parents back to the root as stored', (root, key) => { const tree = listed(root) - expect(workspaceEntries(tree.levels)).toEqual([ + expect(workspaceEntries(tree.levels, false)).toEqual([ { path: `${key}/src`, name: 'src', meta: { kind: 'directory' } }, { path: `${key}/pipe`, name: 'pipe', meta: { kind: 'other' } }, { path: `${key}/src/a.ts`, name: 'a.ts', meta: { kind: 'file' } }, ]) expect(parentOf(tree, `${key}/src`)).toBe(root) expect(parentOf(tree, `${key}/src/lib`)).toBe(`${key}/src`) - expect(Object.keys(workspaceDirectories(tree, t))).toEqual([key, `${key}/src`]) + expect(Object.keys(workspaceDirectories(tree, t, false))).toEqual([key, `${key}/src`]) + expect(Object.keys(searchDirectories(tree))).toEqual([key, `${key}/src`]) }) }) @@ -52,7 +53,7 @@ describe('workspaceDirectories', () => { '/r/c': { kind: 'failed', failure }, '/r/d': { kind: 'ready', level: { entries: [], truncated: false } }, }, - }, t) + }, t, false) expect(states).toEqual({ '/r': { failure: zh['error.notFound'], truncated: true }, '/r/a': { loading: true }, @@ -62,3 +63,37 @@ describe('workspaceDirectories', () => { }) }) }) + +describe('hidden entries', () => { + const tree: FilesTreeState = { + root: '/r', autoRefresh: true, expanded: ['/r', '/r/.git'], + levels: { + '/r': { kind: 'ready', level: { entries: [{ name: '.git', type: 'directory' }, { name: 'a.ts', type: 'file' }], truncated: false } }, + '/r/.git': { kind: 'ready', level: { entries: [{ name: '.keep', type: 'file' }], truncated: false } }, + }, + } + + it('leaves them out, and says a directory of only hidden entries holds some, until they are shown', () => { + expect(workspaceEntries(tree.levels, false).map(entry => entry.path)).toEqual(['/r/a.ts']) + expect(workspaceDirectories(tree, t, false)).toEqual({ '/r': {}, '/r/.git': { omitted: 'hidden' } }) + expect(workspaceEntries(tree.levels, true).map(entry => entry.path)).toEqual(['/r/.git', '/r/a.ts', '/r/.git/.keep']) + expect(workspaceDirectories(tree, t, true)).toEqual({ '/r': {}, '/r/.git': {} }) + }) + + it('leaves out the kept levels below a hidden directory once hidden entries are no longer shown', () => { + const levels: FilesTreeState['levels'] = { + '/r': { kind: 'ready', level: { entries: [{ name: '.config', type: 'directory' }, { name: 'src', type: 'directory' }], truncated: false } }, + '/r/.config': { kind: 'ready', level: { entries: [{ name: 'app', type: 'directory' }, { name: 'config.json', type: 'file' }], truncated: false } }, + '/r/.config/app': { kind: 'ready', level: { entries: [{ name: 'a.json', type: 'file' }], truncated: false } }, + '/r/.configs': { kind: 'ready', level: { entries: [{ name: 'kept.json', type: 'file' }], truncated: false } }, + '/r/src': { kind: 'ready', level: { entries: [{ name: 'b.ts', type: 'file' }], truncated: false } }, + } + // `.configs` shares the hidden directory's name as a prefix but is not below it. + expect(workspaceEntries(levels, false).map(entry => entry.path)).toEqual(['/r/src', '/r/.configs/kept.json', '/r/src/b.ts']) + expect(workspaceEntries(levels, true).map(entry => entry.path)).toContain('/r/.config/app/a.json') + }) + + it('draws a search result directory without matches below it as a selection', () => { + expect(searchDirectories(tree)).toEqual({ '/r': { omitted: 'unmatched' }, '/r/.git': { omitted: 'unmatched' } }) + }) +}) diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 32d15ae638..7381b1f9d5 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: bc1c5164849937a8 - zh: e03adf54d2d5a668 + en: c7a9485c0cdcd9de + zh: 903ad54e44d79eae /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: - en: 5ea28139189887e9 - zh: f5a51f041c39b0fa + en: 35e983f0276188d0 + zh: df588dc1523031da /deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation: en: e4ec261d3b122eb5 zh: 320bb2efc93dccdc @@ -30,8 +30,8 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 45772c086f8a55f1 - zh: c80584bf49897b8f + en: 3c06acc93d7d4d59 + zh: b967155aec39df0c /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: en: dcbc58d4cad47fa8 zh: e962a8cbdfd4a914 @@ -57,8 +57,8 @@ en: de2762a99572475f zh: 9b41107ad14ebf8a /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work: - en: ee310ff3cd487639 - zh: 23793aa1c28a23af + en: ea983111988e4b9b + zh: c0ed7a583d2cad52 /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 764025ddfa..555c6fd2d9 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -25,7 +25,7 @@ Browse local subagent conversations and external tasks from the parent header. L ## Use this package -The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and loads nested catalogs only when their rows expand. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. +The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and discovers the next level on explicit activation. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. @@ -39,7 +39,7 @@ The wide root count trigger shows a 14px Users icon in its 14px slot when no chi Count, owner, and sidebar-action tooltips appear after 500ms of hover. Hovering a text-visible trigger opens its catalog after 150ms; leaving both trigger and catalog closes it after 120ms. Clicking the descendant-count trigger opens and pins its catalog, or closes an already pinned catalog. The icon-only count trigger does not open on hover, including when a pending hover crosses into the narrow layout. Clicking toggles its pinned menu; ArrowDown opens and pins the menu and focuses its first row. Outside click or Escape dismisses a pinned menu. Clicking moves focus into the panel, where ArrowDown/Home enters the first tree row and ArrowUp/End enters the last; Escape returns focus when it was inside. Breadcrumb-title clicks navigate to the corresponding conversation. -Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. A row is a known leaf only after its own catalog loads empty. +Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Clicking or keyboard-opening the menu reads its catalog and its direct children; expanding a branch does the same for that branch. Each activation reads direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests. It does not recursively discover deeper descendants. Hover and rendering do not initiate reads. Once started, a level read may finish after the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. ### Continuing a conversation @@ -61,11 +61,11 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `projectionsBySession` through the standard `useSessions` hook. The renderer selects `subagentCatalog` from each Session’s shared values for membership, disclosure, and counts. Activity prefers the unified UI status and falls back to Session summaries; summaries supply titles and usage. Expanding a row reads its target's projections, including ordinary cold history. A list row with `formatStatus: migration-required` displays “Migration required” before expansion and keeps its history-opening actions without descendant expansion or changing its subagent mode; a projection read requiring migration without a catalog supplies the same notice. Opening the Session supplies its catalog through history and control projections. Otherwise, an available catalog remains usable, including an explicit empty catalog. Live projection frames update every loaded level without menu subscriptions or repeated membership queries. Other rows remain expandable while their catalogs are absent, loading, or failed, and become known leaves after ready empty catalogs. External rows are always leaves and do not load child Sessions. +The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. An unread empty menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Opening a catalog dropdown does not request its root catalog. Child-catalog expansion and failed-read retries call `refreshProjection`; shared projection-value changes update the display automatically. +Explicit menu activation, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. @@ -123,6 +123,8 @@ Append-only. This package never edits earlier request tokens. These limits define what the catalog can show and what `@` references mean; they are current package constraints. - **Non-completed inactive outcomes remain grouped** — the catalog distinguishes a latest normal completion from other inactive states, but does not distinguish failure, cancellation, refusal, token exhaustion, or a child with no closed turn; the UI exposes no Activation identity, and stopping is limited to the composer's current-turn Stop for a running continuable child. +- **Ancestor menus require keyboard activation for uncached branches** — hovering does not read, and clicking the ancestor title navigates. Focus the title and press ArrowDown to prepare that level without leaving the current Session. +- **Level discovery stops on interruption** — an unexpected read rejection stops later siblings and is logged to the console. A reconnect can interrupt discovery before direct children are read; explicitly reopen the menu to prepare the level again. - **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 52d9abc110..056fad6cde 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并且只在行展开时加载嵌套目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 +会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 @@ -39,7 +39,7 @@ kind: "package-reference" 数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。 -目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有一行自身的目录加载为空后,它才是已知叶子。 +目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 ### 续接对话 @@ -61,11 +61,11 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子读取 `projectionsBySession`。renderer 从每个 Session 的共享值中选择 `subagentCatalog`,用于成员关系、展开控件与数量。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要提供标题与用量。展开行读取目标投影,包括普通冷历史。列表行的 `formatStatus` 为 `migration-required` 时,行在展开前即显示“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode;投影读取需要迁移且缺少目录时,也显示同一提示。打开会话后,历史与 control 投影提供其目录。其他情况下,已有目录仍可使用,包括显式空目录。实时 projection 帧更新所有已加载层级,无需菜单订阅或重复成员查询。其他行在目录缺席、加载中或失败时保持可展开,并在目录就绪且为空后成为已知叶子。外部行始终为叶子,不加载子 Session。 +页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -打开目录下拉菜单不会请求其根目录。展开子节点目录或重试失败读取时调用 `refreshProjection`;共享投影值的变化会自动更新显示。 +显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 @@ -123,6 +123,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 这些限制定义目录能显示什么、`@` 引用意味着什么;它们是当前包约束。 - **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。 +- **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。 +- **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。 - **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。 diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css index d3f58ad409..c450098395 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css @@ -350,8 +350,7 @@ } .label, -.secondaryLabel, -.summary { +.secondaryLabel { white-space: normal; overflow-wrap: anywhere; } @@ -370,14 +369,10 @@ color: var(--dsw-alias-label-tertiary); } -.summary, .metrics { color: var(--dsw-alias-label-tertiary); font-size: 10px; line-height: 15px; -} - -.metrics { display: grid; grid-template-rows: 17px 15px; flex: none; @@ -455,10 +450,6 @@ height: 23px; } -.children[aria-busy='true']::before { - content: none; -} - .children > .node::before { top: 0; bottom: 0; diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 92a802ac66..8cbb5be217 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -19,7 +19,7 @@ import type {} from './slots.ts' import css from './SubagentHeaderLineage.module.css' type SubagentCatalogSnapshot = Omit & { - state: 'loading' | 'ready' | 'migration-required' | 'error' + state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] } type Catalogs = Readonly> @@ -29,6 +29,8 @@ export type SubagentCatalogInjected = { openChild: (address: SubagentAddress) => void openChildAside: (address: SubagentAddress) => void refreshProjection: (parentSessionId: SessionId) => void + /** Read this catalog and its direct children after explicit activation or retry. */ + prepareCatalog: (parentSessionId: SessionId) => Promise } /** Root catalog actions and availability of its optional footer. */ @@ -203,9 +205,11 @@ function CatalogLoadingRows({ t }: { t: TranslateNS }) { return
    {t('loading.label')}
    } -/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ -function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { - return catalog?.state === 'ready' && catalog.entries.length === 0 +/** Only confirmed child membership exposes a branch disclosure. */ +function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { + return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required' } /** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ @@ -252,12 +256,12 @@ function CatalogRows({ return () => { clearInterval(timer) } }, [running]) const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => - entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required') + const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) return ( <> + {catalog.state === 'idle' && catalog.entries.length === 0 && ( +
    {t('load.idle')}
    + )} {emptyLoading && ( )} @@ -278,13 +282,10 @@ function CatalogRows({ const external = entry.mode === 'external' const childCatalog = catalogs[entry.id] const isCurrent = entry.id === currentSessionId - const knownLeaf = external || isKnownLeaf(childCatalog) const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' || childCatalog?.state === 'migration-required' - const canExpand = !knownLeaf && !requiresOpening + const canExpand = canExpandCatalog(entry, catalogs, summaries) const isExpanded = canExpand && expanded.has(entry.id) - const childLoading = childCatalog === undefined - || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) const summary = summaries[entry.id] const description = entry.label || summary?.title const name = entryName(entry) @@ -298,7 +299,7 @@ function CatalogRows({ : completed ? t('activity.completed') : t('activity.inactive') - const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] + const secondary = [secondaryLabel, mode, activity] .filter(value => value !== undefined) .join(' · ') const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) @@ -385,7 +386,6 @@ function CatalogRows({ {secondaryLabel !== undefined && ( {secondaryLabel} )} - {requiresOpening && {t('catalog.migrationRequired')}} {metrics !== '' && ( @@ -426,31 +426,35 @@ function CatalogRows({ )}
    - {isExpanded && ( + {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( +
    + {t('load.error')} + +
    + )} + {childCatalog !== undefined && isExpanded && (
    - {childCatalog === undefined - ? - : ( - - )} +
    )} @@ -497,7 +501,7 @@ type CatalogDropdownProps = CatalogDropdownSharedProps & ( function CatalogDropdown(props: CatalogDropdownProps) { const { rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false, + useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false, } = props const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined const projections = useSessions(state => state.projectionsBySession) @@ -507,7 +511,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { const projected = snapshot.values.subagentCatalog const state = snapshot.state === 'idle' - ? projected === undefined ? 'loading' : 'ready' + ? projected === undefined ? 'idle' : 'ready' : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state return [id, { state, @@ -521,6 +525,11 @@ function CatalogDropdown(props: CatalogDropdownProps) { })) }, [projections, summaries, statuses]) const catalog = catalogs[rootSessionId] + const prepareLevel = (sessionId: SessionId): void => { + void prepareCatalog(sessionId).catch((error: unknown) => { + console.error('[ui-subagent] catalog discovery failed:', error) + }) + } const [open, setOpen] = useState(false) const [expanded, setExpanded] = useState>(() => new Set()) const rootRef = useRef(null) @@ -546,7 +555,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'loading', error: null } + ? { entries: [], state: 'idle', error: null } : undefined) const cancelHoverClose = (): void => { @@ -622,7 +631,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { return } setExpanded(current => new Set(current).add(childSessionId)) - refreshProjection(childSessionId) + prepareLevel(childSessionId) } useEffect(() => { @@ -736,6 +745,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { } pinnedRef.current = true if (!open) changeOpen(true) + prepareLevel(rootSessionId) queueMicrotask(() => { menuRef.current?.focus() }) } : () => { @@ -748,6 +758,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { event.preventDefault() if (variant === 'count' && !allowsHoverOpen()) pinnedRef.current = true if (!open) changeOpen(true) + prepareLevel(rootSessionId) queueMicrotask(() => { focusAt(0) }) }} > @@ -804,7 +815,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { level={1} openChild={openChild} openChildAside={openChildAside} - refreshProjection={refreshProjection} + refreshProjection={prepareLevel} toggleBranch={toggleBranch} closeCatalog={() => { changeOpen(false) }} t={t} @@ -841,7 +852,7 @@ export function SubagentCatalogAction(props: SubagentCatalogActionProps) { /** Bind task-board visibility only in root conversations. */ function RootCatalogAction({ sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, t, renderSlot, + openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot, }: SubagentCatalogActionProps) { const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true && team.tasks.some(task => task.status !== 'deleted')) @@ -860,6 +871,7 @@ function RootCatalogAction({ openChild={openChild} openChildAside={openChildAside} refreshProjection={refreshProjection} + prepareCatalog={prepareCatalog} t={t} /> ) @@ -872,7 +884,7 @@ function RootCatalogAction({ */ export function SubagentHeaderLineage({ lineageSessionId, displayTitle, openTitle, - useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, t, + useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t, }: SubagentHeaderLineageProps) { const address = useSession(session => session.subagent?.address) const parentId = useSessions((state) => { @@ -883,7 +895,7 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t } + const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t } // Root sessions carry no breadcrumb; their descendant count lives in the // header actions band (SubagentCatalogAction). if (parentId === undefined) return null diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index a84992246d..b44d4f8e55 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -62,6 +62,19 @@ export function apply(ctx: ClientContext): void { preferNewPane: true, }) }, + async prepareCatalog(parentSessionId: SessionId) { + await ctx.sessions.refreshProjections(parentSessionId) + const parent = ctx.sessions.list.getSnapshot().projectionsBySession[parentSessionId] + if (parent?.state !== 'ready') return + for (const entry of parent.values.subagentCatalog ?? []) { + if (entry.mode === 'external') continue + const state = ctx.sessions.list.getSnapshot() + if (state.byId[entry.id]?.formatStatus === 'migration-required' + || state.projectionsBySession[entry.id]?.state === 'migration-required' + || state.projectionsBySession[entry.id]?.state === 'error') continue + await ctx.sessions.refreshProjections(entry.id) + } + }, refreshProjection(parentSessionId: SessionId) { void ctx.sessions.refreshProjections(parentSessionId) }, diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 27a5b61391..83754edd6c 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -26,8 +26,8 @@ export const zh = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': '正在加载子智能体…', + 'load.idle': '尚未加载子智能体', 'load.error': '无法加载子智能体', - 'catalog.migrationRequired': '需要迁移', 'retry': '重试', 'mode.external': '外部任务', 'mode.oneShot': '一次性', @@ -77,8 +77,8 @@ export const en: Record = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': 'Loading subagents…', + 'load.idle': 'Subagents not loaded', 'load.error': 'Unable to load subagents', - 'catalog.migrationRequired': 'Migration required', 'retry': 'Retry', 'mode.external': 'External task', 'mode.oneShot': 'one-shot', @@ -131,8 +131,8 @@ export const ja = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': 'サブエージェントを読み込み中…', + 'load.idle': 'サブエージェントは未読み込みです', 'load.error': 'サブエージェントを読み込めません', - 'catalog.migrationRequired': '移行が必要です', 'retry': '再試行', 'mode.external': '外部タスク', 'mode.oneShot': '単発', @@ -182,8 +182,8 @@ export const es = { 'tokens.million': '{value}M', 'tokens.total': 'Tok {value}', 'loading.label': 'Cargando subagentes…', + 'load.idle': 'Subagentes sin cargar', 'load.error': 'No se pueden cargar subagentes', - 'catalog.migrationRequired': 'Migración requerida', 'retry': 'Reintentar', 'mode.external': 'tarea externa', 'mode.oneShot': 'un solo disparo', @@ -233,8 +233,8 @@ export const fr = { 'tokens.million': '{value}M', 'tokens.total': 'Jeton {value}', 'loading.label': 'Chargement des sous-agents…', + 'load.idle': 'Sous-agents non chargés', 'load.error': 'Impossible de charger les sous-agents', - 'catalog.migrationRequired': 'Migration requise', 'retry': 'Réessayer', 'mode.external': 'Tâche externe', 'mode.oneShot': 'un coup', @@ -284,8 +284,8 @@ export const de = { 'tokens.million': '{value}M', 'tokens.total': '{value}-Token', 'loading.label': 'Subagenten werden geladen…', + 'load.idle': 'Subagenten nicht geladen', 'load.error': 'Subagenten können nicht geladen werden', - 'catalog.migrationRequired': 'Migration erforderlich', 'retry': 'Erneut versuchen', 'mode.external': 'Externe Aufgabe', 'mode.oneShot': 'One-Shot', @@ -335,8 +335,8 @@ export const ru = { 'tokens.million': '{value}M', 'tokens.total': '{value} ток', 'loading.label': 'Загрузка субагентов…', + 'load.idle': 'Субагенты не загружены', 'load.error': 'Невозможно загрузить субагенты', - 'catalog.migrationRequired': 'Требуется миграция', 'retry': 'Повторить', 'mode.external': 'Внешняя задача', 'mode.oneShot': 'одноразовый', @@ -386,8 +386,8 @@ export const pt = { 'tokens.million': '{value}M', 'tokens.total': '{value} valor', 'loading.label': 'Carregando subagentes…', + 'load.idle': 'Subagentes não carregados', 'load.error': 'Não foi possível carregar subagentes', - 'catalog.migrationRequired': 'Migração necessária', 'retry': 'Tentar novamente', 'mode.external': 'Tarefa externa', 'mode.oneShot': 'tiro único', diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index b5006a277b..83c5839e8d 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -4,7 +4,7 @@ import { Context } from '@deepseek-ai/cordis' import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { - SessionListState, SessionSnapshot, SessionSummary, + SessionListState, SessionSnapshot, SessionSummary, SessionProjectionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' @@ -35,7 +35,8 @@ const sid = (id: string) => id as SessionId function sessionsWith(sessions: SessionSummary[]) { const byId: Record = {} for (const s of sessions) byId[s.id] = s - const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: {} } + const projections: Record = {} + const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: projections } const actionCalls: { method: string; args: unknown[] }[] = [] const address: SubagentAddress = { parentSessionId: sid('parent'), @@ -48,6 +49,7 @@ function sessionsWith(sessions: SessionSummary[]) { subscribe: () => () => {}, }, actionCalls, + projections, subagentAddress: (childSessionId: SessionId) => childSessionId === address.childSessionId ? address : undefined, @@ -121,6 +123,40 @@ describe('apply', () => { expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) }) + it('reads direct child catalogs sequentially after reading the parent', async () => { + const { ctx, face } = await fullBench([...FAMILY, summary({ id: sid('legacy'), formatStatus: 'migration-required' })]) + onTestFinished(() => ctx.fiber.dispose()) + const entry = ctx.slots.entries('conversation.session.header.lineage') + .find(entry => entry.component === SubagentHeaderLineage)! + const actions = (entry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent')) + const projections = face.projections + const held = Promise.withResolvers() + const refresh = vi.spyOn(face, 'refreshProjections').mockImplementation(async (id) => { + if (id === sid('parent')) projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [ + { id: sid('external'), mode: 'external', createdAt: 1 }, + ...['c1', 'c2', 'legacy', 'blocked', 'failed'].map(id => ({ id: sid(id), mode: 'one-shot' as const, createdAt: 1 })), + ] } } + if (id === sid('c1')) { + await held.promise + projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [ + { id: sid('grandchild'), mode: 'one-shot', createdAt: 1 }, + ] } } + } + }) + onTestFinished(() => { refresh.mockRestore() }) + projections[sid('blocked')] = { state: 'migration-required', error: null, values: {} } + projections[sid('failed')] = { state: 'error', error: null, values: {} } + const reading = actions.prepareCatalog(sid('parent')) + await vi.waitFor(() => { expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')]]) }) + held.resolve(undefined) + await reading + expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')], [sid('c2')]]) + await actions.prepareCatalog(sid('c2')) + projections[sid('c2')] = { state: 'ready', error: null, values: {} } + await actions.prepareCatalog(sid('c2')) + expect(refresh.mock.calls.slice(3)).toEqual([[sid('c2')], [sid('c2')]]) + }) + it('registers catalog actions and selects read-only subagent composers from session facts', async () => { const { ctx, face } = await fullBench(FAMILY) const catalogEntry = ctx.slots.entries('conversation.session.header.lineage') diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 43d2255936..a70f41295e 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -75,31 +75,44 @@ function props( ) { const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested } const statuses: SessionStatusSnapshot = new Map() + const byId: Record = { + ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { + id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, projectionValues: { subagentCatalog: [] }, + }]))), + [CHILD]: { + id: CHILD, + title: '正在扫描项目文件', + displayTitle: 'worker', + running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), + retainedBy: {}, + blank: false, + updatedAt: Date.now(), + projectionValues: { subagentCatalog: [] }, + }, + ...summaries, + } const state = { ids: [CHILD], - byId: summaries ?? { - ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { - id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, - }]))), - [CHILD]: { - id: CHILD, - title: '正在扫描项目文件', - displayTitle: 'worker', - running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), - retainedBy: {}, - blank: false, - updatedAt: Date.now(), - }, - }, + byId, phase: 'ready', - projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { - state: catalog.state, error: catalog.error, - values: { - ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, - subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), - }, - }])) , + projectionsBySession: { + ...Object.fromEntries(Object.entries(byId).flatMap(([id, entry]) => entry.projectionValues === undefined ? [] : [[id, { + state: 'idle' as const, error: null, values: entry.projectionValues, + }]])), + ...Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { + state: catalog.state, error: catalog.error, + values: { + ...byId[id as SessionId]?.projectionValues, + ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, + subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), + }, + }])), + }, } satisfies SessionListState + for (const [id, entry] of Object.entries(byId)) { + const projection = state.projectionsBySession[id] + if (projection !== undefined) byId[id as SessionId] = { ...entry, projectionValues: projection.values } + } function useSessions(select: (snapshot: SessionListState) => T): T { return select(state) } @@ -142,6 +155,7 @@ function props( openChild: vi.fn(), openChildAside: vi.fn(), refreshProjection: vi.fn(), + prepareCatalog: vi.fn<(id: SessionId) => Promise>().mockResolvedValue(), renderSlot: vi.fn(() => null), lineageSessionId: PARENT, displayTitle: 'Parent title', @@ -528,8 +542,8 @@ describe('SubagentHeaderLineage', () => { expect(screen.getByText('worker')).toBeTruthy() expect(screen.queryByText('正在扫描项目文件')).toBeNull() expect(screen.getByRole('treeitem', { name: /reviewer child-2 · 一次性 · 当前未运行/ })).toBeTruthy() - expect(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })).toBeTruthy() - expect(screen.getByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeNull() const sidebarButton = within(screen.getByRole('treeitem', { name: /worker/ })) .getByRole('button', { name: '在侧边栏打开 worker' }) @@ -732,8 +746,11 @@ describe('SubagentHeaderLineage', () => { expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(1) }) - it('aligns a known leaf with siblings whose child catalog is still unknown', () => { - render() + it('aligns a known leaf with siblings whose child catalog contains descendants', () => { + render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(2) @@ -1043,6 +1060,7 @@ describe('SubagentHeaderLineage', () => { origin: 'subagent' as const, running: activity === 'running', projectionValues: { + subagentCatalog: [], subagentTiming: { settledMs, ...(id === 'finished' @@ -1111,6 +1129,7 @@ describe('SubagentHeaderLineage', () => { origin: 'subagent', running: true, projectionValues: { + subagentCatalog: [], subagentTiming: { settledMs: 0, active: { since: now - 5_000, through: now } }, }, }, @@ -1147,7 +1166,7 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(input.refreshProjection).toHaveBeenCalledWith(CHILD) + expect(input.refreshProjection).not.toHaveBeenCalled() const nested = screen.getByRole('treeitem', { name: /indexer/ }) expect(nested.getAttribute('aria-level')).toBe('2') @@ -1158,15 +1177,15 @@ describe('SubagentHeaderLineage', () => { }) }) - it('keeps ordinary cold descendants loading until their real catalog arrives', () => { + it('reveals cold descendants only when shared catalog data arrives', () => { const secondGrandchild = 'grandchild-2' as SessionId const summaries = { [CHILD]: { ...summary(CHILD, 1), running: true }, [GRANDCHILD]: { - ...summary(GRANDCHILD, 1), parentId: CHILD, origin: 'subagent' as const, + ...summary(GRANDCHILD, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const, }, [secondGrandchild]: { - ...summary(secondGrandchild, 1), parentId: CHILD, origin: 'subagent' as const, + ...summary(secondGrandchild, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const, running: true, }, } @@ -1176,11 +1195,11 @@ describe('SubagentHeaderLineage', () => { const current = { ...deferred, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) } const view = render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() - expect(deferred.refreshProjection).toHaveBeenCalledWith(CHILD) - expect(screen.getByRole('group').getAttribute('aria-busy')).toBe('true') - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(deferred.refreshProjection).not.toHaveBeenCalled() + expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByRole('treeitem', { name: '正在加载子智能体' })).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() @@ -1193,7 +1212,7 @@ describe('SubagentHeaderLineage', () => { }, } view.rerender() - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() @@ -1213,16 +1232,162 @@ describe('SubagentHeaderLineage', () => { }, summaries) state = { ...state, projectionsBySession: ready.useSessions(value => value.projectionsBySession) } view.rerender() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) expect(screen.getByRole('group').getAttribute('aria-busy')).toBeNull() expect(screen.getByRole('treeitem', { name: /indexer/ }).querySelector('[data-state="idle"]')).not.toBeNull() expect(screen.getByRole('treeitem', { name: /critic/ }).querySelector('[data-state="ongoing"]')).not.toBeNull() expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() - expect(deferred.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(deferred.refreshProjection).not.toHaveBeenCalled() expect(deferred.openChild).not.toHaveBeenCalled() }) - it.each([false, true])('shows list migration status before expanding, with cached descendants=%s', (cached) => { + it.each([ + { running: true, completed: false, dot: 'ongoing' }, + { running: false, completed: true, dot: 'done' }, + { running: false, completed: false, dot: 'idle' }, + ])('preserves the $dot activity marker while an unknown directory loads', ({ running, completed, dot }) => { + const input = props(catalog({ entries: [{ + id: CHILD, mode: 'continuable', label: 'worker', activity: running ? 'running' : 'inactive', + }] }), {}, { [CHILD]: { + ...summary(CHILD, 1), running, + projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: completed } }, + } }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) + const row = screen.getByRole('treeitem', { name: /worker/ }) + const marker = row.querySelector(`[data-state="${dot}"]`) + expect(marker).not.toBeNull() + expect(row.children).toHaveLength(1) + expect(input.refreshProjection).not.toHaveBeenCalled() + + state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: { + ...state.projectionsBySession[CHILD]!, state: 'loading', + } } } + view.rerender() + expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(row) + expect(row.querySelector(`[data-state="${dot}"]`)).toBe(marker) + expect(screen.queryByText('正在加载子智能体…')).toBeNull() + expect(row.hasAttribute('aria-busy')).toBe(false) + expect(row.hasAttribute('aria-expanded')).toBe(false) + expect(within(row).getByRole('button', { name: '在侧边栏打开 worker' }).hasAttribute('disabled')).toBe(false) + expect(input.refreshProjection).not.toHaveBeenCalled() + }) + + it('leaves missing catalogs unread and retries only an explicitly selected failure', () => { + const input = props(catalog(), {}, { [CHILD]: summary(CHILD, 1) }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() + + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, + [CHILD]: { state: 'error', values: {}, error: new RemoteError('gateway/internal', 'private diagnostic', {}) }, + } } + view.rerender() + expect(screen.getByRole('alert').textContent).toContain('无法加载子智能体') + expect(screen.queryByText('private diagnostic')).toBeNull() + expect(screen.queryByRole('status')).toBeNull() + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '重试' })) + expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]]) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(input.openChild).not.toHaveBeenCalled() + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, [CHILD]: { state: 'ready', values: { subagentCatalog: [] }, error: null }, + } } + view.rerender() + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull() + }) + + it('expands cached shared projections without reading the next level', () => { + const childSummary = { ...summary(CHILD, 1), projectionValues: { subagentCatalog: [ + { id: GRANDCHILD, createdAt: 1, mode: 'continuable' as const, label: 'indexer' }, + ] } } + const input = props(catalog(), {}, { [CHILD]: childSummary, [GRANDCHILD]: summary(GRANDCHILD, 1) }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy() + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull() + + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, [CHILD]: { state: 'ready', error: null, values: { subagentCatalog: [] } }, + } } + view.rerender() + expect(screen.queryByRole('button', { name: '收起 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + }) + + it('updates disclosure when a visible leaf gains children without fetching any level', () => { + const input = props(catalog()) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + const worker = screen.getByRole('treeitem', { name: /worker/ }) + expect(worker.hasAttribute('aria-expanded')).toBe(false) + state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: { + state: 'idle', error: null, values: { + subagentCatalog: [{ id: GRANDCHILD, createdAt: 1, mode: 'continuable', label: 'indexer' }], + }, + } } } + view.rerender() + expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(worker) + expect(worker.getAttribute('aria-expanded')).toBe('false') + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy() + }) + + it('prepares only explicitly opened levels', () => { + const input = props(catalog(), { + [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), + }) + render() + const trigger = screen.getByRole('button', { name: /\d+ 个子智能体$/ }) + hoverCatalog(trigger) + expect(input.prepareCatalog).not.toHaveBeenCalled() + fireEvent.click(trigger) + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]]) + fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }) + expect(input.prepareCatalog).toHaveBeenCalledTimes(2) + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + expect(input.prepareCatalog.mock.calls.at(-1)).toEqual([PARENT]) + }) + + it('reports an unexpected explicit catalog failure', async () => { + const input = props(catalog()) + const failure = new Error('projection reader failed') + input.prepareCatalog.mockRejectedValueOnce(failure) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + render() + fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) + await vi.waitFor(() => { expect(report).toHaveBeenCalledWith('[ui-subagent] catalog discovery failed:', failure) }) + } finally { + report.mockRestore() + } + }) + + it.each([false, true])('keeps legacy rows navigable without a migration notice, with cached descendants=%s', (cached) => { const input = props(catalog(), cached ? { [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), } : {}, { @@ -1235,7 +1400,8 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(trigger) const child = screen.getByRole('treeitem', { name: /worker/ }) - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() fireEvent.keyDown(child, { key: 'ArrowRight' }) expect(input.refreshProjection).not.toHaveBeenCalled() @@ -1248,8 +1414,13 @@ describe('SubagentHeaderLineage', () => { view.rerender() hoverCatalog(trigger) expect(screen.queryByText(/需要迁移/)).toBeNull() - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + if (cached) { + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + } else { + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(input.refreshProjection).not.toHaveBeenCalled() + } }) it.each(['ready', 'migration-required'] as const)('stops at a migration-required child until its real catalog arrives with %s read state', (readState) => { @@ -1272,7 +1443,7 @@ describe('SubagentHeaderLineage', () => { const current = { ...input, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) } const view = render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() state = { @@ -1287,15 +1458,15 @@ describe('SubagentHeaderLineage', () => { expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByRole('treeitem', { name: /ordinary-fork/ })).toBeNull() const child = screen.getByRole('treeitem', { name: /worker/ }) - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByText(/模式未知/)).toBeNull() - expect(en['catalog.migrationRequired']).toBe('Migration required') expect(child.hasAttribute('aria-expanded')).toBe(false) expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() expect(screen.queryByRole('group')).toBeNull() expect(screen.queryByText('正在加载子智能体…')).toBeNull() fireEvent.keyDown(child, { key: 'ArrowRight' }) - expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(input.refreshProjection).not.toHaveBeenCalled() expect(input.openChild).not.toHaveBeenCalled() fireEvent.click(child) expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ @@ -1347,7 +1518,8 @@ describe('SubagentHeaderLineage', () => { fireEvent.keyDown(child, { key: 'ArrowRight' }) fireEvent.keyDown(child, { key: 'ArrowRight' }) expect(input.refreshProjection).not.toHaveBeenCalled() - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByText(/模式未知/)).toBeNull() expect(child.hasAttribute('aria-expanded')).toBe(false) expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() @@ -1406,7 +1578,30 @@ describe('SubagentHeaderLineage', () => { expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() }) - it('closes expanded descendants even when their own catalogs have not arrived', () => { + it('collapses expanded descendants whose catalog is removed before their parent closes', () => { + const input = props(catalog(), { + [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), + [GRANDCHILD]: catalog({ entries: [{ id: 'great-grandchild' as SessionId, mode: 'continuable', label: 'deep', activity: 'inactive' }] }), + }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' })) + const { [GRANDCHILD]: _projection, ...projectionsBySession } = state.projectionsBySession + const { [GRANDCHILD]: _summary, ...byId } = state.byId + state = { ...state, projectionsBySession, byId } + view.rerender() + fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + state = input.useSessions(value => value) + view.rerender() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-expanded')).toBe('false') + }) + + it('closes a branch while the visible descendants are loading', () => { const input = props(catalog(), { [CHILD]: catalog({ entries: [{ @@ -1414,11 +1609,12 @@ describe('SubagentHeaderLineage', () => { label: 'indexer', activity: 'running', }], }), - }) + }, { [GRANDCHILD]: summary(GRANDCHILD, 1) }) render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull() + expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-busy')).toBeNull() fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() @@ -1443,7 +1639,8 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(screen.getByRole('button', { name: /0 个子智能体/ })) expect(screen.getByText('index down')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: /重试/ })) - expect(failed.refreshProjection).toHaveBeenCalledWith(PARENT) + expect(failed.prepareCatalog).toHaveBeenCalledExactlyOnceWith(PARENT) + expect(failed.refreshProjection).not.toHaveBeenCalled() }) it.each(['absent', 'idle', 'loading', 'ready'] as const)('does not expose header-only descendants when the projection read is %s', (state) => { @@ -1584,7 +1781,9 @@ describe('SubagentHeaderLineage', () => { const switcher = screen.getByRole('button', { name: '切换子智能体:worker' }) hoverCatalog(switcher) - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(input.prepareCatalog).not.toHaveBeenCalled() + expect(screen.getByText('尚未加载子智能体')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryAllByRole('treeitem')).toEqual([]) expect(input.refreshProjection).not.toHaveBeenCalled() }) @@ -1690,11 +1889,30 @@ describe('SubagentHeaderLineage', () => { const switcher = screen.getByRole('button', { name: '切换子智能体:正在扫描项目文件' }) expect(input.refreshProjection).not.toHaveBeenCalled() hoverCatalog(switcher) - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(input.prepareCatalog).not.toHaveBeenCalled() + expect(screen.getByText('尚未加载子智能体')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryAllByRole('treeitem')).toEqual([]) expect(input.refreshProjection).not.toHaveBeenCalled() }) + it.each(['idle', 'loading'] as const)('shows the actual %s state of an empty title menu', (state) => { + const input = { + ...props(undefined, {}, {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }), + lineageSessionId: CHILD, + displayTitle: 'worker', + } + const initial = input.useSessions(value => value) + render( select({ + ...initial, + projectionsBySession: { [PARENT]: { state, error: null, values: {} } }, + })} />) + hoverCatalog(screen.getByRole('button', { name: '切换子智能体:worker' })) + expect(screen.getByText(state === 'idle' ? zh['load.idle'] : zh['loading.label'])).toBeTruthy() + expect(screen.queryByText(state === 'idle' ? zh['loading.label'] : zh['load.idle'])).toBeNull() + expect(input.prepareCatalog).not.toHaveBeenCalled() + }) + it('keeps a nested title switcher scoped to its direct-parent catalog', () => { const input = { ...props(catalog(), { diff --git a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json index 6a08bf158f..f2f0c5559d 100644 --- a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json +++ b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json @@ -43,7 +43,7 @@ ".instruction: border-radius: 16px", ".delivery: border-radius: 8px" ], - "ui-settings-account/src/client/AccountNotice.module.css": [ + "ui-account-notifications/src/client/AccountNotifications.module.css": [ ".card: border-radius: 16px" ], "ui-settings-account/src/client/DesktopOnboarding.module.css": [ diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 4182c93cfe..59dfd47110 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-tool/use-this-package: - en: 09231e7cc6515a01 - zh: c306bb141cf9bf9d + en: 4d8cb38024095705 + zh: 1baf6fa42f3fb80f /deepseek-ai-dsh-client-ui-tool/use-this-package/registering-a-business-tool-view: en: e458aff61e634190 zh: 650e417f450b3edf diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index b460da0f8f..448a4e197b 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Tool calls appear in the conversation as cards: a root call tree with its nested subcalls, each atomic call rendered by its owning view. Every lifecycle state retains the tool's ordinary business glyph; failure and interruption remain explicit through the frozen call/result state, accessible status text, and failure summary. Users can open files or inspect calls through the Host callbacks. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Text agent lists show each agent name, or the historical ID, above a single-line description, with compact spacing and recorded status. Click the description to expand or collapse its full text; its accessible name follows the selected locale. +Tool calls appear in the conversation as cards: a root call tree with its nested subcalls, each atomic call rendered by its owning view. Every lifecycle state retains the tool's ordinary business glyph; failure and interruption remain explicit through the frozen call/result state, accessible status text, and failure summary. Users can open files or inspect calls through the Host callbacks. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Agent lists show the full description above the name, or the historical ID, with compact spacing and recorded status. Both lines wrap as needed and have no disclosure arrows; rows without a description show only the name. Settled foreground commands with a nonzero exit code, a terminating signal, or an explicit missing exit code keep their description in the ordinary gray text and show a neutral capsule with a red dot immediately after it. The capsule displays only the recorded code, signal, or localized missing-code status and stays on the same line; the description truncates with an ellipsis to reserve its space. Running, successful, and background calls omit it. Generic execution errors and stopped summaries retain their error and warning colors, including on hover. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 3b7811a823..37757c47a7 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。文本形式的智能体列表以紧凑间距展示智能体名称(历史记录为 ID)、下方的单行描述及记录中的状态。点击描述可展开或收起全文;其无障碍名称使用当前语言。 +工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。智能体列表以紧凑间距在上方展示完整描述,下方展示名称(历史记录为 ID),并保留记录中的状态。两行均按需换行,不带展开箭头;没有描述时只显示名称。 已结束的前台命令若返回非零退出码、终止信号,或明确记录为无退出码,描述保持普通灰色,后面紧接带红点的中性胶囊。胶囊仅显示记录的退出码、信号或本地化的“未正常退出”状态,并保持在同一行;描述超出可用宽度时显示省略号,为胶囊预留空间。运行中、成功和后台调用不显示胶囊。通用执行错误与停止摘要仍保留错误色和警告色,悬停时也不改变。 diff --git a/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css b/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css index 0180f9fa0d..44d9f2ef8d 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css @@ -188,42 +188,6 @@ padding: 6px 10px 4px; } -.subtitleToggle { - display: flex; - align-items: flex-start; - gap: 4px; - width: 100%; - padding: 0; - border: 0; - background: transparent; - color: var(--dsw-alias-label-tertiary); - font: inherit; - font-size: 12px; - text-align: left; - cursor: pointer; -} - -.subtitleToggle > span { - min-width: 0; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; -} - -.subtitleToggle > svg { - flex: none; - margin-top: 3px; -} - -.subtitleToggle[aria-expanded='true'] > span { - white-space: pre-wrap; - overflow-wrap: anywhere; -} - -.subtitleToggle[aria-expanded='true'] > svg { - transform: rotate(90deg); -} - .description { margin: 6px 0; color: var(--dsw-alias-label-caption); diff --git a/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx b/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx index 84ee30b93b..65e4db7c84 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx +++ b/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx @@ -1,5 +1,4 @@ /** Compact, read-only fields and lists for recorded Tool results. */ -import { useState } from 'react' import { CodeBlock, MarkdownText, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconPlayOutlineRegular, } from '@deepseek-ai/dsh-client-ui-primitives' @@ -28,7 +27,7 @@ export interface ToolDetailItem { /** Localized display data shared by the built-in detail cards. */ export interface ToolDetailsModel { items: readonly ToolDetailItem[] - /** Tight rows with single-line subtitles that can expand in place. */ + /** Tight spacing for recorded entity rows. */ compact?: boolean summary?: string /** Header text while expanded, omitting a receipt status shown in the body. */ @@ -43,9 +42,8 @@ interface DetailContentProps { onOpenFile?: ((path: string, options?: OpenFileOptions) => void) | undefined } -function DetailItem({ item, compact, t, onOpenFile }: { item: ToolDetailItem; compact?: boolean | undefined } & DetailContentProps) { +function DetailItem({ item, t, onOpenFile }: { item: ToolDetailItem } & DetailContentProps) { const status = item.status - const [expanded, setExpanded] = useState(false) return (
  • {item.title !== undefined && ( @@ -77,19 +75,7 @@ function DetailItem({ item, compact, t, onOpenFile }: { item: ToolDetailItem; co )} )} - {item.subtitle !== undefined && (compact ? ( - - ) :
    {item.subtitle}
    )} + {item.subtitle !== undefined &&
    {item.subtitle}
    } {item.description !== undefined &&

    {item.description}

    } {item.fields.length > 0 && (
    @@ -144,7 +130,7 @@ export function ToolDetails({ model, hasInspect = false, t, onOpenFile }: { {model.caption !== undefined &&
    {model.caption}
    } {model.items.length === 0 ?

    {model.empty}

    : (
      - {model.items.map((item, index) => )} + {model.items.map((item, index) => )}
    )} {model.unchanged !== undefined && ( diff --git a/packages/client/ui-tool/src/client/tool/models/control-details-model.ts b/packages/client/ui-tool/src/client/tool/models/control-details-model.ts index ef6fb9a8a5..c7f73005b0 100644 --- a/packages/client/ui-tool/src/client/tool/models/control-details-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/control-details-model.ts @@ -29,7 +29,14 @@ function teamTaskItems(value: unknown, t: DetailTranslate): DetailItem[] { } function agentList(text: string, json: unknown, t: DetailTranslate): ToolDetailsModel | null { - if (Array.isArray(json)) return detailList(inspectionItems(json, t), t('detail.agents.count', { count: json.length }), t) + if (Array.isArray(json)) { + const items = inspectionItems(json, t).map((item) => { + if (item.title === undefined || item.description === undefined) return item + const { title, description, ...rest } = item + return { ...rest, title: description, subtitle: title } + }) + return { ...detailList(items, t('detail.agents.count', { count: json.length }), t), compact: true } + } if (text === '(no subagents)') return detailList([], t('detail.agents.count', { count: 0 }), t) const items: DetailItem[] = [] for (const line of text.split('\n')) { @@ -39,7 +46,7 @@ function agentList(text: string, json: unknown, t: DetailTranslate): ToolDetails const [, agent, state, title] = match if (agent === undefined || state === undefined) return null items.push({ - title: agent, ...(title === undefined ? {} : { subtitle: title }), + title: title || agent, ...(title ? { subtitle: agent } : {}), badge: detailBadge(state, t), fields: [], }) diff --git a/packages/client/ui-tool/tests/details-models.client.spec.ts b/packages/client/ui-tool/tests/details-models.client.spec.ts index 7147aff0f7..bbf9f5f2e8 100644 --- a/packages/client/ui-tool/tests/details-models.client.spec.ts +++ b/packages/client/ui-tool/tests/details-models.client.spec.ts @@ -93,20 +93,20 @@ describe('control detail adapters', () => { const agents = details('list_agents', 'lead [running] — root agent\nreviewer/checker [inactive] — Check tests\nold-id [unavailable]') expect(agents?.summary).toBe('3 agents') expect(agents?.items).toEqual([ - { title: 'lead', subtitle: 'root agent', badge: { label: 'Running', tone: 'info' }, fields: [] }, - { title: 'reviewer/checker', subtitle: 'Check tests', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, + { title: 'root agent', subtitle: 'lead', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'Check tests', subtitle: 'reviewer/checker', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, { title: 'old-id', badge: { label: 'Unavailable', tone: 'neutral' }, fields: [] }, ]) const historical = details('list_agents', 'a1 [running] — Build\na2 [ready] parent=a1 depth=1 — Review\na3 [diagnostic: corrupt] parent=a1 depth=1', { scope: 'descendants' }) expect(historical?.summary).toBe('3 agents') expect(historical?.items).toEqual([ - { title: 'a1', subtitle: 'Build', badge: { label: 'Running', tone: 'info' }, fields: [] }, - { title: 'a2', subtitle: 'Review', badge: { label: 'Ready', tone: 'neutral' }, fields: [] }, + { title: 'Build', subtitle: 'a1', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'Review', subtitle: 'a2', badge: { label: 'Ready', tone: 'neutral' }, fields: [] }, { title: 'a3', badge: { label: 'diagnostic: corrupt', tone: 'neutral' }, fields: [] }, ]) const structured = details('list_agents', JSON.stringify([{ name: 'lead', status: 'running', description: 'root agent' }, { name: 'reviewer', status: 'inactive' }])) expect(structured?.items).toEqual([ - { title: 'lead', description: 'root agent', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'root agent', subtitle: 'lead', badge: { label: 'Running', tone: 'info' }, fields: [] }, { title: 'reviewer', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, ]) expect(details('list_agents', 'reviewer running')).toBeNull() diff --git a/packages/client/ui-tool/tests/details-row.client.spec.tsx b/packages/client/ui-tool/tests/details-row.client.spec.tsx index b5dde4a667..e21206109f 100644 --- a/packages/client/ui-tool/tests/details-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/details-row.client.spec.tsx @@ -153,26 +153,17 @@ describe('todosDetail', () => { }) describe('DetailsRow', () => { - it('puts agent names first and lets a compact description expand and collapse', () => { + it('shows the full agent description above its name without a disclosure', () => { const description = 'Verify every construction bound. '.repeat(20) const block = { ...result('list_agents', null), content: [{ type: 'text' as const, text: `reviewer/checker [running] — ${description}` }] } const model = detailsCardModel(block, t, 'en')! render() const name = screen.getByText('reviewer/checker') - const toggle = screen.getByRole('button', { name: 'Expand description for reviewer/checker' }) - expect(name.compareDocumentPosition(toggle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(toggle.textContent).toBe(description) - fireEvent.click(toggle) - expect(screen.getByRole('button', { name: 'Collapse description for reviewer/checker' }).getAttribute('aria-expanded')).toBe('true') - fireEvent.click(toggle) - expect(toggle.getAttribute('aria-expanded')).toBe('false') - }) - - it('uses an unqualified accessible name when a compact description has no title', () => { - render() - const toggle = screen.getByRole('button', { name: 'Expand' }) - fireEvent.click(toggle) - expect(screen.getByRole('button', { name: 'Collapse' })).toBe(toggle) + const title = screen.getByText(description.trim()) + expect(title.compareDocumentPosition(name) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(screen.getByRole('listitem').textContent).toBe(`${description}Runningreviewer/checker`) + expect(screen.queryByRole('button')).toBeNull() + expect(screen.getByRole('listitem').querySelector('svg')).toBeNull() }) it('expands fields with the keyboard and keeps Inspect available', () => { diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index c6dfd004d4..e0ee44c80a 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -126,7 +126,7 @@ function sessionSnapshot(nodes: LegacyConversationSlice['nodes']): SessionSnapsh openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: nodes.length === 0, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx index 41e0e6902f..31b9296885 100644 --- a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx @@ -43,7 +43,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx index b3fdffda6b..3e924b4576 100644 --- a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx @@ -49,7 +49,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 7d850ef9c6..e8365eb4c0 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -33,8 +33,8 @@ en: 9fb88260380bf093 zh: 3bace2b96ecd4a82 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: - en: 668ee06286b227b6 - zh: aafdb03cde1b93c9 + en: 249d9552d8bef805 + zh: 405b1c636cba8e0b /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation: en: 8f170900a4096408 zh: 85332e80adf39403 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 2ac681b7ca..fb4c55b2d2 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -85,7 +85,7 @@ Session rows share their existing action contributions between right-click and t `ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?, options?)` opens a Workspace blank only if no later navigation has superseded the request; New Session opens the same blank as Workspace reopening, so it returns to that blank's unsent draft. `forkSession(id, onCreated?, options?)` creates the child without navigating or superseding a pending navigation; `allowMigration` carries the caller's migration permission. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. -Session and Workspace rows derive their affordances from the browser root's access Hooks: the global `useRemoteAccess('session/create')` gates every New Session entry, `useWorkspaceAccess` gates a Workspace's create, rename, delete, and reorder verbs, and `useSessionAccess` gates a Session row's rename, fork, drag, pin, archive, and unarchive verbs plus the search result's restore control. A refused verb is not rendered, while every Host request remains authoritative. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. +Session and Workspace rows derive their affordances from the browser root's access Hooks: `useWorkspaceAccess` gates a Workspace's create, rename, delete, and reorder verbs, and `useSessionAccess` gates a Session row's rename, fork, drag, pin, archive, and unarchive verbs plus the search result's restore control. A refused verb is not rendered, while every Host request remains authoritative. The Ungrouped header offers no New Session, because it has no backing Workspace to start one in. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent, except that restoring a saved blank first reloads that Session's projections, because listed values are cached hints that can lag its log after an unclean Host exit. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 62d749464a..2037167c1c 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -85,7 +85,7 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** `ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?, options?)` 仅在请求未被后续导航替代时打开工作区空白 Session;新会话与重新打开工作区打开同一个空白会话,因此会回到该空白会话中未发送的草稿。`forkSession(id, onCreated?, options?)` 创建子会话,不导航,也不替代尚未完成的导航;`allowMigration` 携带调用方的迁移许可。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。 -Session 行与 Workspace 行的可用操作来自浏览器根的访问 Hook:全局 `useRemoteAccess('session/create')` 门控所有新建会话入口,`useWorkspaceAccess` 门控 Workspace 的新建、重命名、删除与排序动作,`useSessionAccess` 门控 Session 行的重命名、分叉、拖拽、置顶、归档与取消归档动作,以及搜索结果的恢复控件。被拒绝的动作不渲染,但每个发往 Host 的请求仍以其授权为准。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 +Session 行与 Workspace 行的可用操作来自浏览器根的访问 Hook:`useWorkspaceAccess` 门控 Workspace 的新建、重命名、删除与排序动作,`useSessionAccess` 门控 Session 行的重命名、分叉、拖拽、置顶、归档与取消归档动作,以及搜索结果的恢复控件。被拒绝的动作不渲染,但每个发往 Host 的请求仍以其授权为准。Ungrouped 标题行不提供新建会话,因为它没有可在其中新建会话的后备 Workspace。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影;例外是恢复已保存的空白会话时先重新加载该 Session 的投影,因为列表中的值是缓存提示,Host 非正常退出后可能落后于其日志。 diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx index 5af8eba9e6..04b56cb10c 100644 --- a/packages/client/ui-workspace/src/client/rows/Rows.tsx +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -223,31 +223,32 @@ type ProjectRowItemProps = { newShortcut?: ShortcutCatalogEntry | undefined containsCurrentDescendant?: boolean onToggle: () => void - onCreate: () => void + onCreate: (workspaceId: WorkspaceId) => void /** Present only for real Workspace rows in the grouped view. */ drag?: WorkspaceRowDragProps | undefined /** Host account home; POSIX home-rooted hover paths display as `~`. */ home?: string | undefined t: RowTranslate -} & Pick +} & Pick -/** Which of one header row's actions the caller's access snapshot allows. */ -interface ProjectRowAccess { - readonly create: boolean +/** The header actions one row offers; an absent create offers no New Session button. */ +interface ProjectRowActions { + readonly create?: (() => void) | undefined readonly reorder: boolean } /** * Project (workspace) header row: folder + title; - * hover reveals the chevron and create button, and dwelling on a real - * Workspace shows its hover card (the ungrouped bucket has none). + * hover reveals the chevron and, on a real Workspace, the create button; + * dwelling on a real Workspace shows its hover card. The ungrouped bucket + * has neither, because it has no backing Workspace to start a Session in. * `containsCurrent` arrives on the node (derivation fact, no renderer scan). * Create and drag follow the Workspace access snapshot. Menu providers own * their access checks; the ungrouped bucket has no Workspace menu. * @param props.group - derived group node. * @param props.containsCurrentDescendant - highlight an ancestor even when its subtree is collapsed. * @param props.onToggle - expand/collapse the group. - * @param props.onCreate - start a frontend Session inside this Workspace. + * @param props.onCreate - start a frontend Session inside the given Workspace. * @param props.drag - optional workspace-row drag wiring. * @param props.home - host account home for POSIX hover-path abbreviation. * @param props.t - the browser root's locale seat. @@ -260,28 +261,29 @@ export function ProjectRowItem(props: ProjectRowItemProps) { : } -/** The ungrouped bucket's header: no Workspace resource, so starting a Session there asks the global resource. */ +/** The ungrouped bucket's header: no backing Workspace to start a Session in or reorder. */ function UngroupedProjectRow(props: ProjectRowItemProps) { - const create = props.useRemoteAccess('session/create') - return + return } /** A real Workspace's header: every action asks that Workspace's resource. */ function WorkspaceProjectRow({ workspaceId, ...props }: ProjectRowItemProps & { workspaceId: WorkspaceId }) { const { useWorkspaceAccess } = props - const access: ProjectRowAccess = { - create: useWorkspaceAccess(workspaceId, 'session/create'), + const create = useWorkspaceAccess(workspaceId, 'session/create') + const actions: ProjectRowActions = { + create: create ? () => { props.onCreate(workspaceId) } : undefined, reorder: useWorkspaceAccess(workspaceId, 'workspace/insertBefore'), } - return + return } function ProjectRow({ - group, containsCurrentDescendant = false, onToggle, onCreate, drag: offeredDrag, home, newShortcut, t, access, + group, containsCurrentDescendant = false, onToggle, drag: offeredDrag, home, newShortcut, t, actions, renderFactorySlot, useContextMenuTarget, useContextMenu, -}: ProjectRowItemProps & { access: ProjectRowAccess }) { +}: Omit & { actions: ProjectRowActions }) { const { getTriggerProps } = useContextMenu() - const drag = access.reorder ? offeredDrag : undefined + const drag = actions.reorder ? offeredDrag : undefined + const create = actions.create const row = group // The ungrouped bucket has no workspace title: its label is dictionary copy. const label = row.workspaceId === undefined ? t('group.ungrouped') : row.label @@ -326,14 +328,14 @@ function ProjectRow({ className: css.iconButton, }) )} - {access.create && ( + {create !== undefined && ( diff --git a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx index 160a10bc6e..f7c7f1ff04 100644 --- a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx @@ -254,7 +254,7 @@ type SessionTreeProps = Pick< WorkspaceBrowserProps, 'useSessionStatus' | 'startSession' | 'open' | 'renderFactorySlot' | 'useContextMenuTarget' | 'useContextMenu' | 'insertWorkspaceBefore' | 't' | 'usePanelInfo' - | 'useRemoteAccess' | 'useSessionAccess' | 'useWorkspaceAccess' + | 'useSessionAccess' | 'useWorkspaceAccess' > & PropsRenderSlots< | 'sidebar.workspaces.session.row.action' | 'sidebar.session.row.trailing' @@ -314,7 +314,7 @@ function EmptySessions({ rowState, onLeaveArchivedOnly, t }: Pick row.id === 'session.new')} group={group} renderFactorySlot={renderFactorySlot} useContextMenu={useContextMenu} useContextMenuTarget={useContextMenuTarget} - useRemoteAccess={useRemoteAccess} useWorkspaceAccess={useWorkspaceAccess} containsCurrentDescendant={currentAncestors.has(group.key)} home={home} @@ -564,11 +563,9 @@ function SessionTree({ if (group.expanded) dropWatermarks(key => withinGroup(key, group.key)) setGroupExpanded(group.key, !group.expanded) }} - onCreate={() => { - if (group.workspaceId !== undefined) { - setGroupExpanded(group.key, true) - startSession(group.workspaceId) - } + onCreate={(workspaceId) => { + setGroupExpanded(group.key, true) + startSession(workspaceId) }} drag={workspaceDragProps} /> @@ -900,7 +897,6 @@ export function WorkspaceBrowser({ useSectionScroller, useSessions, useSessionStatus, - useRemoteAccess, useSessionAccess, useWorkspaceAccess, useWorkspaces, @@ -1400,7 +1396,6 @@ export function WorkspaceBrowser({ ) : ( { } }) - it('asks the global resource before the Ungrouped header offers New Session', async () => { + it('never offers New Session on the Ungrouped header, even under a global grant', async () => { const access = new ClientAccessState({ type: 'baseline', owner: false, grants: [] }) const runtime = await bench(access, { ungroupedSession: 'loose' as SessionId }) try { @@ -141,7 +141,7 @@ describe('Workspace header actions under the page access snapshot', () => { act(() => { access.update({ type: 'upsert', grant: { resource: { kind: 'global' }, actions: ['session/create'] } }) }) - expect(screen.getByRole('button', { name: '在“未分组”中新建会话' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '在“未分组”中新建会话' })).toBeNull() } finally { await runtime.dispose() } diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 2b9e35a397..0cc4cac028 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -64,11 +64,11 @@ function SessionNodeItem({ renderSlot = renderNoRowEntries, onRenameRequest = () // Direct header specs hold every access answer unless the case refuses one. function ProjectRowItem({ - useRemoteAccess = allowAllAccess.useRemoteAccess, useWorkspaceAccess = allowAllAccess.useWorkspaceAccess, + useWorkspaceAccess = allowAllAccess.useWorkspaceAccess, renderFactorySlot = renderMenuButton, useContextMenuTarget = select => select(null), ...props -}: Omit - & Partial>) { - return + & Partial>) { + return } @@ -707,19 +707,17 @@ describe('workspace browser rows', () => { view.rerender() expect(screen.getByRole('treeitem').getAttribute('draggable')).toBe('true') fireEvent.click(screen.getByRole('button', { name: '在“Project”中新建会话' })) - expect(props.onCreate).toHaveBeenCalledOnce() + expect(props.onCreate).toHaveBeenCalledExactlyOnceWith(props.group.workspaceId) }) - it('ungrouped bucket asks the global resource whether it may start a Session', () => { + it('ungrouped bucket offers no New Session and asks no access', () => { const group: GroupNode = { key: 'ungrouped', workspaceId: undefined, cwd: undefined, createdAt: undefined, label: '', sessionCount: 0, expanded: false, containsCurrent: false, sessions: [], } - const useRemoteAccess = vi.fn((action: string) => action !== 'session/create') const useWorkspaceAccess = vi.fn(() => true) render() - expect(useRemoteAccess).toHaveBeenCalledWith('session/create') + useWorkspaceAccess={useWorkspaceAccess} />) expect(useWorkspaceAccess).not.toHaveBeenCalled() expect(screen.queryByRole('button', { name: /新建会话/ })).toBeNull() expect(fireEvent.contextMenu(screen.getByRole('treeitem'))).toBe(true) diff --git a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx index 2731052450..5df4923b4f 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx @@ -1371,18 +1371,15 @@ describe('WorkspaceBrowser', () => { expect(startSession).toHaveBeenCalledWith(wid('alpha')) }) - it('auto-expands the Ungrouped bucket for a loose current session; its header has no menu and its + is inert', () => { - const startSession = vi.fn() + it('auto-expands the Ungrouped bucket for a loose current session; its header has neither menu nor +', () => { mount({ useSessions: hook(sessionState([summary('loose', 1)], { main: sid('loose') })), useWorkspaces: hook(workspaceState([workspace('alpha', [])])), - startSession, }) // The loose session's group is UNGROUPED_KEY: expanded by the effect. expect(screen.getByText('loose')).toBeTruthy() expect(screen.queryByRole('button', { name: '工作区“未分组”的操作' })).toBeNull() - fireEvent.click(screen.getByRole('button', { name: '在“未分组”中新建会话' })) - expect(startSession).not.toHaveBeenCalled() + expect(screen.queryByRole('button', { name: '在“未分组”中新建会话' })).toBeNull() }) it('keeps an already-expanded group when the selection moves within it', () => { diff --git a/packages/client/web/src/boot-page.module.css b/packages/client/web/src/boot-page.module.css index f154c42761..c28097cf8c 100644 --- a/packages/client/web/src/boot-page.module.css +++ b/packages/client/web/src/boot-page.module.css @@ -56,7 +56,8 @@ content: ''; position: absolute; inset: -2px; - border-radius: inherit; + border-radius: 50%; + corner-shape: round; background: conic-gradient( var(--dsw-alias-brand-primary, var(--dsh-boot-brand)) var(--dsh-boot-arc, 72deg), transparent 0 diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 303831978e..253c4536e4 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: ec2bf804bd1a5439 zh: 316e767507e859ef /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: e2cb7b6101f20425 - zh: a056c43886207083 + en: 4a10108fb0d37732 + zh: cc3be0eb8f00901c /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: 3b48a480036bd5df zh: 28cea2036b0dccee diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index bc38634345..30443d6ace 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. The caller Context owns the transaction and live handle; delegation services bind their runtime relationships during setup. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. +The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. Queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles. ### Persistence integration diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 3717ca17d9..e20aa96f37 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。调用方 Context 拥有事务和存活句柄;委派服务在 setup 期间绑定自己的运行时关系。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 +loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。 ### 持久化集成 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 479b59096a..7ec43dd132 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -141,6 +141,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, projections: LoopProjections, lastTurn: number, + private readonly lifetimeSignal: AbortSignal, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) @@ -189,11 +190,15 @@ export class ReactLoopAgent implements Agent { } cancel(cause: AgentCancelCause, options: CancelOptions = {}): void { - if (!options.keepInbox) { - this.inbox.clear() - if (this.phase.kind !== 'idle') this.phase.wakeRequested = false + try { + if (!options.keepInbox) this.inbox.clear() + } finally { + // Queue persistence must not prevent cancellation of admitted work. + if (this.phase.kind !== 'idle') { + if (!options.keepInbox) this.phase.wakeRequested = false + this.phase.abort.abort(cause) + } } - if (this.phase.kind !== 'idle') this.phase.abort.abort(cause) } runMaintenance(job: (signal: AbortSignal) => Promise): Promise { @@ -228,6 +233,7 @@ export class ReactLoopAgent implements Agent { * the inbox insertion so a reentrant cancel cannot reclassify it. */ private wakeDriver(wakeAfterAbort = false): void { + if (this.lifetimeSignal.aborted) return if (this.phase.kind !== 'idle') { // Maintenance and aborted drivers cannot deliver the wake: latch it for // replay at convergence. Live drivers claim queued work themselves; diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 22b3192588..bda53c3b56 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -469,11 +469,8 @@ export class AgentLoop extends Service implements AgentFactory { const id = session.id const loopCtx = this.runtime.ctx - // Deactivation fuses three owners, each with its own reason: the caller's - // cancellation signal, the owner fiber's unload, and factory teardown. - // It is registered BEFORE any resource exists, over mutable slots, so an - // unload arriving while the scope is still minting finds a working - // disposer instead of a leak. + // The caller's signal governs creation. Owner disposal and factory + // shutdown can end the Agent's lifetime both during and after creation. const abort = new AbortController() const onCallerAbort = (): void => { abort.abort(callerSignal?.reason instanceof Error @@ -514,7 +511,12 @@ export class AgentLoop extends Service implements AgentFactory { if (machine === undefined) await machineReady.promise /* v8 ignore next -- setup failure untracks this disposer before resolving without a machine. */ if (machine !== undefined) { - machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + try { + machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + } catch (error: unknown) { + failures.push(error) + } + // A failed queue write must not release resources underneath work. await machine.whenIdle() } } catch (error: unknown) { @@ -572,7 +574,7 @@ export class AgentLoop extends Service implements AgentFactory { const created = machine = new ReactLoopAgent( loopCtx, id, agentOptions, session, projections, - lastTurn, + lastTurn, abort.signal, ) machineReady.resolve() // Adopt the scope on its original fiber so it cannot unload before teardown. @@ -636,6 +638,7 @@ export class AgentLoop extends Service implements AgentFactory { await loopCtx.agents.announce(agent, source, abort.signal) assertLive() ready = true + callerSignal?.removeEventListener('abort', onCallerAbort) return { agent, dispose } } catch (error: unknown) { // Failed initialization must not release queued input into a new turn. diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index c702b64e89..e5e9be01fc 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -319,20 +319,51 @@ describe('Agent.cancel()', () => { }) const agent = handle.agent + const streaming = Promise.withResolvers() + ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streaming.resolve(undefined) }) send(agent, 'active') - await new Promise(resolve => setTimeout(resolve, 30)) - - // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the - // abort-to-idle window must not latch, so `whenIdle()` does not wait on - // a model turn over the session being torn down. + await streaming.promise const disposal = handle.dispose() - setTimeout(() => { send(agent, 'late wake') }, 10) + send(agent, 'late wake') await disposal expect(adapter.requests).toHaveLength(1) expect(userTexts(agent)).toEqual(['active']) }) + it.each(['before scope cleanup', 'during scope cleanup'])('does not start an idle Agent after disposal begins %s', async (window) => { + const adapter = new MockAdapter([textResponse('late reply')]) + const ctx = await harness(adapter) + const cleanupStarted = Promise.withResolvers() + const releaseCleanup = Promise.withResolvers() + let disposal: Promise | undefined + try { + const handle = await ctx.agents.create({ + sessionId: SessionId('idle-disposal-wake'), + agentOptions: { provider: 'mock', model: 'mock' }, + }) + const agent = handle.agent + agent.ctx.effect(() => async () => { + cleanupStarted.resolve(undefined) + await releaseCleanup.promise + }) + disposal = handle.dispose() + if (window === 'during scope cleanup') await cleanupStarted.promise + send(agent, 'late wake') + await agent.whenIdle() + + expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(0) + expect(adapter.requests).toHaveLength(0) + } finally { + releaseCleanup.resolve(undefined) + try { + await disposal + } finally { + await ctx.fiber.dispose() + } + } + }) + it('cancel after waking send closes its synchronously opened turn without a step', async () => { const adapter = new MockAdapter([textResponse('should not run')]) const ctx = await harness(adapter) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 8cc624caae..e3e659f15c 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,7 +6,44 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx) { +export function apply(ctx, config = {}) { + const checkedCancellation = new WeakSet() + ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { + if (checkedCancellation.has(agent) + || (!config.checkRootCancellation && agent.session.header.origin !== 'subagent')) return next() + checkedCancellation.add(agent) + const pending = { + id: randomUUID(), role: 'user', + content: [{ type: 'text', text: 'Cancellation checkpoint probe.' }], + source: { kind: `plugin:${name}` }, + } + agent.inject(pending) + const failure = new Error('fixture queue-clear refusal') + const stopRejecting = ctx.on('internal/dispatch', (_mode, eventName, args) => { + if (eventName !== 'session/event') return + const [session, event] = args + if (session === agent.session && event.type === 'agent/inbox/spliced' + && event.data.outcome === 'canceled' && (event.data.removedCount ?? 0) > 0) throw failure + }) + let rejected = false + try { + try { + agent.cancel({ kind: 'user' }) + } catch (error) { + if (error !== failure) throw error + rejected = true + } + } finally { + stopRejecting() + } + if (!rejected || !signal.aborted) throw new Error('expected queue-clear rejection and activity cancellation') + agent.inbox.remove(pending.id) + for (const message of messages) { + const ordinary = message.source.kind === 'user' + agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary) + } + return next() + }) const ready = new WeakSet() ctx.on('agent/created', async ({ agent }) => { await setImmediate() diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts new file mode 100644 index 0000000000..0ce7898bb2 --- /dev/null +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -0,0 +1,163 @@ +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { afterEach, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as CheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import { MockAdapter, textResponse } from './mock-adapter.ts' + +const fixtures: { ctx: Context; agent?: Agent; root: string }[] = [] +afterEach(async () => { + for (const fixture of fixtures.splice(0)) { + try { + fixture.agent?.cancel({ kind: 'disposed' }, { keepInbox: true }) + await fixture.agent?.whenIdle() + await fixture.ctx.fiber.dispose() + } finally { + await rm(fixture.root, { recursive: true, force: true }) + } + } +}) + +const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } }) + +async function harness() { + const ctx = new Context() + const root = await mkdtemp(join(tmpdir(), 'dsh-input-atomicity-')) + const fixture: { ctx: Context; agent?: Agent; root: string } = { ctx, root } + fixtures.push(fixture) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(NativeToolExecutor) + await ctx.plugin(AgentRegistry) + await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' }) + await ctx.plugin(CheckpointPolicy) + await ctx.plugin(AgentLoop, { agents: [] }) + const adapter = new MockAdapter(Array.from({ length: 5 }, () => textResponse('ok'))) + ctx.llm.registerAdapter(['mock'], adapter) + const handle = await ctx.agents.create({ sessionId: SessionId('diagnostic'), agentOptions: { provider: 'mock', model: 'mock' } }) + fixture.agent = handle.agent + return { ctx, root, adapter, handle, agent: handle.agent } +} + +it('cancellation still aborts the running request when queue clearing fails', async () => { + const { ctx, agent } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() }) + let stopRejecting = () => {} + try { + agent.followup(input('running')) + const signal = await entered.promise + agent.inject(input('steering')) + const queued = input('queued') + agent.followup(queued) + stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn' + && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure') + }) + expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') + expect(signal.aborted).toBe(true) + expect(agent.inbox.nextTurn).toEqual([queued]) + } finally { + stopRejecting() + hold() + agent.cancel({ kind: 'disposed' }, { keepInbox: true }) + release.resolve(undefined) + await agent.whenIdle() + } +}) + +it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { + const { ctx, agent, handle } = await harness() + const release = Promise.withResolvers() + const waiting = Promise.withResolvers<'waiting'>() + const disposed = Promise.withResolvers<'disposed'>() + let scopeDisposed = false + agent.ctx.effect(() => () => { scopeDisposed = true; disposed.resolve('disposed') }) + const work = agent.runMaintenance(async () => { + await release.promise + agent.session.append('request/context', { provider: 'mock', model: 'mock' }) + }) + agent.inject(input('pending')) + const stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) { + throw new Error('queue clear failed') + } + }) + const whenIdle = agent.whenIdle.bind(agent) + const spy = vi.spyOn(agent, 'whenIdle').mockImplementation(() => { waiting.resolve('waiting'); return whenIdle() }) + const closing = handle.dispose().then(() => undefined, (error: unknown) => error) + try { + expect(await Promise.race([waiting.promise, disposed.promise])).toBe('waiting') + expect(scopeDisposed).toBe(false) + expect(ctx.sessions.get(agent.id)).toBe(agent.session) + release.resolve(undefined) + await work + expect(await closing).toEqual(new Error('queue clear failed')) + expect(scopeDisposed).toBe(true) + expect(agent.session.snapshotEvents().at(-1)?.type).toBe('request/context') + } finally { + stopRejecting() + spy.mockRestore() + release.resolve(undefined) + await work + await closing + } +}) + +it('reports a quiescence failure while releasing the Agent and Session', async () => { + const { ctx, agent, handle } = await harness() + const failure = new Error('injected quiescence failure') + const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure) + try { + await expect(handle.dispose()).rejects.toThrow('injected quiescence failure') + expect(ctx.agents.get(agent.id)).toBeUndefined() + expect(ctx.sessions.get(agent.id)).toBeUndefined() + } finally { + idle.mockRestore() + } +}) + +it('keeps creation resources alive until an interrupted creation listener finishes', async () => { + const { ctx } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const signal = new AbortController() + const id = SessionId('interrupted-announcement') + const stop = ctx.on('agent/created', async ({ agent }) => { + if (agent.id !== id) return + entered.resolve(agent) + await release.promise + }) + const creation = ctx.agents.create({ sessionId: id, agentOptions: { provider: 'mock', model: 'mock' }, signal: signal.signal }) + .then(handle => handle.dispose(), (error: unknown) => error) + try { + const agent = await entered.promise + signal.abort(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBe(agent.session) + release.resolve(undefined) + expect(await creation).toEqual(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBeUndefined() + } finally { + release.resolve(undefined) + await creation + stop() + } +}) diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index 8ed1c4d138..f4ef29eea3 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -79,7 +79,8 @@ describe('loop-owned request freezing', () => { const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition) const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition) const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { agent.cancel({ kind: 'disposed' }) await agent.whenIdle() @@ -129,7 +130,8 @@ describe('loop-owned request freezing', () => { expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1) expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1) const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { resumed.cancel({ kind: 'disposed' }) await resumed.whenIdle() diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts index d6a6f50730..4b01c61f80 100644 --- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts @@ -446,7 +446,9 @@ describe('agent scope lifecycle', () => { }) it('uses signal only for creation: aborts pending setup but not a returned live handle', async () => { - const ctx = await harness() + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + onTestFinished(() => ctx.fiber.dispose()) const pendingController = new AbortController() const setupStarted = Promise.withResolvers() const pending = ctx.agents.create({ @@ -474,6 +476,9 @@ describe('agent scope lifecycle', () => { await Promise.resolve() expect(ctx.agents.get(live.agent.id)).toBe(live.agent) expect(live.agent.status).toBe('idle') + live.agent.followup(createUserMessage({ content: text('continue'), source: { kind: 'user' } })) + await live.agent.whenIdle() + expect(adapter.requests).toHaveLength(1) await live.dispose() }) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 358d56ae02..46e9eb2a5a 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -24,8 +24,8 @@ en: 85b0ff72a187110f zh: 3f61c1568d27b8bc /deepseek-ai-dsh-agent/use-this-package/drive-an-agent-s-conversation: - en: 71e258897e2e7d73 - zh: abf0991012faa17e + en: 8dcb90a344e7ef2c + zh: d48f07379f4674d6 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: en: 2594a1e02adea801 zh: cae8860369728efb diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index c84ac3d237..c7ff87b6d0 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -55,7 +55,7 @@ For scoped switch notices, call `installModelSelection(agentCtx)` from `dsh-agen ### Drive an agent's conversation -The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. +The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. A queue-write failure during cancellation still aborts active work and propagates to the caller. ```text handle.agent.followup({ diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index a2fae55b56..98cda69819 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -55,7 +55,7 @@ await handle.dispose() // stops the loop, unregisters, removes the session, un ### 驱动 agent 的对话 -句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。 +句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。 ```text handle.agent.followup({ diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 2b1698e39c..7012dfdf50 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -206,6 +206,7 @@ declare module './types.ts' { * 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. */ diff --git a/packages/core/session/README.i18n.yaml b/packages/core/session/README.i18n.yaml index 376a117359..0d793887f4 100644 --- a/packages/core/session/README.i18n.yaml +++ b/packages/core/session/README.i18n.yaml @@ -30,8 +30,8 @@ en: 002b8240caa0c57c zh: e0954dd62913a944 /deepseek-ai-dsh-session/use-this-package/fork-a-session: - en: 1c40d17a786059d3 - zh: 81320ce118977c65 + en: 4fcc9eb5c0278b51 + zh: 2a26e81ebffbd9a6 /deepseek-ai-dsh-session/use-this-package/flush-durable-state: en: 70a7673145c851ad zh: 0dd1667d9518993d diff --git a/packages/core/session/README.md b/packages/core/session/README.md index 0f368e9ead..3b55b1fcce 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -83,6 +83,8 @@ The [experimental persistence catalog](../../../docs/experimental-persistence-ca The logical `SessionHeader.isSeeded` field reports whether fork history exists without exposing a positional integer. `Session.inheritedEventCount` retains the exact checked `SessionLogOffset`; `ownEvents()` returns events at and after that cut, and `isOwnSeq(seq)` accepts only an existing child-owned position. A low-level seeded constructor must supply an explicit `seed` and `inheritedEventCount` because the constructor seed can contain child-owned setup events after the inherited prefix. +`session.append(type, data, ...opts)` appends one event and returns that event. `session.append(inputs)` accepts a readonly array of positional `[type, data, ...opts]` tuples (`SessionEventInput`) and returns the committed events in input order; an empty array appends nothing. Array admission validates every candidate and synchronous dispatch before changing the log or message surface, so observers read the complete committed group. Persistence listeners retain their own durability rules; array admission alone does not guarantee crash-atomic storage. + ### Flush durable state `ctx.sessions.flush(session)` dispatches the awaited durability checkpoint: every persistence listener flushes and the call settles after all of them. A producer that needs an immediate durability barrier awaits it instead of assuming the write-behind drained. diff --git a/packages/core/session/README.zh.md b/packages/core/session/README.zh.md index 9b4a192d81..9ca25d8a11 100644 --- a/packages/core/session/README.zh.md +++ b/packages/core/session/README.zh.md @@ -83,6 +83,8 @@ session.deriveMessages() // the derived model history 逻辑 `SessionHeader.isSeeded` 字段报告是否存在 fork 历史,而不公开位置整数。`Session.inheritedEventCount` 保留经过校验的精确 `SessionLogOffset`;`ownEvents()` 返回从该切点开始的事件,`isOwnSeq(seq)` 只接受已存在且由子会话拥有的位置。底层带 seed 构造必须显式提供 `seed` 与 `inheritedEventCount`,因为构造 seed 可以在继承前缀之后包含子会话自有的设置事件。 +`session.append(type, data, ...opts)` 追加一个事件并返回该事件。`session.append(inputs)` 接受位置参数元组 `[type, data, ...opts]`(`SessionEventInput`)的只读数组,并按输入顺序返回已提交事件;空数组不追加任何内容。数组准入会在改变日志或surface前验证所有候选和同步分发,因此观察者读取完整的已提交组。持久化监听器保留各自的持久性规则;仅数组准入不保证进程崩溃时整组存储的原子性。 + ### 刷新持久状态 `ctx.sessions.flush(session)` 分发需等待完成的持久性检查点:每个持久化监听器都会刷新,调用在所有监听器结算后完成。需要立即持久性屏障的生产方应等待它,而不是假定延后写入已经排空。 diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index e9baee1b82..ea6c337f55 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -15,7 +15,7 @@ import type { Scoped } from '@deepseek-ai/dsh-scope' import type { Message } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from './types.ts' import type { TypertLookup } from '@deepseek-ai/dsh-typert-protocol' -import type { CreateSessionOptions, EpochHeader, PluginRecord, PluginRecordMap, PluginRecordType, PrepareSessionOptions, RequestContext, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SessionId, SessionSeedEventState, SurfaceIntent, SurfaceEventType } from './types.ts' +import type { CreateSessionOptions, EpochHeader, PluginRecord, PluginRecordMap, PluginRecordType, PrepareSessionOptions, RequestContext, SessionEvent, SessionEventInput, SessionEventMap, SessionEventType, SessionHeader, SessionId, SessionSeedEventState, SurfaceIntent, SurfaceEventType } from './types.ts' import { SurfaceManager, validateSessionEventData, validateSurfaceMetadata } from './surface.ts' import type { SessionSurface, SessionMessageProjection } from './surface.ts' import { foldRequestHeader } from './request-header.ts' @@ -67,6 +67,9 @@ declare module '@deepseek-ai/cordis' { * Post-commit, fire-and-forget append feed. The listener snapshot resolves * before the log push, but callbacks run after it; observer failures are * logged and contained without making the committed append fail. + * Array append commits every member before publishing them in order; + * `session.seq` and `session.surface` already include the complete batch. + * `session.currentBatchPublication` identifies the member being delivered. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners * receive only events from sessions entered through that agent's context. * @param session - the session whose log grew. @@ -514,6 +517,33 @@ export function pluginRecordOf(event: SessionEvent): PluginRecord | undefined { return { type, seq: event.seq, time: event.time, data: event.data } } +/** Copy live append inputs before sequence assignment. */ +function snapshotAppend( + type: SessionEventType, + data: SessionEventMap[SessionEventType] | undefined, + opts: SurfaceIntent | undefined, + subject: string, +) { + const surfaceOp = opts?.surfaceOp + const sourceEventSeqs = opts?.sourceEventSeqs + const dataSnapshot = snapshotJsonValue(data) + if (dataSnapshot === undefined) throw new Error(`${subject} carries non-JSON-serializable data`) + const surface = snapshotJsonValue({ + ...sourceEventSeqs === undefined ? {} : { sourceEventSeqs }, + ...surfaceOp === undefined ? {} : { surfaceOp }, + }) + if (surface === undefined) throw new Error(`${subject} carries non-JSON-serializable surface metadata`) + return { type, data: dataSnapshot, surface } +} + +/** Construct and validate one live event from detached inputs. */ +function createAppendEvent(snapshot: ReturnType, seq: SessionSeq): SessionEvent { + const { type, data, surface } = snapshot + const event = deepFreeze({ type, seq, time: Date.now(), data, ...surface } as SessionEvent) + validateSessionEventData(event, `session event "${type}" at seq ${seq}`) + return event +} + /** * An event-sourced session: an append-only log of {@link SessionEvent}s. * @@ -524,6 +554,7 @@ export function pluginRecordOf(event: SessionEvent): PluginRecord | undefined { */ export class Session { private log: SessionEvent[] = [] + private batchPublication: SessionEvent | undefined /** Single incremental owner of surface acceptance and projection state. */ private readonly surfaceManager: SurfaceManager @@ -761,6 +792,22 @@ export class Session { return SessionLogOffset(this.log.length) } + /** Current event while synchronously notifying a batch's observers. */ + get currentBatchPublication(): SessionEvent | undefined { + return this.batchPublication + } + + /** + * Append consecutive events together after validating every candidate and dispatch. + * Observers read the complete committed log and final message surface. + * Listener registration changes during publication take effect on the next append. + * Persistence listeners retain their own durability rules. + * @param inputs - event payloads and surface intents in commit order. An empty array records no events. + * @returns immutable committed events in the same order. + * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails. + */ + append(inputs: readonly SessionEventInput[]): readonly SessionEvent[] + /** * Append one typed event to the log and synchronously notify observers via * the store-owned, module-private publication hooks. The hot path never blocks @@ -807,35 +854,68 @@ export class Session { type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : [] - ): SessionEvent { + ): SessionEvent + append( + type: SessionEventType | readonly SessionEventInput[], + data?: SessionEventMap[SessionEventType], + ...opts: [opts?: SurfaceIntent] + ): SessionEvent | readonly SessionEvent[] { + if (typeof type !== 'string') return this.#appendEvents(type) this.publicationEntry() - const surfaceOpts: SurfaceIntent | undefined = opts[0] - const surfaceMetadata = { - ...surfaceOpts?.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs }, - ...surfaceOpts?.surfaceOp === undefined ? {} : { surfaceOp: surfaceOpts.surfaceOp }, - } - const dataSnapshot = snapshotJsonValue(data) - if (dataSnapshot === undefined) { - throw new Error(`session event "${type}" carries non-JSON-serializable data`) - } - const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata) - if (surfaceMetadataSnapshot === undefined) { - throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`) - } + const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`) // Payload getters can detach the Session while the snapshots are read. const entry = this.publicationEntry() - const event = deepFreeze({ - type, - seq: SessionSeq(this.log.length), - time: Date.now(), - data: dataSnapshot, - ...(surfaceMetadataSnapshot as { surfaceOp?: unknown; sourceEventSeqs?: unknown }), - } as unknown as SessionEvent) - validateSessionEventData(event, `session event "${type}" at seq ${event.seq}`) - this.commit(event as SessionEvent, entry) + const event = createAppendEvent(snapshot, SessionSeq(this.log.length)) + this.commit(event, entry) return event } + /** + * Validate and publish consecutive events together. Observers see the complete log. + * @param inputs - event payloads and surface intents in commit order. + * @returns immutable committed events in the same order. + * @throws before changing the log if any candidate or synchronous dispatch validation fails. + */ + #appendEvents(inputs: readonly SessionEventInput[]): readonly SessionEvent[] { + this.publicationEntry() + if (inputs.length === 0) return [] + const snapshots = Array.from({ length: inputs.length }, (_, index) => { + const input = inputs.at(index) + if (input === undefined) throw new Error(`session batch has an empty member at index ${index}`) + const [type, data, surfaceOpts] = input + return snapshotAppend(type, data, surfaceOpts, `session batch member ${index} ("${type}")`) + }) + // Payload getters may append to or detach the Session. + const entry = this.publicationEntry() + const startSeq = this.log.length + const events = snapshots.map((snapshot, index) => createAppendEvent(snapshot, SessionSeq(startSeq + index))) + const acceptSurface = this.surfaceManager.prepareBatch(events) + if (entry !== undefined) entry.appending = true + try { + const publications = entry === undefined ? [] : events.map((event) => { + const args: unknown[] = [this, event] + const callbacks = collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...args]) + return { event, args, callbacks } + }) + for (const event of events) this.log.push(event) + this.eventsSnapshot = undefined + acceptSurface() + if (entry !== undefined) { + for (const { event, args, callbacks } of publications) { + this.batchPublication = event + invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, args, callbacks) + } + } + } finally { + this.batchPublication = undefined + if (entry !== undefined) { + entry.appending = false + if (entry.detachRequested) entry.detach() + } + } + return events + } + static { commitPluginRecord = (session, type, data) => session.#appendRecord(type, data) } diff --git a/packages/core/session/src/surface.ts b/packages/core/session/src/surface.ts index 0bb84c030e..7a13bc1d7c 100644 --- a/packages/core/session/src/surface.ts +++ b/packages/core/session/src/surface.ts @@ -367,14 +367,13 @@ function assertSourceEventReferences( /** Resolve tool additions against their immutable historical request header. */ function assertDeveloperHeader( event: SessionEvent, - events: readonly SessionEvent[], - baseSeq: SessionLogOffset, + read: (seq: number) => SessionEvent | undefined, ): void { if (event.type !== 'developer/message') return validateSessionEventData(event, `developer/message at seq ${event.seq}`) if (event.data.headerSeq === undefined) return const headerSeq = event.data.headerSeq - const headerEvent = events[headerSeq - baseSeq] + const headerEvent = read(headerSeq) if (headerSeq >= event.seq || headerEvent?.type !== 'request/header') { throw new Error('developer/message headerSeq must reference an earlier request/header') } @@ -456,15 +455,14 @@ function isDeepEqualJson(a: unknown, b: unknown): boolean { function assertToolResultRewrite( event: SessionEvent, shadowedSeqs: readonly SessionSeq[], - events: readonly SessionEvent[], - baseSeq: SessionLogOffset, + read: (seq: number) => SessionEvent | undefined, ): void { if (event.type !== 'tool/result') return if (shadowedSeqs.length !== 1) { throw new Error('tool/result surface replacement must rewrite exactly one current node') } for (const originalSeq of shadowedSeqs) { - const original = events[originalSeq - baseSeq] + const original = read(originalSeq) if (original?.type !== 'tool/result') { throw new Error('tool/result surface replacement must target a current tool/result') } @@ -495,11 +493,10 @@ function assertSystemHeadRewrite( state: SurfaceFoldState, startIdx: number, shadowedSeqs: readonly SessionSeq[], - events: readonly SessionEvent[], - baseSeq: SessionLogOffset, + read: (seq: number) => SessionEvent | undefined, ): void { if (startIdx !== 0) return - const head = events[state.nodes[0] as number - baseSeq] + const head = read(state.nodes[0] as number) if (head?.type !== 'system/message') return if (event.type !== 'system/message' || shadowedSeqs.length !== 1) { throw new Error('surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node') @@ -514,16 +511,25 @@ function planSurfaceEvent( events: readonly SessionEvent[], baseSeq: SessionLogOffset, projections: readonly SessionMessageProjection[], + candidates?: readonly SessionEvent[], ): SurfacePlan | undefined { if (event.seq !== expectedSeq) { throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`) } const surfaceOp = validateSurfaceMetadata(event) - assertDeveloperHeader(event, events, baseSeq) + const read = (seq: number): SessionEvent | undefined => { + const index = seq - baseSeq + return index < events.length ? events[index] : candidates?.[index - events.length] + } + assertDeveloperHeader(event, read) const projection = projections.find(item => item.type === event.type) if (projection !== undefined) { + let projectionEvents: readonly SessionEvent[] | undefined return { kind: 'project', projection, messages: projection.project(event, { - nodes: state.nodes, events, baseSeq, messages: state.projectedMessages, + nodes: state.nodes, + get events() { return candidates === undefined ? events : (projectionEvents ??= [...events, ...candidates]) }, + baseSeq, + messages: state.projectedMessages, }) } } if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) { @@ -535,8 +541,8 @@ function planSurfaceEvent( } const range = replacementRange(state, surfaceOp) assertSourceEventReferences(event, range.shadowedSeqs) - assertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq) - assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, events, baseSeq) + assertToolResultRewrite(event, range.shadowedSeqs, read) + assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read) return { kind: 'replace', seq: event.seq, @@ -645,6 +651,46 @@ export class SurfaceManager implements SessionSurface { } } + /** + * Validate consecutive candidates against an isolated surface fold. + * @param events - candidates immediately following the committed log. + * @returns a callback adopting the validated fold after all candidates enter the log. + */ + prepareBatch(events: readonly SessionEvent[]): () => void { + this._assertProjections() + if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta() + const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1) + if (events.every(event => (event.surfaceOp === undefined || event.surfaceOp === 'append') + && !this.projections.some(projection => projection.type === event.type))) { + const plans = events.map((event, index) => planSurfaceEvent( + this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events, + )) + return () => { + for (const plan of plans) applySurfacePlan(this._state, plan) + this._lastProcessedSeq = lastProcessedSeq + this._pendingPlan = undefined + } + } + const state: SurfaceFoldState = { + ...this._state, + nodes: [...this._state.nodes], + projectedMessages: new Map(this._state.projectedMessages), + projections: new Set(this._state.projections), + } + const plans = events.map((event, index) => { + const plan = planSurfaceEvent( + state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events, + ) + applySurfacePlan(state, plan) + return plan + }) + return () => { + for (const plan of plans) applySurfacePlan(this._state, plan) + this._lastProcessedSeq = lastProcessedSeq + this._pendingPlan = undefined + } + } + /** Monotonic count of folded positional replacements. */ get replaceGeneration(): number { this._assertProjections() diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts index 7787dd9bd0..0cf13c86a0 100644 --- a/packages/core/session/src/types.ts +++ b/packages/core/session/src/types.ts @@ -485,6 +485,11 @@ export type SurfaceIntent = { sourceEventSeqs?: SessionSeq[] }) +/** One positional event call proposed for append, without assigned sequence or time. */ +export type SessionEventInput = { + [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []] +}[SessionEventType] + /** * One immutable entry in the session log. * diff --git a/packages/core/session/tests/append.spec.ts b/packages/core/session/tests/append.spec.ts new file mode 100644 index 0000000000..ecc5a514c4 --- /dev/null +++ b/packages/core/session/tests/append.spec.ts @@ -0,0 +1,213 @@ +import { describe, expect, it, onTestFinished } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { Session, SessionId, SessionSeq, type SessionEventInput } from '@deepseek-ai/dsh-session' + +function message(text: string) { + return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }) +} + +describe('multiple Session appends', () => { + it('rejects sparse arrays before changing the log or surface', () => { + const session = Session.create(SessionId('sparse-append')) + const inputs = new Array(3) + inputs[0] = ['turn/start', { turn: 1 }] + inputs[2] = ['user/message', message('last'), { surfaceOp: 'append' }] + expect(() => session.append(inputs)).toThrow(/empty member at index 1/) + expect(session.seq).toBe(0) + expect(session.surface.nodes).toEqual([]) + }) + + it('reads only surface metadata from event options', () => { + const session = Session.create(SessionId('options-append')) + const old = session.append('user/message', message('old'), { surfaceOp: 'append' }) + const next = message('new') + const events = session.append([['user/message', next, old]]) + expect(events[0]?.data).toEqual(next) + expect(session.deriveMessages()).toEqual([old.data, next]) + }) + + it('leaves the log unchanged for empty input and accepts a single array member', () => { + const session = Session.create(SessionId('empty-append')) + expect(session.append([])).toEqual([]) + expect(session.seq).toBe(0) + const events = session.append([['turn/start', { turn: 1 }]]) + expect(events).toHaveLength(1) + expect(events[0]).toMatchObject({ type: 'turn/start', seq: 0, data: { turn: 1 } }) + }) + + it('accepts both call forms through an append wrapper', () => { + const session = Session.create(SessionId('wrapped-append')) + const append = new Proxy(session.append.bind(session), { + apply: (target, receiver, args): unknown => Reflect.apply(target, receiver, args), + }) + session.append = append + expect(session.append('turn/start', { turn: 1 }).seq).toBe(0) + expect(session.append([['step/start', { turn: 1, step: 1 }]])).toHaveLength(1) + }) + + it('publishes each member after the complete log and surface are committed', async () => { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId('observed-append')) + const observed: number[] = [] + ctx.on('session/event', (current, event) => { + if (current !== session) return + expect(current.currentBatchPublication).toBe(event) + expect(current.seq).toBe(2) + expect(current.surface.nodes).toEqual([1]) + expect(current.deriveMessages()).toEqual([messageValue]) + observed.push(event.seq) + }) + const messageValue = message('visible') + session.append([ + ['turn/start', { turn: 1 }], + ['user/message', messageValue, { surfaceOp: 'append' }], + ]) + expect(observed).toEqual([0, 1]) + expect(session.currentBatchPublication).toBeUndefined() + }) + + it('replaces an earlier member in the same append', () => { + const session = Session.create(SessionId('replace-append')) + const nodes = session.surface.nodes + const replacement = message('replacement') + session.append([ + ['user/message', message('original'), { surfaceOp: 'append' }], + ['user/message', replacement, { surfaceOp: { op: 'replace', startSeq: SessionSeq(0), endSeq: SessionSeq(0) }, sourceEventSeqs: [SessionSeq(0)] }], + ]) + expect(nodes).toEqual([1]) + expect(session.deriveMessages()).toEqual([replacement]) + }) + + it('rejects non-JSON data before publishing any member', () => { + const session = Session.create(SessionId('non-json-append')) + expect(() => session.append([ + ['turn/start', { turn: 1 }], + ['turn/start', { turn: Number.NaN }], + ])).toThrow('session batch member 1 ("turn/start") carries non-JSON-serializable data') + expect(session.seq).toBe(0) + }) + + it('assigns consecutive sequences after a candidate getter appends an event', () => { + const session = Session.create(SessionId('getter-append')) + const events = session.append([ + ['turn/start', { + get turn() { + session.append('request/context', { provider: 'mock', model: 'mock' }) + return 1 + }, + }], + ['step/start', { turn: 1, step: 1 }], + ]) + expect(events.map(event => event.seq)).toEqual([1, 2]) + expect(session.snapshotEvents().map(event => event.type)).toEqual(['request/context', 'turn/start', 'step/start']) + }) + + it('contains a reentrant append while publishing the remaining members', async () => { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId('reentrant-batch')) + const observed: number[] = [] + const warnings: string[] = [] + ctx.logger.warn = (warning: unknown) => { warnings.push(String(warning)) } + ctx.on('session/event', (current, event) => { + if (current === session && event.seq === 0) { + session.append('request/context', { provider: 'mock', model: 'mock' }) + } + }) + ctx.on('session/event', (current, event) => { + if (current === session) observed.push(event.seq) + }) + session.append([ + ['turn/start', { turn: 1 }], + ['step/start', { turn: 1, step: 1 }], + ]) + expect(session.seq).toBe(2) + expect(observed).toEqual([0, 1]) + expect(warnings).toEqual([expect.stringContaining('session append cannot reenter')]) + }) + + it('detaches only after every member has been observed', async () => { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + const session = ctx.sessions.prepare(SessionId('detached-append')) + const detach = ctx.sessions.enter(session) + ctx.sessions.announce(session) + const observed: number[] = [] + ctx.on('session/event', (current, event) => { + expect(ctx.sessions.get(current.id)).toBe(current) + detach() + observed.push(event.seq) + }) + session.append([ + ['turn/start', { turn: 1 }], + ['step/start', { turn: 1, step: 1 }], + ]) + expect(observed).toEqual([0, 1]) + expect(ctx.sessions.get(session.id)).toBeUndefined() + }) + + it('folds preceding single appends before admitting an array', () => { + const session = Session.create(SessionId('mixed-append')) + session.append('user/message', message('before'), { surfaceOp: 'append' }) + expect(session.surface.contentGeneration).toBe(0) + session.append([['user/message', message('after'), { surfaceOp: 'append' }]]) + expect(session.surface.nodes).toEqual([0, 1]) + expect(session.surface.replaceGeneration).toBe(0) + }) + + it('publishes a complete group with its final surface', () => { + const session = Session.create(SessionId('batch')) + const events = session.append([ + ['turn/start', { turn: 1 }], + ['user/message', message('hello'), { surfaceOp: 'append' }], + ]) + expect(events.map(event => event.seq)).toEqual([0, 1]) + expect(session.surface.nodes).toEqual([1]) + expect(session.deriveMessages()).toEqual([events[1]?.data]) + }) + + it('retains the committed log and surface when a later candidate is invalid', () => { + const session = Session.create(SessionId('rejected-batch')) + session.append('user/message', message('before'), { surfaceOp: 'append' }) + const before = session.deriveMessages() + expect(() => session.append([ + ['user/message', message('candidate'), { surfaceOp: 'append' }], + ['user/message', message('invalid'), { surfaceOp: { op: 'replace', startSeq: SessionSeq(40), endSeq: SessionSeq(41) } }], + ])).toThrow() + expect(session.seq).toBe(1) + expect(session.deriveMessages()).toEqual(before) + expect(session.surface.nodes).toEqual([0]) + }) + + it('rejects the entire group when dispatch validation vetoes its last event', async () => { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(SessionStore) + const session = ctx.sessions.create(SessionId('veto-batch')) + const observed: number[] = [] + ctx.on('session/event', (current, event) => { + if (current === session) observed.push(event.seq) + }) + const stop = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [current, event] = args as [Session, { seq: number }] + if (current === session && event.seq === 1) throw new Error('veto final event') + }) + expect(() => session.append([ + ['turn/start', { turn: 1 }], + ['user/message', message('candidate'), { surfaceOp: 'append' }], + ])).toThrow('veto final event') + expect(session.seq).toBe(0) + expect(session.surface.nodes).toEqual([]) + expect(observed).toEqual([]) + stop() + session.append('turn/start', { turn: 1 }) + expect(observed).toEqual([0]) + }) + +}) diff --git a/packages/core/session/tests/append.type-test.ts b/packages/core/session/tests/append.type-test.ts new file mode 100644 index 0000000000..297725a048 --- /dev/null +++ b/packages/core/session/tests/append.type-test.ts @@ -0,0 +1,24 @@ +/** Compile-time checks for single and multiple event admission. */ +import { expectTypeOf } from 'vitest' +import type { Session, SessionEvent, SessionEventInput } from '@deepseek-ai/dsh-session' +import type { UserMessage } from '@deepseek-ai/dsh-llm' + +/** + * Check result cardinality and event-specific payload and surface requirements. + * @param session - target Session; this function is typechecked without execution. + * @param message - user input with durable identity. + */ +export function checkAppendTypes(session: Session, message: UserMessage): void { + expectTypeOf(session.append('turn/start', { turn: 1 })).toEqualTypeOf>() + const inputs: readonly SessionEventInput[] = [ + ['turn/start', { turn: 1 }], + ['user/message', message, { surfaceOp: 'append' }], + ] + expectTypeOf(session.append(inputs)).toEqualTypeOf() + // @ts-expect-error -- message-producing members require a surface operation. + session.append([['user/message', message]]) + // @ts-expect-error -- log-only members cannot carry a surface operation. + session.append([['turn/start', { turn: 1 }, { surfaceOp: 'append' }]]) + // @ts-expect-error -- each payload must match its event type. + session.append([['turn/start', message]]) +} diff --git a/packages/core/session/tests/canonical-envelopes.spec.ts b/packages/core/session/tests/canonical-envelopes.spec.ts index 1c52750edb..9f66190dcd 100644 --- a/packages/core/session/tests/canonical-envelopes.spec.ts +++ b/packages/core/session/tests/canonical-envelopes.spec.ts @@ -37,17 +37,21 @@ function toolData(isError: boolean) { } function appendEvent(session: Session, event: SessionEvent) { - const append = session.append.bind(session) as ( - type: SessionEvent['type'], data: unknown, metadata?: unknown, - ) => SessionEvent - return append(event.type, event.data, { + return Reflect.apply(session.append.bind(session), session, [event.type, event.data, { ...event.surfaceOp === undefined ? {} : { surfaceOp: event.surfaceOp }, ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs }, - }) + }]) as SessionEvent } const entryPaths: Record unknown> = { append: (event: SessionEvent) => appendEvent(Session.create(id), event), + batch: (event: SessionEvent) => { + const session = Session.create(id) + return Reflect.apply(session.append.bind(session), session, [[[event.type, event.data, { + ...event.surfaceOp === undefined ? {} : { surfaceOp: event.surfaceOp }, + ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs }, + }]]]) as readonly SessionEvent[] + }, seed: (event: SessionEvent) => Session.create(id, [event]), restore: (event: SessionEvent) => Session.fromRestore(id, [event], { ...header }, SessionLogOffset(0), 'detached'), adopt: adoptSessionEvent, @@ -290,7 +294,7 @@ describe('canonical event-local surface metadata', () => { surfaceOp: { opaque: ['not', 'placement'] }, sourceEventSeqs: { opaque: [null, true] }, } as unknown as SessionEvent for (const [path, accept] of Object.entries(entryPaths)) { - if (path === 'append') continue + if (path === 'append' || path === 'batch') continue expect(() => accept(structuredClone(event))).not.toThrow() } const session = Session.create(id, [event]) diff --git a/packages/core/session/tests/developer-header.spec.ts b/packages/core/session/tests/developer-header.spec.ts index de38469c8e..b1d094a6cf 100644 --- a/packages/core/session/tests/developer-header.spec.ts +++ b/packages/core/session/tests/developer-header.spec.ts @@ -20,6 +20,28 @@ function opened(tools: ToolSchema[] = [first]) { } describe('developer request-header references', () => { + it('resolves a tool addition against an earlier header in the same batch', () => { + const session = Session.create(SessionId('batch-developer-header')) + const message = addition() + session.append([ + ['request/header', { reason: 'initial', header: { config: { provider: 'test', model: 'test' }, tools: [first] } }], + ['developer/message', { turn: 1, step: 1, headerSeq: SessionSeq(0), message }, { surfaceOp: 'append' }], + ]) + expect(session.seq).toBe(2) + expect(session.deriveMessages()).toEqual([message]) + expect(foldSurface(session.snapshotEvents()).nodes).toEqual([1]) + }) + + it.each([1, 2])('rejects a non-earlier batch header reference %s without committing a prefix', (reference) => { + const session = Session.create(SessionId('invalid-batch-developer-header')) + expect(() => session.append([ + ['request/header', { reason: 'initial', header: { config: { provider: 'test', model: 'test' }, tools: [first] } }], + ['developer/message', { turn: 1, step: 1, headerSeq: SessionSeq(reference), message: addition() }, { surfaceOp: 'append' }], + ])).toThrow('earlier request/header') + expect(session.seq).toBe(0) + expect(session.surface.nodes).toEqual([]) + }) + it('keeps an older header binding through compound changes, replacement, restore, and fork', () => { const { session, headerSeq } = opened([first, { name: 'other', description: 'Other', parameters: {} }]) session.append('request/header', { reason: 'change', header: { config: { provider: 'test', model: 'test' }, tools: [second] } }) diff --git a/packages/core/session/tests/message-projections.spec.ts b/packages/core/session/tests/message-projections.spec.ts index 6eccae4f3e..45c346e364 100644 --- a/packages/core/session/tests/message-projections.spec.ts +++ b/packages/core/session/tests/message-projections.spec.ts @@ -59,6 +59,24 @@ describe('plugin-owned message projections', () => { expect(source.data.content).toEqual([{ type: 'text', text: 'original' }]) }) + it.each(['projected', 'reject'])('admits message projections through array append (%s)', (text) => { + const session = Session.create(SessionId('array-projection'), undefined, undefined, undefined, [projection]) + const original = createUserMessage({ content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } }) + const append = () => session.append([ + ['user/message', original, { surfaceOp: 'append' }], + ['test/project', { seq: SessionSeq(0), text }], + ]) + if (text === 'reject') { + expect(append).toThrow('rejected decision') + expect(session.seq).toBe(0) + expect(session.deriveMessages()).toEqual([]) + } else { + append() + expect(session.deriveMessages()[0]?.content).toEqual([{ type: 'text', text }]) + expect(session.surface.contentGeneration).toBe(1) + } + }) + it('registers by fiber and refuses cached or pending decisions after disposal', async () => { const ctx = new Context() contexts.push(ctx) diff --git a/packages/credentials/credentials-local/README.i18n.yaml b/packages/credentials/credentials-local/README.i18n.yaml index b4401964e7..ee9d36bb0e 100644 --- a/packages/credentials/credentials-local/README.i18n.yaml +++ b/packages/credentials/credentials-local/README.i18n.yaml @@ -24,8 +24,8 @@ en: fccad7d354c2af71 zh: 5b95b5890e21f80f /deepseek-ai-dsh-credentials-local/use-this-package/storing-and-removing-keys: - en: 5e3d45470142b9dd - zh: 1f8358f987769d3a + en: 89712d3b085e69ed + zh: 09ad74cb3e329e07 /deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from: en: a55fac148b62e007 zh: fdb3d19ccae676ee diff --git a/packages/credentials/credentials-local/README.md b/packages/credentials/credentials-local/README.md index c3d15999be..ed463fcc7b 100644 --- a/packages/credentials/credentials-local/README.md +++ b/packages/credentials/credentials-local/README.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable, masked? } — never the value await ctx.credentials.unset(ref) // remove ``` -A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). +A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. A stored file value also reports a `masked` preview; environment fallbacks omit this field. The preview splits the provider identifier after the first hyphen or underscore, or uses no identifier when neither exists. It keeps the identifier and the first five/last four key code points only when at least eight key code points remain hidden. Otherwise it masks the whole value, including the identifier. Counts and slicing use `Array.from` Unicode code points; combining sequences are not treated as one grapheme. The identifier is intentionally visible and must not be assumed nonsensitive merely because it precedes a separator. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). ### Where keys come from diff --git a/packages/credentials/credentials-local/README.zh.md b/packages/credentials/credentials-local/README.zh.md index 5249827cde..733cf42629 100644 --- a/packages/credentials/credentials-local/README.zh.md +++ b/packages/credentials/credentials-local/README.zh.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable, masked? } — never the value await ctx.credentials.unset(ref) // remove ``` -你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 +你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。文件中已保存的值还会报告 `masked` 脱敏预览;环境后备值不包含此字段。预览在第一个连字符或下划线之后划分提供商标识;没有分隔符时不划分标识。只有密钥部分至少保留八个隐藏码点时,才显示标识及密钥的前五、后四个码点;否则遮住整串,包括标识。计数和切片使用 `Array.from` 的 Unicode 码点,组合序列不按单个字素处理。标识会有意显示,不能仅因它位于分隔符前就认定其不含机密。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 ### 密钥从哪里来 diff --git a/packages/credentials/credentials-local/src/index.ts b/packages/credentials/credentials-local/src/index.ts index 48ae487c6d..c767adea73 100644 --- a/packages/credentials/credentials-local/src/index.ts +++ b/packages/credentials/credentials-local/src/index.ts @@ -513,6 +513,20 @@ function sameJsonValue(left: unknown, right: unknown): boolean { && sameJsonValue((left as Record)[key], (right as Record)[key])) } +/** + * Keep the provider identifier and five leading/four trailing key code points + * only when at least eight key code points stay hidden; otherwise mask all. + * @param value - stored credential, with an optional identifier ending at the first hyphen or underscore. + * @returns a same-length code-point preview without the full credential. + */ +function maskCredential(value: string): string { + const chars = Array.from(value) + const providerEnd = chars.findIndex(char => char === '-' || char === '_') + 1 + const hidden = chars.length - providerEnd - 5 - 4 + return hidden < 8 ? '•'.repeat(chars.length) + : `${chars.slice(0, providerEnd + 5).join('')}${'•'.repeat(hidden)}${chars.slice(-4).join('')}` +} + /** File-backed credentials provider (`$DSH_HOME/.credentials.yaml`). */ export class LocalCredentialProvider extends CredentialProvider { static Config: z = z.object({ @@ -633,7 +647,7 @@ export class LocalCredentialProvider extends CredentialProvider { override describe(ref: CredentialRef): Promise { const stored = this.values.get(ref) - if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true }) + if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true, masked: maskCredential(stored) }) // Every reference is writable: a set writes the managed file, which // outranks every fallback, and an unset exposes the fallback again. if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true }) diff --git a/packages/credentials/credentials-local/tests/local.spec.ts b/packages/credentials/credentials-local/tests/local.spec.ts index d1436e0731..36b2789528 100644 --- a/packages/credentials/credentials-local/tests/local.spec.ts +++ b/packages/credentials/credentials-local/tests/local.spec.ts @@ -59,6 +59,32 @@ describe('resolveSpec', () => { }) describe('layering and reads', () => { + it.each([ + ['plain', '•'.repeat(5)], + ['abcdefghijklmnop', '•'.repeat(16)], + ['abcdefghijklmnopq', `abcde${'•'.repeat(8)}nopq`], + ['sk-abcdefghijklmn', '•'.repeat(17)], + ['sk-abcdefghijklmnop', '•'.repeat(19)], + ['sk-abcdefghijklmnopq', `sk-abcde${'•'.repeat(8)}nopq`], + ['vendor_abcdefghijklmnopq', `vendor_abcde${'•'.repeat(8)}nopq`], + ['sk-proj-abcdefghijklmnopq', `sk-proj-${'•'.repeat(13)}nopq`], + ['abc-def_abcdefghijklmnopq', `abc-def_a${'•'.repeat(12)}nopq`], + ['abcdefghijklmnop-', '•'.repeat(17)], + ['😀'.repeat(16), '•'.repeat(16)], + ['😀'.repeat(17), `${'😀'.repeat(5)}${'•'.repeat(8)}${'😀'.repeat(4)}`], + [`sk-${'😀'.repeat(17)}`, `sk-${'😀'.repeat(5)}${'•'.repeat(8)}${'😀'.repeat(4)}`], + ['😀_abcdefghijklmno😀😀', `😀_abcde${'•'.repeat(8)}no😀😀`], + ])('describes only the masked preview for %s', async (value, masked) => { + const dir = await tempDir() + const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) + await ctx.credentials.set(KEY, value) + const info = await ctx.credentials.describe(KEY) + expect(info).toEqual({ configured: true, source: 'file', writable: true, masked }) + expect(Array.from(masked)).toHaveLength(Array.from(value).length) + expect(JSON.stringify(info)).not.toContain(value) + expect(await ctx.credentials.resolve(KEY)).toEqual({ value, source: 'file' }) + }) + it('treats an absent file as an empty writable store', async () => { const dir = await tempDir() const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) @@ -73,7 +99,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' }) expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(5) }) }) it('lets the managed file win over a non-empty process environment', async () => { @@ -83,7 +109,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', 'from-env') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(9) }) }) it('treats an empty environment value as absent, falling through to the file', async () => { @@ -93,7 +119,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', '') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(6) }) }) it('fails boot loud when the document exists but cannot be read', async () => { @@ -131,7 +157,7 @@ describe('layer ladder', () => { expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) // A key sitting in the user's .env does not make the stored one // unwritable. - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(6) }) await expect(ctx.credentials.set(KEY, 'rotated')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' }) }) @@ -145,8 +171,10 @@ describe('layer ladder', () => { expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: true }) await ctx.credentials.set(KEY, 'stored') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(6) }) await ctx.credentials.unset(KEY) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-launch', source: 'env' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: true }) }) it('serves the user .env only when nothing is stored', async () => { @@ -230,9 +258,10 @@ describe('layer ladder', () => { { source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } }, ]) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(6) }) await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: '•'.repeat(4) }) }) }) @@ -382,7 +411,7 @@ describe('document writes', () => { const reread = await boot({ path, watch: false }) expect(await reread.credentials.resolve(KEY)).toEqual({ value: multiLine, source: 'file' }) expect(await reread.credentials.resolve(OTHER)).toEqual({ value: mixedQuotes, source: 'file' }) - expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, masked: `line ${'•'.repeat(8)} two` }) }) it('unsets only the owning entry, with its own annotation, and keeps an absent unset silent', async () => { diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 3f2265caf7..2b850ee561 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: fa334e2d4438e0b6 - zh: 009b9252ed046886 + en: 68096f3f256353ed + zh: 673608f5d5e66d66 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 85ed5a68b0..26e324c30b 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable, masked? } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. +Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. Providers may disclose a masked stored-value preview through the optional `masked` field; the full value stays on the Host. ### Storing, updating, and removing records diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index c73f0c68bf..7aa8fc9d9e 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable, masked? } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。 +用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。提供方可通过可选的 `masked` 字段报告已保存值的脱敏预览;完整值留在 Host。 ### 存储、更新与移除记录 diff --git a/packages/credentials/credentials/src/index.ts b/packages/credentials/credentials/src/index.ts index 2e0b56931a..8f6054a327 100644 --- a/packages/credentials/credentials/src/index.ts +++ b/packages/credentials/credentials/src/index.ts @@ -4,7 +4,7 @@ * the actual values and their storage. Consumers resolve a reference once per * operation, so a changed credential reaches the next operation without any * plugin restart, and configuration surfaces describe a reference without - * ever seeing its value. + * ever seeing its full value. * @module @deepseek-ai/dsh-credentials */ @@ -185,9 +185,9 @@ export abstract class CredentialProvider extends Service { /** * 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 diff --git a/packages/credentials/credentials/src/types.ts b/packages/credentials/credentials/src/types.ts index 5c9ae99350..8bd191815a 100644 --- a/packages/credentials/credentials/src/types.ts +++ b/packages/credentials/credentials/src/types.ts @@ -60,9 +60,8 @@ export interface GrantRecord { export type CredentialRecord = ApiKeyRecord | GrantRecord /** - * 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. */ export interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ @@ -71,6 +70,8 @@ export 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 } declare module '@deepseek-ai/cordis' { diff --git a/packages/credentials/deepseek-account-platform/README.i18n.yaml b/packages/credentials/deepseek-account-platform/README.i18n.yaml deleted file mode 100644 index 9e6ffe9905..0000000000 --- a/packages/credentials/deepseek-account-platform/README.i18n.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/credentials/deepseek-account-platform/README.md -/: - en: 9dbb9bc3960a11fe - zh: ed58987926489d3e -/deepseek-ai-dsh-deepseek-account-platform: - en: 7be860d52e1202db - zh: a2612757253d67a6 -/deepseek-ai-dsh-deepseek-account-platform/summary: - en: 28bcca957bf6abf4 - zh: 4a3fc8a59f2925bc -/deepseek-ai-dsh-deepseek-account-platform/table-of-contents: - en: af856ba79fe31b8e - zh: 15b7d1a5d1856de2 -/deepseek-ai-dsh-deepseek-account-platform/use-this-package: - en: 56bee240f50c293a - zh: 6c4c5de6088c9d79 -/deepseek-ai-dsh-deepseek-account-platform/understand-the-implementation: - en: 76d2da2dab100ac3 - zh: 2c9404f27915daab -/deepseek-ai-dsh-deepseek-account-platform/further-exploration: - en: c8b43a641360ec9e - zh: a545f6a0b6a5066b -/deepseek-ai-dsh-deepseek-account-platform/model-experience: - en: ee1df7ca3467ee3f - zh: 84904a5148da3862 -/deepseek-ai-dsh-deepseek-account-platform/model-experience/kv-cache-effect: - en: ca3015e252db0114 - zh: ebca9253cf15e8e9 -/deepseek-ai-dsh-deepseek-account-platform/known-limitations-and-deferred-work: - en: 1b26fcb10e139c27 - zh: 8babfccddabdabc4 -/deepseek-ai-dsh-deepseek-account-platform/known-limitations-and-deferred-work/dev-note: - en: c5d41d3333c20c2b - zh: 41442ff16d92b37a diff --git a/packages/credentials/deepseek-account-platform/README.md b/packages/credentials/deepseek-account-platform/README.md deleted file mode 100644 index 104b597c9a..0000000000 --- a/packages/credentials/deepseek-account-platform/README.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -description: "Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-deepseek-account-platform - -English | [中文](README.zh.md) - -Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The provider derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. - -getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its 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 issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. - -`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The provider owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. - -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. - -## Summary - -Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in. - -Platform requests report `no-response` when fetch rejects before returning a Response, including request timeouts. HTTP errors and response-body failures do not use this code; authorization-attempt expiry retains `expired`. - -Device identity reads validate the existing login device record and expose only its ID, the current account ID, and the shared login OS version string. - -## Table of Contents - -- [Use this package](#use-this-package) -- [Model Experience](#model-experience) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - - -## Use this package - -The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. - -Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. - -getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. - -getUnnotifiedBonuses reads GET /api/v0/users/get_unnotified_bonuses and ackBonusNotified posts POST /api/v0/users/ack_bonus_notified with a JSON body naming the order on the same origin, each sending the five client headers built from the caller's metadata. Both resolve the account identity for the captured grant first, so a signed-out or switched account yields null or false instead of acknowledging another account's bonus, and a read publishes only after the whole query settled under one credential lifetime. The Host forwards the bonus list in Platform order, retains the string fields order_id, expires_at and msg, and maps them to orderId, expiresAt and message. An optional string title is forwarded unchanged; null or absent titles use the client default. An empty, null or absent expires_at becomes an empty expiresAt and means the notice never expires. Order IDs need not be UUIDs; campaign, amount, currency and granted_at are optional, unvalidated metadata forwarded as campaign, amount, currency and grantedAt; malformed payloads, other HTTP failures and other business failures throw, while a credential rejection (HTTP 401 or response code `40003`) invalidates the current grant and yields null or false. - -Balance requests use balanceTimeoutMs (30,000ms by default); timeout returns a failed outcome without clearing the account or manufacturing a zero balance. Configure platformOrigin, allowLoopbackHttp, requestTimeoutMs, balanceTimeoutMs, and attemptTimeoutMs in the plugin row. HTTP is accepted only for explicitly enabled loopback development. The provider registers /oauth/callback on the existing Host webServer before auth_init, validates state, exchanges an S256 PKCE code once, and commits a grant before redirecting to auth_exchange.biz_data.authorized_url. Browser destinations default to the configured platform origin and always require the fixed /dsh/authorize or /dsh/authorized path. The completion URL sets `login_source` to the initiating client (`web` or `desktop`) and preserves other Platform-supplied query parameters. Device identity is a separate random UUID record shared by processes using the same credential store; device_model reports OS and architecture. - -Platform URLs have one configuration owner: `platformOrigin`. Authorization requests, browser validation, completion redirects, usage, and top-up destinations all use that origin. Set it in a private `$DSH_HOME/cordis.patch.yml`; deployment addresses do not belong in source control. HTTPS is required except for loopback HTTP with `allowLoopbackHttp: true`. Model and file token destinations use the separate `inferenceOrigin` configuration. - -`requestHeaders` adds Host-only headers to authorization, profile, balance, and logout requests on `platformOrigin`. Header values are secret configuration; they are excluded from account UI state. Authorization, X-DSH-Auth-Token, Host, Content-Type and connection/framing headers are reserved. Client identity headers override same-named deployment headers. Redirects fail without forwarding headers. Store deployment cookies in private configuration or environment variables; browser cookies are not collected automatically. - -A private patch can read environment variables through Cordis expressions: - -```yaml -- id: deepseek-account - config: - platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN - allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' - requestHeaders: !!js | - process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} -``` - -The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The provider fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. Callback requests use state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt route. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. - -Host diagnostics use `console.error` with the `[deepseek-account]` prefix on standard error and in the Host inspector Console, only for request, response-validation, or sign-in failures. Successful requests, caller cancellation, and normal account state changes are silent; request timeouts remain failures. Failure diagnostics include endpoint paths, HTTP status, numeric response codes, failure stages, invalid field paths, received types and validation codes, and browser URL rejection rules; headers, request and response bodies, authorization URLs, and raw exceptions are excluded. - -`rewriteBrowserOrigin` defaults to `false`, requiring same-origin browser URLs. A private development patch may set it to `true` to map authorization and completion URLs to `platformOrigin`, preserving their fixed paths and query strings. Source URLs must use HTTPS or already match the configured origin; user information, fragments and unexpected paths remain rejected. Shipped profiles retain strict same-origin validation. - -inferenceOrigin defaults to `https://api.deepseek.com`. A private deployment patch may replace it with one exact HTTP(S) origin, including its port, for inference and file authentication through x-dsh-auth-token. Paths, URL credentials, queries and fragments are invalid configuration. Alternate origins require a grant issued by the configured platformOrigin; mock tokens remain excluded. Loopback grants cannot authenticate the official production API. Deployment addresses belong in private patches, not shipped configuration. - -At provider initialization, a valid stored grant whose issuer differs from platformOrigin is deleted locally before consumers read account state. Startup continues signed out without a remote logout request; API keys and device identity remain stored. Storage failures remain explicit, and account HTTP or response-validation failures do not delete a matching grant. - - -## Understand the implementation - -Account presence reads the credential store, and attempt state projects private state directly. Behavior tests verify asynchronous cancellation and commit ordering. - - -## Further Exploration - -The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. - -The attemptTimeoutMs limit includes initialization, browser waiting, and exchange. Initialization does not extend its absolute deadline; the server TTL may only shorten the remaining time. Credential persistence admitted before expiry completes without cancellation. - - -## Model Experience - -None, as account credentials affect HTTP authentication and never enter model prompts, Session logs, or tool results. - -#### KV Cache effect - -No model request prefix changes. - -## Known Limitations and Deferred Work - - - -- Browser sign-in requires the Host webServer. Only local access and SSH local forwarding through HTTP localhost, 127.0.0.1, or [::1] with an explicit port are supported; non-loopback reverse proxies are unsupported. Account tokens have no expiry or refresh flow; explicit DSH sign-out removes the local grant before calling POST /auth-api/v0/users/logout in the background. Remote failures never restore local login. The captured old token receives at most five additional attempts with exponential delays of 1, 2, 4, 8, and 16 seconds by default; logoutMaxRetries (0–5) and logoutRetryDelayMs configure that policy. Each request uses requestTimeoutMs. Provider shutdown aborts requests and waits, and pending revocations are not persisted. Local credential deletion failures remain visible to the caller. Authorization-attempt deadlines still apply before a token is issued. Cancellation or timeout after initialization sends one background POST /auth-api/v0/dsh/auth_cancel with the authorize_id from auth_init.biz_data and the original code_verifier, without account authorization. Local cancellation never waits for this request or reverses on failure; requestTimeoutMs bounds it, and provider shutdown aborts it. TODO(product-error-ui): Product must define localized copy and UI behavior for the supplied biz_code values. Until then, business failures use the existing generic retry message; other codes and HTTP errors use the same fallback. Development grants never authenticate production requests. - - -### Dev Note - -The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. - -The first profile read after sign-in uses the sanitized user returned by auth_exchange. A null or malformed user falls back to current; subsequent refreshes and Host restarts also query current. Failed current requests retain the latest successful profile for the same credential in Host memory; credential changes and disposal clear it. A ready current response whose stable account ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, so identity consumers re-read getPlatformSession; refreshes that repeat the same ID stay silent. Exchange registers the submitted device information. - -accountRequestHeaders overlays requestHeaders for current, balance and embedded Platform page/API requests. Cookie pairs merge by name so routing overrides retain other deployment cookies. Authorization initialization, exchange, cancellation and logout keep requestHeaders. Both maps remain private to Host and Electron main; the session's userId stays Host-only too, and renderer bootstrap receives only origin and token. - -The account provider’s `embeddedPageDist` configuration adds a `dist` query parameter to embedded Usage and Top-up URLs. Its default is empty; private frontend branch selectors belong in the local profile patch. It does not change API URLs or credential delivery. - -Platform wallet balances accept decimal strings with optional scientific notation (including `0E-16`); the provider preserves the original string for consumers. diff --git a/packages/credentials/deepseek-account-platform/README.zh.md b/packages/credentials/deepseek-account-platform/README.zh.md deleted file mode 100644 index 7e9b181868..0000000000 --- a/packages/credentials/deepseek-account-platform/README.zh.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -description: "通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-deepseek-account-platform - -[English](README.md) | 中文 - -每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。提供者据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 - -getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 - -`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 - -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 - -## 概述 - -通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。 - -当 fetch 在返回 Response 前拒绝(包括单次请求超时)时,Platform 请求报告 `no-response`。HTTP 错误和响应体失败不使用此代码;授权尝试到期仍使用 `expired`。 - -设备身份读取会校验已有登录设备记录,仅提供设备 ID、当前账户 ID 和与登录共用的操作系统版本字符串。 - -## 目录 - -- [使用此包](#use-this-package) -- [模型体验](#model-experience) -- [已知限制与后续工作](#known-limitations-and-deferred-work) - - -## 使用此包 - -本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 - -账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 - -getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 - -getUnnotifiedBonuses 读取同一来源上的 GET /api/v0/users/get_unnotified_bonuses,ackBonusNotified 向 POST /api/v0/users/ack_bonus_notified 发送仅含订单号的 JSON 正文,两者都按调用方元数据组装这五个客户端请求头。二者都先为捕获到的授权解析账号身份,因此退登或切号时返回 null 或 false,而不会确认另一个账号的赠金;一次读取只有在同一凭证生命周期内全部结算后才发布。Host 按 Platform 返回顺序转发赠金列表,保留字符串字段 order_id、expires_at 和 msg,并映射为 orderId、expiresAt 和 message。可选的字符串 title 原样转发;null 或缺省表示使用客户端默认标题。expires_at 为空字符串、null 或缺省时,统一转为空字符串 expiresAt,表示通知永不过期。订单号不要求 UUID 格式;campaign、amount、currency 和 granted_at 均为可选元数据,不做校验,分别原样转发为 campaign、amount、currency 和 grantedAt;格式错误、其他 HTTP 失败和其他业务失败都会抛出,而凭据被拒绝(HTTP 401 或响应码 `40003`)会使当前授权失效并返回 null 或 false。 - -余额请求使用 balanceTimeoutMs(默认 30,000ms);超时返回失败结果,不清除账号,也不制造零余额。在插件行配置 platformOrigin、allowLoopbackHttp、requestTimeoutMs、balanceTimeoutMs 和 attemptTimeoutMs。HTTP 仅用于显式启用的本机开发。提供者先在现有 Host webServer 注册 /oauth/callback,再调用 auth_init;校验 state、使用 S256 PKCE 授权码兑换一次,并在跳转 auth_exchange.biz_data.authorized_url 前提交授权记录。浏览器地址默认要求匹配配置的平台来源,并始终要求固定的 /dsh/authorize 或 /dsh/authorized 路径。完成页地址将 `login_source` 设为发起登录的客户端类型(`web` 或 `desktop`),并保留平台返回的其他查询参数。设备标识是独立的随机 UUID 记录,由使用同一凭证存储的进程共享;device_model 报告操作系统和架构。 - -开放平台 URL 统一由 `platformOrigin` 配置管理。授权请求、浏览器地址校验、完成跳转、用量和充值入口都使用该来源。将配置放在私有的 `$DSH_HOME/cordis.patch.yml`,部署地址不进入源码仓库。默认要求 HTTPS;只有本机 HTTP 可通过 `allowLoopbackHttp: true` 显式启用。模型及文件 token 的目标由独立的 `inferenceOrigin` 配置管理。 - -`requestHeaders` 为 `platformOrigin` 上的授权、资料、余额和退登请求添加仅 Host 使用的请求头。请求头值属于敏感配置,不包含在账号 UI 状态中。Authorization、X-DSH-Auth-Token、Host、Content-Type 及连接和消息分帧请求头由提供者保留。客户端身份请求头覆盖部署配置中的同名请求头。重定向会失败,不会转发请求头。开发环境 Cookie 应保存在私有配置或环境变量中;不会自动收集浏览器 Cookie。 - -私有 patch 也可通过 Cordis 表达式读取环境变量: - -```yaml -- id: deepseek-account - config: - platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN - allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' - requestHeaders: !!js | - process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} -``` - -已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。提供者固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。回调请求使用 state 和 PKCE 校验,不要求 RPC 鉴权。完成、取消和卸载仅移除本次尝试的路由。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 - -Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error` 写入标准错误及 Host 调试器 Console,前缀为 `[deepseek-account]`。成功请求、调用方主动取消和正常账号状态变化不输出日志;请求超时仍记录为失败。失败诊断包含接口路径、HTTP 状态、数值响应码、失败阶段、校验失败的字段路径、实际类型和校验码,以及浏览器 URL 拒绝规则,不包含请求头、请求和响应正文、授权 URL 或原始异常。 - -`rewriteBrowserOrigin` 默认为 `false`,要求浏览器地址同源。私有开发 patch 可设为 `true`,将授权页和完成页地址映射到 `platformOrigin`,保留固定路径和查询字符串。原地址必须使用 HTTPS 或已匹配配置来源;仍拒绝用户名密码、片段和非预期路径。发布的 profile 保持严格同源校验。 - -inferenceOrigin 默认为 `https://api.deepseek.com`。私有部署 patch 可将其替换为一个精确的 HTTP(S) 来源(含端口),让推理及文件请求通过 x-dsh-auth-token 认证。配置不得包含路径、URL 凭证、查询或片段。其他来源要求授权由配置的 platformOrigin 签发;仍拒绝 Mock token。本机授权不能认证官方生产 API。部署地址保存在私有 patch 中,不随默认配置发布。 - -提供者初始化时,若有效的已存授权 issuer 与 platformOrigin 不同,会在使用方读取账号状态前删除该本地授权,以未登录态继续启动,不发送远端退登请求;API Key 和设备标识保留。存储错误仍明确报错,账号 HTTP 或响应校验失败不会删除来源匹配的授权。 - - -## 理解实现 - -账号是否存在直接读取凭证存储,尝试状态直接投影私有状态。异步取消和提交由行为测试验证。 - - -## 深入探索 - -[凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 - -attemptTimeoutMs 包含初始化、等待浏览器和兑换的耗时。初始化不会延长绝对截止时间;服务端 TTL 只能缩短剩余时间。在到期前已获准的凭证持久化不再取消。 - - -## 模型体验 - -无,因为账号凭证只影响 HTTP 认证,不进入模型提示、Session 日志或工具结果。 - -#### KV Cache effect - -不改变模型请求前缀。 - -## 已知限制与后续工作 - - - -- 浏览器登录需要 Host webServer,仅支持通过带显式端口的 HTTP localhost、127.0.0.1 或 [::1] 本机访问及 SSH 本地转发,不支持非本机域名的反向代理。账号 token 没有过期或刷新流程;用户主动在 DSH 退出登录时,先删除本地授权,再在后台调用 POST /auth-api/v0/users/logout。远程失败不会恢复本地登录态。默认仅针对捕获的旧 token 最多额外重试五次,指数退避间隔为 1、2、4、8、16 秒;logoutMaxRetries(0–5)和 logoutRetryDelayMs 可配置该策略。每次请求使用 requestTimeoutMs。提供者关闭时取消请求和等待,不持久化待撤销任务。本地凭证删除失败仍向调用者报错。签发 token 前的授权尝试仍有有效期。初始化后的取消或超时会在后台发送一次 POST /auth-api/v0/dsh/auth_cancel,携带 auth_init.biz_data 中的 authorize_id 和原始 code_verifier,不附带账号授权。本地取消不等待该请求,也不会因失败而恢复;requestTimeoutMs 限制请求时间,提供者关闭时中止请求。TODO(product-error-ui):产品需定义已给定 biz code 的本地化文案和交互表现。在此之前,业务失败沿用现有“操作失败,请重试”兜底;其他 code 和 HTTP 错误也使用该兜底。开发授权不能认证生产请求。 - - -### 开发备注 - -[桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 - -登录后首次读取资料使用 auth_exchange 返回并经筛选的 user。user 为 null 或格式无效时回退到 current;后续刷新及 Host 重启也查询 current。current 请求失败时保留 Host 内存中同一凭证最近一次成功的资料;凭证变更或提供者销毁时清空。current 成功返回的稳定账号 ID 首次可用或变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取 getPlatformSession;重复相同 ID 的刷新不通知。exchange 负责登记提交的设备信息。 - -accountRequestHeaders 覆盖 requestHeaders,供 current、余额以及内嵌 Platform 页面/API 请求使用。Cookie 按名称合并,路由覆盖保留其他部署 Cookie。授权初始化、兑换、取消和退登保持使用 requestHeaders。两组请求头仅供 Host 和 Electron 主进程使用;快照的 userId 同样仅限 Host,渲染层 bootstrap 仅接收 origin 和 token。 - -账号提供者的 `embeddedPageDist` 配置为内嵌用量和充值页面 URL 添加 `dist` 查询参数。默认值为空;私有前端分支选择值应写在本地 profile patch 中。此配置不改变 API 地址或凭证传递方式。 - -Platform 钱包余额接受带可选科学计数法的十进制字符串(包括 `0E-16`),提供方保留原始字符串供调用方使用。 diff --git a/packages/credentials/deepseek-account-platform/locale/en.json b/packages/credentials/deepseek-account-platform/locale/en.json deleted file mode 100644 index 542b6b880f..0000000000 --- a/packages/credentials/deepseek-account-platform/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "deepseek-account-platform" - } -} diff --git a/packages/credentials/deepseek-account-platform/package.json b/packages/credentials/deepseek-account-platform/package.json deleted file mode 100644 index 9c4f09ff16..0000000000 --- a/packages/credentials/deepseek-account-platform/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-deepseek-account-platform", - "description": "Authorize DeepSeek accounts through browser PKCE", - "version": "0.2.2-rc.1", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/credentials/deepseek-account-platform" - }, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./types": { - "types": "./lib/types/types.d.ts", - "default": "./lib/types/types.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json", - "./locale/*.json": "./locale/*.json" - }, - "files": [ - "locale/*.json", - "lib/index.js", - "lib/types/**/*.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "lib/**/*.js.map", - "src" - ], - "license": "MIT", - "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-authorization": "workspace:*", - "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-host-webserver": "workspace:*" - }, - "devDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-authorization": "workspace:*", - "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-host-webserver": "workspace:*" - }, - "dependencies": { - "@deepseek-ai/schemastery": "workspace:~", - "zod": "4.6.6" - } -} diff --git a/packages/credentials/deepseek-account-platform/src/index.ts b/packages/credentials/deepseek-account-platform/src/index.ts deleted file mode 100644 index 0319a553c3..0000000000 --- a/packages/credentials/deepseek-account-platform/src/index.ts +++ /dev/null @@ -1,660 +0,0 @@ -/** Platform PKCE account provider; browser approval never bypasses local cancellation. */ -import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto' -import type { ServerResponse } from 'node:http' -import type {} from '@deepseek-ai/dsh-host-webserver' -import { arch, platform, release } from 'node:os' -import { promises as streamPromises } from 'node:stream' -import { Context, Service } from '@deepseek-ai/cordis' -import Schema from '@deepseek-ai/schemastery' -import { z } from 'zod' -import { DeepSeekAccount, installAccountTaskCancellation, mergePlatformCookies, platformClientHeaders, platformWireLocale, type AccountBonusBatch, type AccountBonusOrderId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from '@deepseek-ai/dsh-deepseek-account' -import { credentialKey } from '@deepseek-ai/dsh-credentials' -import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' -import { profile, readAccountDetail, readUnnotifiedBonuses, sendBonusNotified } from './details.ts' -import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' -import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' - -const KEY = credentialKey('deepseek-account-platform', 'default') -const DEVICE = credentialKey('deepseek-account-platform', 'device') -const grant = z.object({ version: z.literal(1), token: z.string().min(1), issuer: z.url() }) -const device = z.object({ id: z.uuid() }) - -/** Deployment-specific platform and request deadlines. */ -export interface Config { - /** Platform origin serving auth-api and browser pages. */ - platformOrigin?: 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. */ - embeddedPageDist?: string - /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ - inferenceOrigin?: string - /** Allow HTTP only on loopback for the development Mock. */ - 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. */ - requestHeaders?: Record - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ - accountRequestHeaders?: Record - /** Deadline for each platform HTTP request. */ - requestTimeoutMs?: number - /** Deadline for recharge-wallet queries; timeout returns a failed balance outcome. */ - balanceTimeoutMs?: number - /** Additional logout attempts after the first request fails, at most five. */ - logoutMaxRetries?: number - /** Delay before the first logout retry; each later delay doubles. */ - logoutRetryDelayMs?: number - /** Upper bound for the entire local attempt, even if the server advertises a longer TTL. */ - attemptTimeoutMs?: number -} -/** Validated deployment choices. */ -export const Config = Schema.object({ - platformOrigin: Schema.string().default('https://platform.deepseek.com'), - desktopPlatform: Schema.union([Schema.const('darwin'), Schema.const('win32'), Schema.const(null)]).default(null), - embeddedPageDist: Schema.string().default(''), - inferenceOrigin: Schema.string().default('https://api.deepseek.com'), - allowLoopbackHttp: Schema.boolean().default(false), - rewriteBrowserOrigin: Schema.boolean().default(false), - requestHeaders: Schema.dict(Schema.string().role('secret')).default({}), - accountRequestHeaders: Schema.dict(Schema.string().role('secret')).default({}), - requestTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), - balanceTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), - logoutMaxRetries: Schema.number().min(0).max(5).step(1).default(5), - logoutRetryDelayMs: Schema.number().min(1).max(60_000).default(1_000), - attemptTimeoutMs: Schema.number().min(1).max(3_600_000).default(600_000), -}) - -interface Attempt { - locale: 'en_US' | 'zh_CN' - clientHeaders: Record - view: SignInAttemptView - controller: AbortController - done: Promise - running: Promise - origin: string - loginSource: 'web' | 'desktop' - disposeCallback?: () => Promise - callback?: ServerResponse - initialProfile?: { token: string; value: AccountDetails['profile'] } - completionUrl?: string -} - -/** The platform implementation owns login state and its opaque stored grant. */ -export class PlatformAccount extends DeepSeekAccount { - static inject = ['credentials', 'authorization'] - static Config = Config - private readonly origin: string - private readonly embeddedPageDist: string - private readonly inferenceOrigin: string - private readonly rewriteBrowserOrigin: boolean - private readonly platform: 'darwin' | 'win32' | null - private readonly requestHeaders: Record - private readonly accountRequestHeaders: Record - private readonly requestTimeout: number - private readonly balanceTimeout: number - private readonly attemptTimeout: number - private readonly logoutPolicy: LogoutRetryPolicy - private readonly logoutLifetime = new AbortController() - private readonly revocations = new Set>() - private attempt: Attempt | undefined - private readonly listeners = new Set<(identityOnly: boolean) => void>() - /** - * Latest ready profile read and the grant token it was read with. Binding the token keeps a - * cached identity from answering for a credential that has since changed. - */ - private lastProfile: { readonly token: string; readonly profile: Extract } | undefined - private detailsLifetime = new AbortController() - private closed = false - private removing: Promise | undefined - - /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ - constructor(ctx: Context, config: Config = {}) { - super(ctx) - installAccountTaskCancellation(ctx) - const resolved = Config(config) - this.embeddedPageDist = resolved.embeddedPageDist - this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp) - const inference = new URL(resolved.inferenceOrigin) - if (!['http:', 'https:'].includes(inference.protocol) || inference.username || inference.password - || inference.pathname !== '/' || inference.search || inference.hash) { - throw new Error('account: inferenceOrigin must be an HTTP(S) origin without credentials, path, query or fragment') - } - this.inferenceOrigin = inference.origin - this.rewriteBrowserOrigin = resolved.rewriteBrowserOrigin - this.platform = resolved.desktopPlatform - this.requestHeaders = platformHeaders(resolved.requestHeaders) - const accountHeaders = platformHeaders(resolved.accountRequestHeaders) - this.accountRequestHeaders = { ...this.requestHeaders, ...accountHeaders } - if (accountHeaders.cookie !== undefined) { - this.accountRequestHeaders.cookie = mergePlatformCookies(this.requestHeaders.cookie ?? '', accountHeaders.cookie) - } - this.requestTimeout = resolved.requestTimeoutMs - this.balanceTimeout = resolved.balanceTimeoutMs - this.attemptTimeout = resolved.attemptTimeoutMs - this.logoutPolicy = { - maxRetries: resolved.logoutMaxRetries, delayMs: resolved.logoutRetryDelayMs, requestTimeoutMs: this.requestTimeout, - } - ctx.authorization.registerFlow({ - key: KEY, label: 'DeepSeek', methods: [{ id: 'browser', label: 'DeepSeek' }], - run: (session) => { - const attempt = this.attempt - if (attempt === undefined) return Promise.reject(new PlatformAuthError('protocol')) - attempt.running = this.run(session, attempt) - return attempt.running - }, - }) - ctx.on('credentials/record-updated', (key) => { - if (key !== KEY) return - this.invalidateDetails() - this.changed() - }) - ctx.effect(() => async () => { - this.closed = true - this.logoutLifetime.abort() - this.invalidateDetails() - const active = this.attempt - if (active !== undefined) { - if (active.view.phase !== 'committing') active.controller.abort() - await active.done - } - await this.removing - await Promise.all(this.revocations) - this.changed() - }, 'account: active attempt lifetime') - } - - async [Service.init](): Promise { - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined) return - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - if (parsed.data.issuer === this.origin) return - await this.ctx.credentials.deleteRecord(KEY) - } - - override async getState(): Promise { - const record = await this.ctx.credentials.readRecord(KEY) - if (record !== undefined && (record.kind !== 'grant' || !grant.safeParse(record.payload).success)) { - throw new PlatformAuthError('storage') - } - const attempt = this.attempt?.view ?? null - return { - status: record === undefined ? 'signed-out' : 'credential-stored', - // Credential removal can notify watchers before sign-out finishes clearing the attempt. - attempt: record === undefined && attempt?.phase === 'succeeded' ? null : attempt, - links: { usageUrl: new URL('/usage', this.origin).href, topUpUrl: new URL('/top_up', this.origin).href }, - } - } - - override async getProfile(client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - const result = await this.getDetail('profile', this.detailHeaders(client), { lifetime, stored }) - if (this.detailsLifetime !== lifetime) return null - if (result !== null) this.cacheProfile(stored.token, result) - if (result?.status !== 'failed') return result - // Only this same grant's last ready read may stand in for a failed refresh. - const cached = this.lastProfile?.token === stored.token ? this.lastProfile.profile : undefined - return cached ?? result - } - - override getBalance(client: AccountClientMetadata): Promise { - return this.getDetail('balance', this.detailHeaders(client)) - } - - override async getUnnotifiedBonuses(client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const headers = this.detailHeaders(client) - const stored = await this.readCurrentGrant(lifetime) - if (stored === null) return null - const accountId = await this.currentAccountId(lifetime, stored, headers) - if (accountId === null) return null - try { - const bonuses = await readUnnotifiedBonuses(this.origin, stored.token, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) - return { accountId, bonuses } - } catch (error) { - if (error instanceof AccountUnauthorizedError) { - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return null - } - throw error - } - } - - override async ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const headers = this.detailHeaders(client) - const stored = await this.readCurrentGrant(lifetime) - if (stored === null) return false - const current = await this.currentAccountId(lifetime, stored, headers) - if (current === null || current !== accountId) return false - try { - await sendBonusNotified(this.origin, stored.token, orderId, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) - return true - } catch (error) { - if (error instanceof AccountUnauthorizedError) { - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return false - } - throw error - } - } - - /** - * Resolve the profile identity bound to one captured grant, within that grant's credential lifetime. - * @param lifetime - credential lifetime the grant was captured under; a change discards the result. - * @param stored - captured grant; the identity query never re-reads a newer credential. - * @param headers - client identity headers of the calling operation. - * @returns the account identity, or null while signed out or after the credential changed. - */ - private async currentAccountId(lifetime: AbortController, stored: z.infer, - headers: Record): Promise { - // A profile already read for this same captured grant names the account, so a bonus read or - // acknowledgement reuses it instead of issuing another current query. - if (this.lastProfile?.token === stored.token) return this.identityOf(this.lastProfile.profile) - const details = await this.getDetail('profile', headers, { lifetime, stored }) - if (details === null) return null - if (details.status === 'failed') { - // The query named no identity, and the cache is empty or belongs to another grant. - throw new PlatformAuthError('network') - } - this.cacheProfile(stored.token, details) - return this.identityOf(details) - } - - /** - * Cache one ready profile against the grant token it was read with, so identity reuse cannot cross - * a credential change. A stable ID that first appears or changes notifies identity-enabled watch consumers, so - * identity consumers re-read getPlatformSession; repeated IDs stay silent. - * @param token - grant the profile was read with. - * @param profile - profile outcome to record when it carries account data. - */ - private cacheProfile(token: string, profile: AccountDetails['profile']): void { - if (profile.status !== 'ready') return - // Identity publishers re-read the session snapshot; wake them only when the stable ID changes. - const previous = this.lastProfile?.profile.value.id || null - this.lastProfile = { token, profile } - if (previous !== (profile.value.id || null)) this.changed(true) - } - - /** - * @param profile - ready profile projected for the UI. - * @returns the account identity it names. - * @throws PlatformAuthError when the profile carries no stable Platform id, which cannot isolate notices. - */ - private identityOf(profile: Extract): AccountUserId { - if (profile.value.id === null) throw new PlatformAuthError('protocol') - return profile.value.id - } - - private async getDetail(field: K, headers: Record, - captured?: { lifetime: AbortController; stored: z.infer }): Promise { - const lifetime = captured?.lifetime ?? this.detailsLifetime - const stored = captured?.stored ?? await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - if (field === 'profile' && this.attempt?.initialProfile?.token === stored.token) { - const initial = this.attempt.initialProfile.value - delete this.attempt.initialProfile - return initial as AccountDetails[K] - } - try { - const details = await readAccountDetail(field, this.origin, stored.token, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(field === 'balance' ? this.balanceTimeout : this.requestTimeout)]), headers) - return this.detailsLifetime !== lifetime ? null : details - } catch (_unauthorized) { - // readAccountDetail exposes only authenticated credential rejection failures. - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return null - } - } - - /** Deployment account headers plus the client identity headers derived from one call's metadata. */ - private detailHeaders(client: AccountClientMetadata): Record { - return { ...this.accountRequestHeaders, ...platformClientHeaders(this.platform, client) } - } - - override async rejectToken(token: string): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored?.token !== token || this.detailsLifetime !== lifetime) return - await this.expireCredential(token, lifetime) - } - - private async expireCredential(token: string, lifetime: AbortController): Promise { - this.removing ??= (async () => { - if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) - const record = await this.ctx.credentials.readRecord(KEY) - if (this.closed || this.detailsLifetime !== lifetime || record?.kind !== 'grant') return this.getState() - const current = grant.parse(record.payload) - if (current.token !== token || current.issuer !== this.origin) return this.getState() - await this.ctx.credentials.deleteRecord(KEY) - this.ctx.emit('deepseek-account/session-expired') - this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') - this.changed() - return this.getState() - })().finally(() => { this.removing = undefined }) - await this.removing - } - - override async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> { - const [record, session] = await Promise.all([ - this.ctx.credentials.readRecord(DEVICE), - this.getPlatformSession(), - ]) - const parsed = record?.kind === 'grant' ? device.safeParse(record.payload) : undefined - return { - ...parsed?.success ? { deviceId: parsed.data.id } : {}, - ...session?.userId == null ? {} : { userId: session.userId }, - osVersion: deviceOsVersion(), - } - } - - override async getPlatformSession(): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - // Deployment headers only; the consuming client adds the identity of its own UI. - const requestHeaders = { ...this.accountRequestHeaders } - // Identity comes from the profile read for this same grant; an unknown ID requires disposable - // browser storage. A replaced credential never publishes the account its predecessor named. - return { origin: this.origin, token: stored.token, - userId: this.lastProfile?.token === stored.token ? this.lastProfile.profile.value.id || null : null, - ...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}), - requestHeaders } - } - - private async readCurrentGrant(lifetime: AbortController): Promise | null> { - if (this.closed) return null - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined || lifetime.signal.aborted) return null - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - // A private origin override must never forward a grant issued by another environment. - if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') - return parsed.data - } - - override async resolveToken(url: string): Promise { - if (this.closed || this.removing !== undefined) return undefined - const destination = new URL(url) - if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined) return undefined - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const result = grant.safeParse(record.payload) - if (!result.success) throw new PlatformAuthError('storage') - // Development grants cannot authenticate production model or file requests. - const issuer = new URL(result.data.issuer) - if (result.data.token.startsWith('dsh_mock_')) return undefined - if (this.inferenceOrigin === 'https://api.deepseek.com') { - if (['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname)) return undefined - } else if (issuer.origin !== this.origin) return undefined - return result.data.token - } - - override async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { - if (this.removing !== undefined) await this.removing - const origin = loginOrigin(callbackOrigin) - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== undefined && ['initializing', 'waiting-browser', 'exchanging', 'committing'].includes(this.attempt.view.phase)) { - return this.getState() - } - const previous = this.attempt - if (previous !== undefined) { - await previous.done - // Disposal can close the provider while the previous attempt settles. - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== previous) return this.getState() - } - const attempt: Attempt = { - origin, loginSource, - locale: platformWireLocale(client.locale), - clientHeaders: platformClientHeaders(this.platform, client), - view: { id: randomUUID() as SignInAttemptId, phase: 'initializing' }, - controller: new AbortController(), done: Promise.resolve(), running: Promise.resolve(), - } - this.attempt = attempt - attempt.done = this.ctx.authorization.begin({ - key: KEY, signal: attempt.controller.signal, - interaction: { notify: () => undefined, prompt: () => Promise.reject(new PlatformAuthError('protocol')) }, - }).then((outcome) => { - this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' }) - if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) { - attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end() - } else attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() - }).catch((error: unknown) => { - const code = error instanceof PlatformAuthError ? error.code : 'protocol' - console.error('[deepseek-account] sign-in failed', { errorCode: code }) - this.update(attempt, { phase: code === 'expired' ? 'expired' : 'failed', errorCode: code }) - this.finishFailedCallback(attempt) - }).then(async () => { - // begin() may report cancellation before the HTTP work observes its signal. - await attempt.running.catch(() => undefined) - if (attempt.callback !== undefined) { - await streamPromises.finished(attempt.callback, { cleanup: true }).catch(() => undefined) - } - await attempt.disposeCallback?.() - }) - this.changed() - return this.getState() - } - - override async cancelSignIn(id: SignInAttemptId): Promise { - const attempt = this.attempt - if (attempt?.view.id === id) { - if (attempt.view.phase !== 'committing') { - attempt.controller.abort() - this.ctx.authorization.cancel(KEY) - } - await attempt.done - } - return this.getState() - } - - override signOut(client: AccountClientMetadata): Promise { - this.removing ??= (async () => { - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) - const record = await this.ctx.credentials.readRecord(KEY) - if (record !== undefined) { - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') - await this.ctx.credentials.deleteRecord(KEY) - this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) - } - this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') - this.changed() - return this.getState() - })().finally(() => { this.removing = undefined }) - return this.removing - } - - override async *watch(signal: AbortSignal, includeIdentityChanges = false): AsyncIterable { - let dirty = true - let wake: (() => void) | undefined - const wakeUp = (): void => { dirty = true; wake?.() } - const changed = (identityOnly: boolean): void => { if (!identityOnly || includeIdentityChanges) wakeUp() } - this.listeners.add(changed) - signal.addEventListener('abort', wakeUp, { once: true }) - try { - while (!this.closed && !signal.aborted) { - if (dirty) { dirty = false; yield await this.getState(); continue } - await new Promise((resolve) => { wake = resolve }) - } - } finally { - this.listeners.delete(changed) - signal.removeEventListener('abort', wakeUp) - } - } - - private revoke(token: string, headers: Record): void { - if (this.closed) return - const revocation = revokeAccount(this.origin, token, this.logoutPolicy, - this.logoutLifetime.signal, { ...this.requestHeaders, ...headers }).finally(() => { this.revocations.delete(revocation) }) - this.revocations.add(revocation) - } - - private invalidateDetails(): void { - this.lastProfile = undefined - this.detailsLifetime.abort() - this.detailsLifetime = new AbortController() - } - - private changed(identityOnly = false): void { for (const listener of this.listeners) listener(identityOnly) } - - private update(attempt: Attempt, value: Partial): void { - const { authorizeUrl: _url, ...rest } = attempt.view - attempt.view = { ...rest, ...value } - this.changed() - } - - private async run(session: AuthorizationSession, attempt: Attempt): Promise { - const webServer = this.ctx.get('webServer') - if (webServer === undefined) throw new PlatformAuthError('protocol') - const verifier = randomBytes(32).toString('base64url') - const state = randomBytes(32).toString('base64url') - const challenge = createHash('sha256').update(verifier).digest('base64url') - let authorizeId: string | undefined - const code = Promise.withResolvers() - // Callback requests may precede initialization settlement; the rejection is observed immediately. - void code.promise.catch(() => undefined) - const deadline = new AbortController() - let expiresAt = Date.now() + this.attemptTimeout - const signal = AbortSignal.any([session.signal, deadline.signal]) - let timer = setTimeout(() =>{ deadline.abort() }, this.attemptTimeout) - const abort = (): void => { code.reject(new PlatformAuthError('expired')) } - signal.addEventListener('abort', abort, { once: true }) - try { - attempt.disposeCallback = this.ctx.effect(() => webServer.register({ - kind: 'exact', path: '/oauth/callback', handler: (req, res) => { - let url: URL - try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } - catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } - const receivedCode = url.searchParams.get('code') - const receivedState = url.searchParams.get('state') ?? '' - const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) - && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) - if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || !validState || !receivedCode - || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { - res.writeHead(400, { 'cache-control': 'no-store' }).end(); return - } - if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { - res.writeHead(410, { 'cache-control': 'no-store' }).end(); return - } - attempt.callback = res - code.resolve(receivedCode) - }, - }), 'account: browser callback') - signal.throwIfAborted() - const redirectUri = `${attempt.origin}/oauth/callback` - const init = initialization.safeParse(await this.request('auth_init', { - code_challenge: challenge, code_challenge_method: 'S256', state, redirect_uri: redirectUri, locale: attempt.locale, - login_source: attempt.loginSource, - }, signal, attempt.clientHeaders), { reportInput: true }) - if (!init.success) this.rejectPayload('auth_init', init.error) - const authorizeUrl = browserUrl(init.data.authorize_url, this.origin, '/dsh/authorize', this.rewriteBrowserOrigin) - authorizeId = init.data.authorize_id - signal.throwIfAborted() - const now = Date.now() - expiresAt = Math.min(expiresAt, now + init.data.expires_in * 1000) - const remaining = expiresAt - now - if (remaining <= 0) { deadline.abort(); signal.throwIfAborted() } - clearTimeout(timer) - timer = setTimeout(() =>{ deadline.abort() }, remaining) - this.update(attempt, { phase: 'waiting-browser', authorizeUrl, expiresAt }) - const receivedCode = await code.promise - signal.throwIfAborted() - this.update(attempt, { phase: 'exchanging' }) - const deviceRecord = await this.ctx.credentials.modifyRecord(DEVICE, current => Promise.resolve(current === undefined - ? { kind: 'grant', payload: { id: randomUUID() } } : undefined)) - if (deviceRecord?.kind !== 'grant') throw new PlatformAuthError('storage') - const identity = device.parse(deviceRecord.payload) - const result = exchange.safeParse(await this.request('auth_exchange', { - code: receivedCode, code_verifier: verifier, redirect_uri: redirectUri, - device_id: identity.id, device_model: `${platform()}-${arch()}`, os_version: deviceOsVersion(), - }, signal, attempt.clientHeaders), { reportInput: true }) - if (!result.success) this.rejectPayload('auth_exchange', result.error) - const completionUrl = new URL(browserUrl(result.data.authorized_url, this.origin, '/dsh/authorized', this.rewriteBrowserOrigin)) - completionUrl.searchParams.set('login_source', attempt.loginSource) - attempt.completionUrl = completionUrl.href - if (Date.now() >= expiresAt) deadline.abort() - signal.throwIfAborted() - if (result.data.user != null) { - try { attempt.initialProfile = { token: result.data.token, value: { status: 'ready', value: profile(result.data.user) } } } - catch { - // Invalid optional user data falls back to current without discarding a valid authorization. - } - } - this.update(attempt, { phase: 'committing' }) - clearTimeout(timer) - try { await session.commit({ kind: 'grant', payload: { version: 1, token: result.data.token, issuer: this.origin } }) } - catch { throw new PlatformAuthError('storage') } - } catch (error) { - if (deadline.signal.aborted) throw new PlatformAuthError('expired') - throw error - } finally { - if (signal.aborted && authorizeId !== undefined) this.cancelRequest(authorizeId, verifier, attempt.clientHeaders) - clearTimeout(timer) - signal.removeEventListener('abort', abort) - // begin() settles the browser response and removes only this attempt’s route. - } - } - - private rejectPayload(stage: string, error: z.ZodError): never { - console.error('[deepseek-account] payload rejected', { - stage, issues: error.issues.map(issue => ({ - path: issue.path, code: issue.code, - receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input, - })), - }) - throw new PlatformAuthError('protocol') - } - - private cancelRequest(authorizeId: string, verifier: string, headers: Record): void { - if (this.closed) return - const cancellation = this.request('auth_cancel', { authorize_id: authorizeId, code_verifier: verifier }, - this.logoutLifetime.signal, headers).then(() => undefined, () => { - // Remote cancellation failures never reverse local cancellation or expose verifier diagnostics. - }).finally(() => { this.revocations.delete(cancellation) }) - this.revocations.add(cancellation) - } - - private request(method: string, body: unknown, signal: AbortSignal, headers: Record): Promise { - return requestPlatform(this.origin, method, body, - AbortSignal.any([signal, AbortSignal.timeout(this.requestTimeout)]), { ...this.requestHeaders, ...headers }) - } - - private finishFailedCallback(attempt: Attempt): void { - if (attempt.loginSource === 'web') { - const nonce = randomBytes(16).toString('base64url') - const message = attempt.locale === 'zh_CN' ? '登录失败,请关闭此标签页并在原页面重试。' - : 'Sign-in failed. Close this tab and try again in the original tab.' - attempt.callback?.writeHead(200, { - 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', - 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'`, - 'referrer-policy': 'no-referrer', - }).end(`${message}` - + `

    ${message}

    `) - } else { - // Native account subscribers focus the login window; retain the browser’s Platform document. - attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() - } - } -} -export default PlatformAccount - -/** OS identification shared by login and credential-free identity reads. */ -function deviceOsVersion(): string { - return `${platform()} ${release()}` -} diff --git a/packages/credentials/deepseek-account-platform/src/types.ts b/packages/credentials/deepseek-account-platform/src/types.ts deleted file mode 100644 index ed3d43d0f8..0000000000 --- a/packages/credentials/deepseek-account-platform/src/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Platform provider reuses the account service's client-safe state. */ -export type { AccountView, SignInAttemptView } from '@deepseek-ai/dsh-deepseek-account/types' diff --git a/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts b/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts deleted file mode 100644 index 959af7bc3f..0000000000 --- a/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts +++ /dev/null @@ -1,419 +0,0 @@ -/** Bonus notification reads and acknowledgements over the real Host HTTP path. */ -import { afterEach, expect, it, vi } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' -import { Context } from '@deepseek-ai/cordis' -import AuthorizationService from '@deepseek-ai/dsh-authorization' -import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' -import { credentialKey } from '@deepseek-ai/dsh-credentials' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountUserId, AccountView } from '@deepseek-ai/dsh-deepseek-account' -import { PlatformAccount } from '../src/index.ts' - -const cleanups: Array<() => Promise> = [] -afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) - -const ORDER = '4c1b0000-0000-4000-8000-000000000000' -const SECOND_ORDER = '5d2c0000-0000-4000-8000-000000000000' -const USER = 'test-user' - -/** Client identity supplied with each account operation; only the locale's primary subtag selects the wire locale. */ -const clientMetadata = (locale = 'en-US'): AccountClientMetadata => ({ version: '1.2.3', locale, timezoneOffsetSeconds: 28_800 }) - -interface Recorded { - readonly method: string | undefined - readonly url: string | undefined - readonly token: string | undefined - readonly locale: string | undefined - readonly bundleId: string | undefined - readonly platform: string | undefined - readonly version: string | undefined - readonly timezoneOffset: string | undefined - readonly contentType: string | undefined - readonly body: string | undefined -} - -/** Read one request body; the acknowledgement carries its order id in JSON, so the fixture keeps the exact bytes. */ -function requestBody(req: IncomingMessage): Promise { - return new Promise((resolve, reject) => { - let body = '' - req.setEncoding('utf8') - req.on('data', (chunk: string) => { body += chunk }) - req.on('error', reject) - req.on('end', () => { resolve(body) }) - }) -} - -async function fixture() { - const home = await mkdtemp(join(tmpdir(), 'dsh-bonus-')) - cleanups.push(() => rm(home, { recursive: true, force: true })) - const requests: Recorded[] = [] - let profileId: string | null = USER - let profileBizCode = 0 - let profileStatus = 200 - let bonusBizCode = 0 - let bonusStatus = 200 - let bonuses: unknown = [ - { order_id: ORDER, campaign: 'dsh_login_bonus', amount: '5.00', currency: 'CNY', - granted_at: '2026-09-21T12:00:00Z', expires_at: '2026-10-21T12:00:00Z', msg: '已赠送您 5.00 元 DSH 体验赠金。' }, - { order_id: SECOND_ORDER, campaign: 'dsh_login_bonus', amount: '1.50', currency: 'CNY', - granted_at: '2026-09-20T12:00:00Z', expires_at: '2026-10-20T12:00:00Z', msg: '已赠送您 1.50 元 DSH 体验赠金。' }, - ] - let ackBizCode = 0 - let ackStatus = 200 - let beforeProfileResponse: (() => Promise) | undefined - let origin = '' - const handle = async (req: IncomingMessage, res: ServerResponse): Promise => { - expect(req.headers.authorization).toBeUndefined() - const body = await requestBody(req) - requests.push({ method: req.method, url: req.url, token: req.headers['x-dsh-auth-token'] as string | undefined, - locale: req.headers['x-client-locale'] as string | undefined, - bundleId: req.headers['x-client-bundle-id'] as string | undefined, - platform: req.headers['x-client-platform'] as string | undefined, - version: req.headers['x-client-version'] as string | undefined, - timezoneOffset: req.headers['x-client-timezone-offset'] as string | undefined, - contentType: req.headers['content-type'], body: body === '' ? undefined : body }) - res.setHeader('content-type', 'application/json') - if (req.url === '/auth-api/v0/users/current') { - await beforeProfileResponse?.() - res.writeHead(profileStatus).end(JSON.stringify({ code: profileStatus === 200 ? 0 : 1, data: { biz_code: profileBizCode, - biz_data: { id: profileId, email: 't***@example.invalid', id_profile: { name: 'Test', picture: null } } } })) - return - } - if (req.url === '/api/v0/users/get_unnotified_bonuses') { - res.writeHead(bonusStatus).end(JSON.stringify({ code: bonusStatus === 200 ? 0 : 1, - data: { biz_code: bonusBizCode, biz_data: bonuses } })) - return - } - // The exact path is the assertion: a query parameter would fall through to the 404 below. - if (req.url === '/api/v0/users/ack_bonus_notified') { - res.writeHead(ackStatus).end(JSON.stringify(ackStatus === 200 - ? { code: 0, msg: '', data: { biz_code: ackBizCode, biz_msg: ackBizCode === 0 ? '' : 'BONUS_ORDER_NOT_FOUND', biz_data: null } } - : { code: 1, msg: 'INTERNAL', data: null })) - return - } - res.writeHead(404).end('{}') - } - const server = createServer((req, res) => { void handle(req, res).catch(() => { res.writeHead(500).end('{}') }) }) - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('missing listener') - origin = `http://127.0.0.1:${address.port}` - cleanups.push(async () => { - await new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }) - }) - const ctx = new Context() - const credentials = ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) - await credentials - const authorization = ctx.plugin(AuthorizationService) - await authorization - // The composed client identity is this fixture's choice; `null` is the web profile's documented setting. - const provider = ctx.plugin(PlatformAccount, { - platformOrigin: origin, allowLoopbackHttp: true, requestTimeoutMs: 5_000, desktopPlatform: null, - }) - await provider - cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose() }) - const key = credentialKey('deepseek-account-platform', 'default') - return { - account: ctx.deepseekAccount, ctx, requests, key, - grant: (token: string) => ctx.credentials.modifyRecord(key, () => Promise.resolve({ - kind: 'grant', payload: { version: 1, token, issuer: origin }, - })), - signOut: () => ctx.credentials.deleteRecord(key), - profileId: (value: string | null) => { profileId = value }, - failProfile: (bizCode = 17, status = 200) => { profileBizCode = bizCode; profileStatus = status }, - bonuses: (value: unknown) => { bonuses = value }, - failBonuses: (bizCode = 17, status = 200) => { bonusBizCode = bizCode; bonusStatus = status }, - failAck: (bizCode = 0, status = 200) => { ackBizCode = bizCode; ackStatus = status }, - onProfile: (hook: () => Promise) => { beforeProfileResponse = hook }, - } -} - -it('reads the identity once, then sends one call\'s client identity headers on both bonus requests', async () => { - const f = await fixture() - await f.grant('test-account-token') - const client = { version: '3.0.0', locale: 'zh-TW', timezoneOffsetSeconds: -18_000 } - await f.account.getUnnotifiedBonuses(client) - await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, client) - expect(f.requests.map(request => [ - request.url, request.bundleId, request.platform, request.version, request.locale, request.timezoneOffset, - ])).toEqual([ - ['/auth-api/v0/users/current', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ['/api/v0/users/get_unnotified_bonuses', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ['/api/v0/users/ack_bonus_notified', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ]) -}) - -it('queries the account identity once even across repeated reads and acknowledgements', async () => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')) - expect(f.requests.filter(request => request.url === '/auth-api/v0/users/current')).toHaveLength(1) -}) - -it('does not reuse a cached identity from another grant', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - await f.grant('rotated-token') - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - expect(f.requests.map(request => [request.url, request.token])).toEqual([ - ['/auth-api/v0/users/current', 'test-account-token'], - ['/auth-api/v0/users/current', 'rotated-token'], - ['/api/v0/users/get_unnotified_bonuses', 'rotated-token'], - ]) -}) - -it('publishes the identity a bonus read resolved, so the session can scope account storage', async () => { - const f = await fixture() - await f.grant('test-account-token') - const lifetime = new AbortController() - const states: AccountView[] = [] - const watching = (async () => { for await (const state of f.account.watch(lifetime.signal, true)) states.push(state) })() - try { - await expect.poll(() => states.length).toBe(1) - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toMatchObject({ accountId: USER }) - // The bonus read names the account, so identity consumers re-read the session snapshot. - await expect.poll(() => states.length).toBe(2) - expect(await f.account.getPlatformSession()).toMatchObject({ userId: USER, token: 'test-account-token' }) - } finally { - lifetime.abort() - await watching - } -}) - -it('reads unnotified bonuses with the platform origin, grant header, and locale header', async () => { - const f = await fixture() - await f.grant('test-account-token') - const batch = await f.account.getUnnotifiedBonuses(clientMetadata('zh-CN')) - expect(batch).toEqual({ - accountId: USER as AccountUserId, - bonuses: [ - { orderId: ORDER as AccountBonusOrderId, campaign: 'dsh_login_bonus', amount: '5.00', currency: 'CNY', - grantedAt: '2026-09-21T12:00:00Z', expiresAt: '2026-10-21T12:00:00Z', message: '已赠送您 5.00 元 DSH 体验赠金。' }, - { orderId: SECOND_ORDER as AccountBonusOrderId, campaign: 'dsh_login_bonus', amount: '1.50', currency: 'CNY', - grantedAt: '2026-09-20T12:00:00Z', expiresAt: '2026-10-20T12:00:00Z', message: '已赠送您 1.50 元 DSH 体验赠金。' }, - ], - }) - expect(f.requests).toEqual([ - { method: 'GET', url: '/auth-api/v0/users/current', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - { method: 'GET', url: '/api/v0/users/get_unnotified_bonuses', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - ]) -}) - -it.each([ - ['absent', {}, {}], - ['unvalidated', { campaign: null, amount: 'not-a-number', currency: 'EUR', granted_at: 42 }, - { campaign: null, amount: 'not-a-number', currency: 'EUR', grantedAt: 42 }], -])('accepts opaque order IDs with %s unused fields and acknowledges the same ID', async (_name, extra, expected) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([{ order_id: 'model-update-1', expires_at: '2099-01-01T00:00:00Z', title: 'Model news', msg: 'Model updated', ...extra }]) - const batch = await f.account.getUnnotifiedBonuses(clientMetadata('en')) - expect(batch?.bonuses).toEqual([ - { orderId: 'model-update-1', expiresAt: '2099-01-01T00:00:00Z', title: 'Model news', message: 'Model updated', ...expected }, - ]) - const notice = batch!.bonuses[0]! - expect(await f.account.ackBonusNotified(batch!.accountId, notice.orderId, clientMetadata('en'))).toBe(true) - expect(f.requests.at(-1)?.body).toBe(JSON.stringify({ order_id: 'model-update-1' })) -}) - -it.each([ - ['empty', { expires_at: '' }], - ['null', { expires_at: null }], - ['absent', {}], -])('accepts %s expiry as a notice that never expires', async (_name, expiry) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([{ order_id: 'notice', msg: 'News', ...expiry }]) - expect((await f.account.getUnnotifiedBonuses(clientMetadata('en')))?.bonuses).toEqual([ - { orderId: 'notice', expiresAt: '', message: 'News' }, - ]) -}) - -it.each([ - ['zh-CN', 'zh_CN'], - ['en-US', 'en_US'], -])('selects %s copy through the locale header and never a language query', async (locale, wireLocale) => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getUnnotifiedBonuses(clientMetadata(locale)) - expect(f.requests.map(request => request.locale)).toEqual([wireLocale, wireLocale]) - expect(f.requests.map(request => request.url)).toEqual([ - '/auth-api/v0/users/current', - '/api/v0/users/get_unnotified_bonuses', - ]) -}) - -it.each([ - ['a non-string title', [{ order_id: 'order', title: 42, expires_at: 'b', msg: 'm' }]], - ['a non-string order id', [{ order_id: 42, expires_at: 'b', msg: 'm' }]], - ['a non-string expiry', [{ order_id: 'order', expires_at: 42, msg: 'm' }]], - ['a missing message', [{ order_id: ORDER, campaign: 'c', amount: '5.00', currency: 'CNY', granted_at: 'a', expires_at: 'b' }]], - ['a payload that is not a list', { bonuses: [] }], -])('rejects a malformed unnotified payload: %s', async (_name, payload) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses(payload) - await expect(f.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('acknowledges a displayed bonus with the grant, locale, and a JSON body', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('zh-CN'))).toBe(true) - expect(f.requests).toEqual([ - { method: 'GET', url: '/auth-api/v0/users/current', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - { method: 'POST', url: '/api/v0/users/ack_bonus_notified', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800', - contentType: 'application/json', body: `{"order_id":"${ORDER}"}` }, - ]) -}) - -it.each([ - ['the unnotified read', (f: Awaited>) => { - f.failBonuses(0, 401) - return f.account.getUnnotifiedBonuses(clientMetadata('en')) - }, null], - ['the acknowledgement', (f: Awaited>) => { - f.failAck(0, 401) - return f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')) - }, false], -])('expires the rejected grant when %s returns HTTP 401', async (_name, run, signedOutOutcome) => { - const f = await fixture() - await f.grant('test-account-token') - const expired = vi.fn() - f.ctx.on('deepseek-account/session-expired', expired) - // A rejected authenticated request names an invalid credential, so the provider drops it locally - // exactly as the profile and balance reads do; the caller sees its signed-out outcome. - expect(await run(f)).toBe(signedOutOutcome) - expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) - expect(expired).toHaveBeenCalledOnce() -}) - -it.each([ - ['read', (f: Awaited>) => f.account.getUnnotifiedBonuses(clientMetadata('en')), null], - ['acknowledgement', (f: Awaited>) => - f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')), false], -])('ignores a bonus %s rejection whose response cleanup overlaps a credential replacement', async (_name, run, outcome) => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getProfile(clientMetadata()) - const response = new Response('', { status: 401 }) - const cancel = response.body!.cancel.bind(response.body) - // Credential changes can arrive while the response reader releases a rejected response body. - const cleanup = vi.spyOn(response.body!, 'cancel').mockImplementation(async () => { - await f.grant('replacement-token') - await cancel() - }) - const fetchResponse = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) - const expired = vi.fn() - f.ctx.on('deepseek-account/session-expired', expired) - try { - expect(await run(f)).toBe(outcome) - expect(cleanup).toHaveBeenCalledOnce() - expect(expired).not.toHaveBeenCalled() - expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) - expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) - } finally { cleanup.mockRestore(); fetchResponse.mockRestore() } -}) - -it('retains the grant when an acknowledgement returns HTTP 500', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(0, 500) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))) - .rejects.toThrow('account: network') - expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) -}) - -it('rejects the supplied BONUS_ORDER_NOT_FOUND envelope as a business failure', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(1) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))) - .rejects.toThrow('account: protocol') - expect(f.requests[1]).toMatchObject({ - method: 'POST', url: '/api/v0/users/ack_bonus_notified', locale: 'en_US', - contentType: 'application/json', body: `{"order_id":"${ORDER}"}`, - }) -}) - -it.each([ - ['a business failure', 1, 200, 'account: protocol'], - ['an HTTP failure', 0, 500, 'account: network'], -])('surfaces %s as a retryable acknowledgement failure', async (_name, bizCode, status, message) => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(bizCode, status) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).rejects.toThrow(message) -}) - -it('does not acknowledge a notification from another account', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.ackBonusNotified('other-user' as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).toBe(false) - expect(f.requests.map(request => request.url)).toEqual(['/auth-api/v0/users/current']) -}) - -it('returns signed-out outcomes without any request', async () => { - const f = await fixture() - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toBeNull() - expect(await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).toBe(false) - expect(f.requests).toEqual([]) -}) - -it('discards a read that a credential change invalidated before it published', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.onProfile(async () => { await f.grant('rotated-token') }) - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toBeNull() - expect(f.requests.map(request => request.url)).toEqual(['/auth-api/v0/users/current']) -}) - -it('reports an unknown identity as retryable and an absent id as a protocol failure', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failProfile() - await expect(f.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: network') - const absent = await fixture() - await absent.grant('test-account-token') - absent.profileId(null) - await expect(absent.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('reuses a cached identity for the same credential after a failed query', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - f.failProfile() - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).resolves.toBe(true) -}) - -it('refuses a cached identity that carries no Platform id', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.profileId(null) - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - f.failProfile() - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('treats a null title as absent without rejecting other notifications', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([ - { order_id: 'untitled', title: null, msg: 'News' }, - { order_id: 'titled', title: 'Update', msg: 'Details' }, - ]) - expect((await f.account.getUnnotifiedBonuses(clientMetadata('en')))?.bonuses).toEqual([ - { orderId: 'untitled', expiresAt: '', message: 'News' }, - { orderId: 'titled', title: 'Update', expiresAt: '', message: 'Details' }, - ]) -}) diff --git a/packages/credentials/deepseek-account-platform/tsconfig.json b/packages/credentials/deepseek-account-platform/tsconfig.json deleted file mode 100644 index 63c81daaea..0000000000 --- a/packages/credentials/deepseek-account-platform/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../deepseek-account" - }, - { - "path": "../authorization" - }, - { - "path": "../credentials" - }, - { - "path": "../../../vendor/schemastery" - }, - { - "path": "../../host/webserver" - } - ] -} diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/credentials/deepseek-account/README.i18n.yaml index 7ac8b46fac..7c8e7b9d6f 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/credentials/deepseek-account/README.i18n.yaml @@ -3,26 +3,26 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/credentials/deepseek-account/README.md /: - en: 30a2d1a634d60f4a - zh: 9fbf972d342f8ba2 + en: 9dbb9bc3960a11fe + zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 4333ad7e5c2d257f - zh: 1f1acbb68131d328 + en: 78e86576b7f38038 + zh: 7ec9f58f21ce00bf /deepseek-ai-dsh-deepseek-account/summary: - en: 26e77d24d904dd48 - zh: abc2d141826091f9 + en: 28bcca957bf6abf4 + zh: 4a3fc8a59f2925bc /deepseek-ai-dsh-deepseek-account/table-of-contents: en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: d7825ac71d3acb22 - zh: 337bb5048aaade09 + en: a334962d65816a50 + zh: 28f66b089476123a /deepseek-ai-dsh-deepseek-account/understand-the-implementation: - en: ca361e6eb61faf02 - zh: d14923826e86293a + en: 76d2da2dab100ac3 + zh: 2c9404f27915daab /deepseek-ai-dsh-deepseek-account/further-exploration: - en: 5a57b4b331031f41 - zh: 8b72ac64ed244f58 + en: adda341390cbdb9b + zh: e564f30150373228 /deepseek-ai-dsh-deepseek-account/model-experience: en: ee1df7ca3467ee3f zh: 84904a5148da3862 @@ -30,8 +30,8 @@ en: ca3015e252db0114 zh: ebca9253cf15e8e9 /deepseek-ai-dsh-deepseek-account/known-limitations-and-deferred-work: - en: 0960f4968520bf50 - zh: 6a45253b706eceb0 + en: 1b26fcb10e139c27 + zh: c419d805bf62d62d /deepseek-ai-dsh-deepseek-account/known-limitations-and-deferred-work/dev-note: - en: 01eda6d8c3a86813 - zh: 9a4fd8c0571c33f4 + en: c6980daf81e68974 + zh: 58d58e6ad468f749 diff --git a/packages/credentials/deepseek-account/README.md b/packages/credentials/deepseek-account/README.md index 16cdf91af5..28e3b20afe 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/credentials/deepseek-account/README.md @@ -1,5 +1,5 @@ --- -description: "Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin." +description: "Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in." kind: "package-reference" --- @@ -7,23 +7,21 @@ kind: "package-reference" English | [中文](README.zh.md) -getPlatformSession returns a Host-only origin/token snapshot for native Platform embedding, or null when signed out. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile holds no ID. The snapshot reuses that ID without issuing a profile request, 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 preference storage by origin and userId and use temporary storage while userId is null. It is absent from account-controller RPC and Client state. Consumers destroy documents holding a snapshot when the account changes. The snapshot carries deployment request headers only; the embedding client composes the Platform client identity of its own UI. +Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The service derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. -`platformClientHeaders` builds the five Platform client headers for one call from its `AccountClientMetadata` and the composition's desktop platform: `x-client-bundle-id` is intentionally empty, `x-client-platform` is `web` unless the Desktop profile supplies `darwin` or `win32`, `x-client-version` is the calling build's version, `x-client-locale` reduces the active UI language to `zh_CN` or `en_US` through the exported `platformWireLocale`, and `x-client-timezone-offset` is whole seconds east of UTC. A consumer whose request body carries that same wire locale reuses `platformWireLocale` so the header and body cannot disagree. +getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its 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 issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. -getUnnotifiedBonuses returns the granted bonuses Platform has not yet recorded as displayed, together with the account they belong to; ackBonusNotified records one bonus the user actually saw. The acknowledgement names that account, so a notification read under one account is never confirmed for another. +`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -`rejectToken` accepts a Host inference request’s rejected token and removes only the matching current login; a late rejection cannot clear a replacement credential. - -`deepseek-account/session-expired` notifies current subscribers once after a rejected credential is removed. Account snapshots carry no expiry notice, so reconnecting does not repeat the toast. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. ## Summary -Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin. +Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in. -`SignInErrorCode` distinguishes `no-response` (fetch returned no Response) from HTTP and response-validation failures so clients can offer network troubleshooting. +Platform requests report `no-response` when fetch rejects before returning a Response, including request timeouts. HTTP errors and response-body failures do not use this code; authorization-attempt expiry retains `expired`. -`getDeviceIdentity()` returns existing device and account IDs plus the login OS version string, without credentials or device creation. +Device identity reads validate the existing login device record and expose only its ID, the current account ID, and the shared login OS version string. ## Table of Contents @@ -34,25 +32,62 @@ Account consumers read stored login state, start or cancel a browser login, and ## Use this package -`AccountProfile.avatarUrl` is an optional profile image URL; null or absence means no avatar. +The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. -Successful local sign-out emits `deepseek-account/signed-out`. The platform provider installs the account-owned cancellation listener, which checks running Agents against `session.requestContext().provider` and cancels account tasks while retaining inboxes. The account controller uses the same predicate for its confirmation dialog. No additional Agent state is maintained. Before a new turn binds its first request, this predicate still sees the previous turn’s provider. +`DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. -The service defines account operations and reconnectable state snapshots. The platform provider owns the protocol and stored grant. Credentials are Host-only; the API controller exports state and commands without resolveToken. +The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. Mounting the service installs account-task cancellation. -Account model failures with `ACCOUNT_SIGN_IN_REQUIRED` emit `deepseek-account/model-sign-in-required`; the Client receives this live event for sign-in guidance. Other request errors do not emit it. +The `agents` service is optional. `hasRunningAccountTasks()` returns false when it is absent; when present, it checks running tasks for the account provider. + +The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. + +Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. + +getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. + +getNotifications reads `GET /api/v0/users/notifications/list`; getNotificationContent reads `GET /api/v0/users/notifications/content?id=`, including consumed notifications. The list also validates the required positive `next_poll_after` against browser timer limits and projects it as `nextPollAfterSeconds`. Both use x-client-locale. The list envelope requires a valid polling delay and notification array. Each notification is decoded separately; malformed fields or unsupported actions skip that notification with a diagnostic, preserving valid neighbors and server order. Skipped notifications are not shown or reported. A malformed single-content response still rejects, allowing the client to retain the current content. reportNotificationEvent posts `POST /api/v0/users/notifications/events` with notification_id and type displayed, cta_clicked, or dismissed. A valid acked response records the server decision without closing the local card. Each operation captures the current grant and its cancellation lifetime without a current-user preflight. Credential changes cancel the old lifetime and discard its late replies; token values remain Host-only. Other HTTP, business, and response-validation failures reject; HTTP 401 or response code 40003 invalidate only the current grant and return a signed-out result. + +Balance requests use balanceTimeoutMs (30,000ms by default); timeout returns a failed outcome without clearing the account or manufacturing a zero balance. Configure platformOrigin, allowLoopbackHttp, requestTimeoutMs, balanceTimeoutMs, and attemptTimeoutMs in the plugin row. HTTP is accepted only for explicitly enabled loopback development. The service registers /oauth/callback on the existing Host webServer before auth_init, validates state, exchanges an S256 PKCE code once, and commits a grant before redirecting to auth_exchange.biz_data.authorized_url. Browser destinations default to the configured platform origin and always require the fixed /dsh/authorize or /dsh/authorized path. The completion URL sets `login_source` to the initiating client (`web` or `desktop`) and preserves other Platform-supplied query parameters. Device identity is a separate random UUID record shared by processes using the same credential store; device_model reports OS and architecture. + +platformOrigin defaults to `https://platform.deepseek.com` for login, profile, balance, logout, external navigation, and native embedded pages. harnessOrigin defaults to `https://harness.deepseek.com` for notification list, content, and events only. Private deployments set harnessOrigin explicitly. Both accept HTTPS, or loopback HTTP when allowLoopbackHttp is enabled. Model and file token destinations use inferenceOrigin. + +`requestHeaders` adds Host-only headers to Platform and notification API requests. `accountRequestHeaders` overrides them for profile, balance, notifications, and native embedded pages; Cookie pairs merge by name. Header values are secret configuration and are excluded from account UI state. Authorization, X-DSH-Auth-Token, Host, Content-Type and connection/framing headers are reserved. Client identity headers override same-named deployment headers. Redirects fail without forwarding headers. Store deployment cookies in private configuration or environment variables; browser cookies are not collected automatically. + +A private patch can read environment variables through Cordis expressions: + +```yaml +- id: deepseek-account + config: + platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN + allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' + requestHeaders: !!js | + process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} +``` + +The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The service fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. Callback requests use state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt route. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. + +Host diagnostics use `console.error` with the `[deepseek-account]` prefix on standard error and in the Host inspector Console, only for request, response-validation, or sign-in failures. Successful requests, caller cancellation, and normal account state changes are silent; request timeouts remain failures. Failure diagnostics include endpoint paths, HTTP status, numeric response codes, failure stages, invalid field paths, received types and validation codes, and browser URL rejection rules; headers, request and response bodies, authorization URLs, and raw exceptions are excluded. + +`rewriteBrowserOrigin` defaults to `false`, requiring same-origin browser URLs. A private development patch may set it to `true` to map authorization and completion URLs to `platformOrigin`, preserving their fixed paths and query strings. Source URLs must use HTTPS or already match the configured origin; user information, fragments and unexpected paths remain rejected. Shipped profiles retain strict same-origin validation. + +inferenceOrigin defaults to `https://api.deepseek.com`. A private deployment patch may replace it with one exact HTTP(S) origin, including its port, for inference and file authentication through x-dsh-auth-token. Paths, URL credentials, queries and fragments are invalid configuration. Alternate origins require a grant issued by the configured platformOrigin; mock tokens remain excluded. Loopback grants cannot authenticate the official production API. Deployment addresses belong in private patches, not shipped configuration. + +At service initialization, a valid stored grant whose issuer differs from platformOrigin is deleted locally before consumers read account state. Startup continues signed out without a remote logout request; API keys and device identity remain stored. Storage failures remain explicit, and account HTTP or response-validation failures do not delete a matching grant. ## Understand the implementation -The service defines account operations without maintaining a second credential index. The provider owns persistence and login lifecycle checks. +Account presence reads the credential store, and attempt state projects private state directly. Behavior tests verify asynchronous cancellation and commit ordering. ## Further Exploration The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. -A ready AccountDetails.balance keeps recharge wallets in value and bonus wallets in bonusWallets; both arrays preserve decimal strings and currency. Query failure supplies neither amount. +The attemptTimeoutMs limit includes initialization, browser waiting, and exchange. Initialization does not extend its absolute deadline; the server TTL may only shorten the remaining time. Credential persistence admitted before expiry completes without cancellation. + +Account updates share one ordered stream. A credential write takes priority over pending progress snapshots; a state read interrupted by a newer credential lifetime is discarded. ## Model Experience @@ -67,11 +102,17 @@ No model request prefix changes. -- Account tokens have no expiry or refresh flow. Sign-out removes the local grant before background provider revocation; remote logout failures never restore local login. Profile and balance query failures retain the stored grant. getProfile / getBalance reports profile and balance query outcomes independently. +- Browser sign-in requires the Host webServer. Only local access and SSH local forwarding through HTTP localhost, 127.0.0.1, or [::1] with an explicit port are supported; non-loopback reverse proxies are unsupported. Account tokens have no expiry or refresh flow; explicit DSH sign-out removes the local grant before calling POST /auth-api/v0/users/logout in the background. Remote failures never restore local login. The captured old token receives at most five additional attempts with exponential delays of 1, 2, 4, 8, and 16 seconds by default; logoutMaxRetries (0–5) and logoutRetryDelayMs configure that policy. Each request uses requestTimeoutMs. Provider shutdown aborts requests and waits, and pending revocations are not persisted. Local credential deletion failures remain visible to the caller. Authorization-attempt deadlines still apply before a token is issued. Cancellation or timeout after initialization sends one background POST /auth-api/v0/dsh/auth_cancel with the authorize_id from auth_init.biz_data and the original code_verifier, without account authorization. Local cancellation never waits for this request or reverses on failure; requestTimeoutMs bounds it, and provider shutdown aborts it. TODO(product-error-ui): Product must define localized copy and UI behavior for the supplied biz_code values. Until then, business failures use the existing generic retry message; other codes and HTTP errors use the same fallback. Development grants never authenticate production requests. ### Dev Note The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. -PlatformSession may carry Host-only requestHeaders from Host to Electron main: deployment headers only, because the embedded document's client identity is composed where its locale, timezone and version are known. Consumers must exclude those headers from renderer bootstrap and restrict them to the configured origin. userId is Host-only on the same terms and never enters renderer bootstrap. mergePlatformCookies preserves unrelated cookie pairs while replacing matching names. +The first profile read after sign-in uses the sanitized user returned by auth_exchange. A null or malformed user falls back to current; subsequent refreshes and Host restarts also query current. Failed current requests retain the latest successful profile for the same credential in Host memory; credential changes and disposal clear it. A ready current response whose stable account ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, so identity consumers re-read getPlatformSession; refreshes that repeat the same ID stay silent. Exchange registers the submitted device information. + +accountRequestHeaders overlays requestHeaders for current, balance and embedded Platform page/API requests. Cookie pairs merge by name so routing overrides retain other deployment cookies. Authorization initialization, exchange, cancellation and logout keep requestHeaders. Both maps remain private to Host and Electron main; the session's userId stays Host-only too, and renderer bootstrap receives only origin and token. + +The account provider’s `embeddedPageDist` configuration adds a `dist` query parameter to embedded Usage and Top-up URLs. Its default is empty; private frontend branch selectors belong in the local profile patch. It does not change API URLs or credential delivery. + +Platform wallet balances accept decimal strings with optional scientific notation (including `0E-16`); the service preserves the original string for consumers. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/credentials/deepseek-account/README.zh.md index 2ef0d01d89..628fd2ed61 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/credentials/deepseek-account/README.zh.md @@ -1,5 +1,5 @@ --- -description: "账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。" +description: "通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。" kind: "package-reference" --- @@ -7,23 +7,21 @@ kind: "package-reference" [English](README.md) | 中文 -getPlatformSession 为原生 Platform 内嵌提供仅限 Host 的 origin/token 快照,退登时返回 null。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器偏好存储的键,userId 为 null 时改用临时存储。账号控制器 RPC 和 Client 状态不包含此方法及快照。账号变化时,使用方销毁持有旧快照的文档。快照只携带部署请求头;Platform 客户端身份由发起请求的内嵌客户端自行组装。 +每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。服务据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 -`platformClientHeaders` 依据单次调用的 `AccountClientMetadata` 与组合出的桌面平台生成五个 Platform 客户端请求头:`x-client-bundle-id` 有意保持为空字符串,`x-client-platform` 在没有 Desktop profile 提供 `darwin` 或 `win32` 时为 `web`,`x-client-version` 为调用方构建的版本,`x-client-locale` 通过导出的 `platformWireLocale` 将当前界面语言归约为 `zh_CN` 或 `en_US`,`x-client-timezone-offset` 为东为正的整秒偏移。请求正文需要同一个线上语言值时,消费方复用 `platformWireLocale`,使请求头与正文不会不一致。 +getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 -getUnnotifiedBonuses 返回平台尚未记录为已展示的赠金及其所属账号;ackBonusNotified 记录用户实际看到的那一笔赠金。确认请求携带该账号,因此在一个账号下读取的通知绝不会被确认到另一个账号。 +`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -`rejectToken` 接收 Host 推理请求被拒绝的 token,仅删除与它匹配的当前登录凭据;延迟返回的拒绝不能清除替换后的凭据。 - -`deepseek-account/session-expired` 在移除被拒绝的凭据后,向当前订阅方通知一次。账号快照不携带失效提示,因此重新连接不会重复弹出 toast。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 ## 概述 -账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。 +通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。 -`SignInErrorCode` 将 `no-response`(fetch 未返回 Response)与 HTTP 和响应校验失败区分开,使客户端可以提示检查网络。 +当 fetch 在返回 Response 前拒绝(包括单次请求超时)时,Platform 请求报告 `no-response`。HTTP 错误和响应体失败不使用此代码;授权尝试到期仍使用 `expired`。 -`getDeviceIdentity()` 返回已有设备和账户 ID 以及登录使用的操作系统版本字符串,不返回凭据,也不创建设备标识。 +设备身份读取会校验已有登录设备记录,仅提供设备 ID、当前账户 ID 和与登录共用的操作系统版本字符串。 ## 目录 @@ -34,25 +32,62 @@ getUnnotifiedBonuses 返回平台尚未记录为已展示的赠金及其所属 ## 使用此包 -本地成功退出登录后发出 `deepseek-account/signed-out`。Platform 提供方安装账号模块的取消监听器,根据运行中 Agent 的 `session.requestContext().provider` 判断账号任务,取消时保留收件箱。账号控制器的确认弹窗复用同一判断,不维护额外 Agent 状态。新轮次绑定首请求前,该判断仍读取上一轮的提供方。 +服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 -`AccountProfile.avatarUrl` 是可选的账号头像 URL;为空或缺失时表示没有头像。 +`DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 -该服务定义账号操作和可重连的状态快照。平台提供者负责协议和授权记录。凭证仅限 Host;API 控制器只导出状态与操作,不导出 resolveToken。 +`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。挂载服务时会安装账号任务取消逻辑。 -账号模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时,发出 `deepseek-account/model-sign-in-required`,Client 接收该实时事件以提示登录。其他请求错误不触发此事件。 +`agents` 服务为可选依赖。未提供时,`hasRunningAccountTasks()` 返回 false;提供时,检查使用账号服务的运行中任务。 + +账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 + +本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 + +getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 + +getNotifications 读取 `GET /api/v0/users/notifications/list`;getNotificationContent 读取 `GET /api/v0/users/notifications/content?id=`,支持已消费通知。列表还会校验必填的正数 `next_poll_after` 不超出浏览器计时范围,并投影为 `nextPollAfterSeconds`。二者都通过 x-client-locale 指定语言。列表外层要求有效的轮询间隔和通知数组。每条通知单独解码;字段格式错误或操作不受支持时,记录诊断并跳过该条,保留其他有效通知及服务端顺序。被跳过的通知不会展示或上报。单条内容响应格式错误时仍拒绝请求,让客户端保留当前内容。reportNotificationEvent 向 `POST /api/v0/users/notifications/events` 发送 notification_id 和 type displayed、cta_clicked 或 dismissed。有效的 acked 响应表示服务端消费决策,不会关闭本地卡片。每项操作都捕获当前授权和取消生命周期,不前置查询当前用户;凭据变化会取消旧生命周期并丢弃迟到的响应,token 始终只留在 Host。其他 HTTP、业务和响应校验失败均拒绝;HTTP 401 或响应码 40003 仅使当前授权失效,并返回未登录结果。 + +余额请求使用 balanceTimeoutMs(默认 30,000ms);超时返回失败结果,不清除账号,也不制造零余额。在插件行配置 platformOrigin、allowLoopbackHttp、requestTimeoutMs、balanceTimeoutMs 和 attemptTimeoutMs。HTTP 仅用于显式启用的本机开发。服务先在现有 Host webServer 注册 /oauth/callback,再调用 auth_init;校验 state、使用 S256 PKCE 授权码兑换一次,并在跳转 auth_exchange.biz_data.authorized_url 前提交授权记录。浏览器地址默认要求匹配配置的平台来源,并始终要求固定的 /dsh/authorize 或 /dsh/authorized 路径。完成页地址将 `login_source` 设为发起登录的客户端类型(`web` 或 `desktop`),并保留平台返回的其他查询参数。设备标识是独立的随机 UUID 记录,由使用同一凭证存储的进程共享;device_model 报告操作系统和架构。 + +platformOrigin 默认为 `https://platform.deepseek.com`,用于登录、资料、余额、退出登录、外部导航和原生内嵌页面。harnessOrigin 默认为 `https://harness.deepseek.com`,仅用于通知 list、content 和 events 接口。私有部署需显式设置 harnessOrigin。二者均接受 HTTPS;启用 allowLoopbackHttp 后也接受回环 HTTP。模型和文件 token 目标使用 inferenceOrigin。 + +`requestHeaders` 为 Platform 和通知 API 请求添加仅 Host 使用的请求头。`accountRequestHeaders` 为资料、余额、通知和原生内嵌页面覆盖这些请求头;Cookie 按名称合并。请求头值属于敏感配置,不包含在账号 UI 状态中。Authorization、X-DSH-Auth-Token、Host、Content-Type 及连接和消息分帧请求头由服务保留。客户端身份请求头覆盖部署配置中的同名请求头。重定向会失败,不会转发请求头。开发环境 Cookie 应保存在私有配置或环境变量中;不会自动收集浏览器 Cookie。 + +私有 patch 也可通过 Cordis 表达式读取环境变量: + +```yaml +- id: deepseek-account + config: + platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN + allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' + requestHeaders: !!js | + process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} +``` + +已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。服务固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。回调请求使用 state 和 PKCE 校验,不要求 RPC 鉴权。完成、取消和卸载仅移除本次尝试的路由。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 + +Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error` 写入标准错误及 Host 调试器 Console,前缀为 `[deepseek-account]`。成功请求、调用方主动取消和正常账号状态变化不输出日志;请求超时仍记录为失败。失败诊断包含接口路径、HTTP 状态、数值响应码、失败阶段、校验失败的字段路径、实际类型和校验码,以及浏览器 URL 拒绝规则,不包含请求头、请求和响应正文、授权 URL 或原始异常。 + +`rewriteBrowserOrigin` 默认为 `false`,要求浏览器地址同源。私有开发 patch 可设为 `true`,将授权页和完成页地址映射到 `platformOrigin`,保留固定路径和查询字符串。原地址必须使用 HTTPS 或已匹配配置来源;仍拒绝用户名密码、片段和非预期路径。发布的 profile 保持严格同源校验。 + +inferenceOrigin 默认为 `https://api.deepseek.com`。私有部署 patch 可将其替换为一个精确的 HTTP(S) 来源(含端口),让推理及文件请求通过 x-dsh-auth-token 认证。配置不得包含路径、URL 凭证、查询或片段。其他来源要求授权由配置的 platformOrigin 签发;仍拒绝 Mock token。本机授权不能认证官方生产 API。部署地址保存在私有 patch 中,不随默认配置发布。 + +服务初始化时,若有效的已存授权 issuer 与 platformOrigin 不同,会在使用方读取账号状态前删除该本地授权,以未登录态继续启动,不发送远端退登请求;API Key 和设备标识保留。存储错误仍明确报错,账号 HTTP 或响应校验失败不会删除来源匹配的授权。 ## 理解实现 -服务只定义账号操作,不维护第二份凭证索引。提供者负责持久化和登录生命周期检查。 +账号是否存在直接读取凭证存储,尝试状态直接投影私有状态。异步取消和提交由行为测试验证。 ## 深入探索 [凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 -AccountDetails.balance 就绪时,value 保存充值钱包,bonusWallets 保存赠送钱包;两个数组均保留十进制金额字符串和币种。查询失败不提供金额。 +attemptTimeoutMs 包含初始化、等待浏览器和兑换的耗时。初始化不会延长绝对截止时间;服务端 TTL 只能缩短剩余时间。在到期前已获准的凭证持久化不再取消。 + +账号更新共用一条有序流。凭据写入优先于待发送的进度快照;状态读取期间若凭据生命周期被替换,则丢弃该次读取。 ## 模型体验 @@ -67,11 +102,17 @@ AccountDetails.balance 就绪时,value 保存充值钱包,bonusWallets 保 -- 账号 token 没有过期或刷新流程。退出时先移除本地授权,再由提供者在后台撤销;远程退登失败不会恢复本地登录态。资料和余额查询失败保留已存储授权。getProfile / getBalance 分别报告资料和余额的查询结果。 +- 浏览器登录需要 Host webServer,仅支持通过带显式端口的 HTTP localhost、127.0.0.1 或 [::1] 本机访问及 SSH 本地转发,不支持非本机域名的反向代理。账号 token 没有过期或刷新流程;用户主动在 DSH 退出登录时,先删除本地授权,再在后台调用 POST /auth-api/v0/users/logout。远程失败不会恢复本地登录态。默认仅针对捕获的旧 token 最多额外重试五次,指数退避间隔为 1、2、4、8、16 秒;logoutMaxRetries(0–5)和 logoutRetryDelayMs 可配置该策略。每次请求使用 requestTimeoutMs。服务关闭时取消请求和等待,不持久化待撤销任务。本地凭证删除失败仍向调用者报错。签发 token 前的授权尝试仍有有效期。初始化后的取消或超时会在后台发送一次 POST /auth-api/v0/dsh/auth_cancel,携带 auth_init.biz_data 中的 authorize_id 和原始 code_verifier,不附带账号授权。本地取消不等待该请求,也不会因失败而恢复;requestTimeoutMs 限制请求时间,服务关闭时中止请求。TODO(product-error-ui):产品需定义已给定 biz code 的本地化文案和交互表现。在此之前,业务失败沿用现有“操作失败,请重试”兜底;其他 code 和 HTTP 错误也使用该兜底。开发授权不能认证生产请求。 ### 开发备注 [桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 -PlatformSession 可将仅限 Host 的 requestHeaders 从 Host 传至 Electron 主进程,其中只有部署请求头,因为内嵌文档的客户端身份在其语言、时区和版本可知处组装。消费者必须从渲染层 bootstrap 排除这些请求头,并将其限定于配置来源。userId 同样仅限 Host,绝不进入渲染层 bootstrap。mergePlatformCookies 替换同名 Cookie,同时保留其他 Cookie。 +登录后首次读取资料使用 auth_exchange 返回并经筛选的 user。user 为 null 或格式无效时回退到 current;后续刷新及 Host 重启也查询 current。current 请求失败时保留 Host 内存中同一凭证最近一次成功的资料;凭证变更或服务销毁时清空。current 成功返回的稳定账号 ID 首次可用或变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取 getPlatformSession;重复相同 ID 的刷新不通知。exchange 负责登记提交的设备信息。 + +accountRequestHeaders 覆盖 requestHeaders,供 current、余额以及内嵌 Platform 页面/API 请求使用。Cookie 按名称合并,路由覆盖保留其他部署 Cookie。授权初始化、兑换、取消和退登保持使用 requestHeaders。两组请求头仅供 Host 和 Electron 主进程使用;快照的 userId 同样仅限 Host,渲染层 bootstrap 仅接收 origin 和 token。 + +账号服务的 `embeddedPageDist` 配置为内嵌用量和充值页面 URL 添加 `dist` 查询参数。默认值为空;私有前端分支选择值应写在本地 profile patch 中。此配置不改变 API 地址或凭证传递方式。 + +Platform 钱包余额接受带可选科学计数法的十进制字符串(包括 `0E-16`),提供方保留原始字符串供调用方使用。 diff --git a/packages/credentials/deepseek-account-platform/locale/de.json b/packages/credentials/deepseek-account/locale/de.json similarity index 76% rename from packages/credentials/deepseek-account-platform/locale/de.json rename to packages/credentials/deepseek-account/locale/de.json index edd924d206..4fc42a20db 100644 --- a/packages/credentials/deepseek-account-platform/locale/de.json +++ b/packages/credentials/deepseek-account/locale/de.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek Kontoanmeldung", + "title": "DeepSeek-Konto", "description": "Schließen Sie die Anmeldeautorisierung für das DeepSeek-Konto über den Browser ab." } } diff --git a/packages/credentials/deepseek-account/locale/en.json b/packages/credentials/deepseek-account/locale/en.json new file mode 100644 index 0000000000..6a40638c62 --- /dev/null +++ b/packages/credentials/deepseek-account/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "DeepSeek account" + } +} diff --git a/packages/credentials/deepseek-account-platform/locale/es.json b/packages/credentials/deepseek-account/locale/es.json similarity index 71% rename from packages/credentials/deepseek-account-platform/locale/es.json rename to packages/credentials/deepseek-account/locale/es.json index e5ce28e7cd..18de04f7a0 100644 --- a/packages/credentials/deepseek-account-platform/locale/es.json +++ b/packages/credentials/deepseek-account/locale/es.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek inicio de sesión de cuenta", + "title": "Cuenta de DeepSeek", "description": "Complete la autorización de inicio de sesión de la cuenta DeepSeek a través del navegador." } } diff --git a/packages/credentials/deepseek-account-platform/locale/fr.json b/packages/credentials/deepseek-account/locale/fr.json similarity index 72% rename from packages/credentials/deepseek-account-platform/locale/fr.json rename to packages/credentials/deepseek-account/locale/fr.json index e472dc67ec..e443d00434 100644 --- a/packages/credentials/deepseek-account-platform/locale/fr.json +++ b/packages/credentials/deepseek-account/locale/fr.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek connexion au compte", + "title": "Compte DeepSeek", "description": "Complétez l'autorisation de connexion au compte DeepSeek via le navigateur." } } diff --git a/packages/credentials/deepseek-account-platform/locale/ja.json b/packages/credentials/deepseek-account/locale/ja.json similarity index 70% rename from packages/credentials/deepseek-account-platform/locale/ja.json rename to packages/credentials/deepseek-account/locale/ja.json index 1409b20137..e9ef24eaad 100644 --- a/packages/credentials/deepseek-account-platform/locale/ja.json +++ b/packages/credentials/deepseek-account/locale/ja.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek アカウントログイン", + "title": "DeepSeek アカウント", "description": "ブラウザで DeepSeek アカウントへのログイン認可を行います。" } } diff --git a/packages/credentials/deepseek-account-platform/locale/pt.json b/packages/credentials/deepseek-account/locale/pt.json similarity index 74% rename from packages/credentials/deepseek-account-platform/locale/pt.json rename to packages/credentials/deepseek-account/locale/pt.json index 2653ad2013..ed8f92bdd7 100644 --- a/packages/credentials/deepseek-account-platform/locale/pt.json +++ b/packages/credentials/deepseek-account/locale/pt.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek login da conta", + "title": "Conta DeepSeek", "description": "Conclua a autorização de login da conta DeepSeek através do navegador." } } diff --git a/packages/credentials/deepseek-account-platform/locale/ru.json b/packages/credentials/deepseek-account/locale/ru.json similarity index 75% rename from packages/credentials/deepseek-account-platform/locale/ru.json rename to packages/credentials/deepseek-account/locale/ru.json index 3d5fff9ff8..defd4481c6 100644 --- a/packages/credentials/deepseek-account-platform/locale/ru.json +++ b/packages/credentials/deepseek-account/locale/ru.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek вход в аккаунт", + "title": "Аккаунт DeepSeek", "description": "Завершите авторизацию входа в учетную запись DeepSeek через браузер." } } diff --git a/packages/credentials/deepseek-account-platform/locale/zh.json b/packages/credentials/deepseek-account/locale/zh.json similarity index 71% rename from packages/credentials/deepseek-account-platform/locale/zh.json rename to packages/credentials/deepseek-account/locale/zh.json index 86bbe95c12..65d9b31b58 100644 --- a/packages/credentials/deepseek-account-platform/locale/zh.json +++ b/packages/credentials/deepseek-account/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek 账号登录", + "title": "DeepSeek 账号", "description": "通过浏览器完成 DeepSeek 账号登录授权。" } } diff --git a/packages/credentials/deepseek-account/package.json b/packages/credentials/deepseek-account/package.json index 2a4d649a9f..088b4e8106 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/credentials/deepseek-account/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-deepseek-account", - "description": "Read account state and resolve official API credentials", + "description": "Sign in to DeepSeek and manage account credentials and notifications", "version": "0.2.2-rc.1", "publishConfig": { "access": "public" @@ -22,15 +22,34 @@ "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./client-metadata": { + "types": "./lib/types/client-metadata.d.ts", + "default": "./lib/types/client-metadata.js" + }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + } }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", "src" ], "license": "MIT", @@ -39,18 +58,30 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-util-values": "workspace:*" + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-util-values": "workspace:*" + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-agent": { "optional": true } + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~", + "zod": "4.6.6" } } diff --git a/packages/credentials/deepseek-account/src/client-metadata.ts b/packages/credentials/deepseek-account/src/client-metadata.ts new file mode 100644 index 0000000000..76583ca318 --- /dev/null +++ b/packages/credentials/deepseek-account/src/client-metadata.ts @@ -0,0 +1,56 @@ +/** Platform client identity headers and deployment cookies. */ +import type { AccountClientMetadata } from './types.ts' + +/** Merge Cookie header pairs by case-sensitive name, retaining unrelated cookies. + * @param base - existing request cookies. + * @param override - deployment cookies whose values take precedence. + * @returns one Cookie header with at most one pair per name. + */ +export function mergePlatformCookies(base: string, override: string): string { + const cookies = new Map() + for (const header of [base, override]) { + for (const pair of header.split(';')) { + const separator = pair.indexOf('=') + if (separator < 1) continue + cookies.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()) + } + } + return [...cookies].map(([name, value]) => `${name}=${value}`).join('; ') +} + +/** + * Identify native desktop API requests; null leaves non-desktop requests unchanged. + * @param platform - Operating system supplied by the desktop composition. + * @returns Platform request headers shared by account and update-policy clients. + */ +export function desktopClientHeaders(platform: 'darwin' | 'win32' | null): Record { + if (platform === null) return {} + return { 'x-client-platform': platform === 'win32' ? 'desktop-win' : 'desktop-mac' } +} + +/** + * Build the Platform client identity headers for one call. + * @param platform - Operating system supplied by the desktop composition; null identifies the client as web. + * @param client - identity of the requesting UI for this call. + * @returns the five client headers; the bundle ID is intentionally empty. + */ +export function platformClientHeaders(platform: 'darwin' | 'win32' | null, client: AccountClientMetadata): Record { + return { + 'x-client-bundle-id': '', + 'x-client-platform': 'web', + ...desktopClientHeaders(platform), + 'x-client-version': client.version, + 'x-client-locale': platformWireLocale(client.locale), + 'x-client-timezone-offset': String(client.timezoneOffsetSeconds), + } +} + +/** + * Reduce a caller's UI language to the region-tagged Platform locale. + * Shares one normalization with the header and with request body locale fields. + * @param locale - active UI language such as `zh-CN`, `zh_TW`, or `en-US`. + * @returns the region-tagged Platform locale for that language, `zh_CN` or `en_US`. + */ +export function platformWireLocale(locale: string): 'zh_CN' | 'en_US' { + return locale.toLowerCase().split(/[-_]/)[0] === 'zh' ? 'zh_CN' : 'en_US' +} diff --git a/packages/credentials/deepseek-account-platform/src/details.ts b/packages/credentials/deepseek-account/src/details.ts similarity index 53% rename from packages/credentials/deepseek-account-platform/src/details.ts rename to packages/credentials/deepseek-account/src/details.ts index d7c90b9ac3..e1dc0dec3f 100644 --- a/packages/credentials/deepseek-account-platform/src/details.ts +++ b/packages/credentials/deepseek-account/src/details.ts @@ -1,7 +1,7 @@ /** Platform Web profile and wallet queries projected for account UI consumers. */ import { z } from 'zod' -import type { AccountBonusNotification, AccountBonusOrderId, AccountDetails, AccountProfile, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import { AccountUnauthorizedError, PlatformAuthError, requestAccount, requestBonusNotified, requestUnnotifiedBonuses } from './protocol.ts' +import type { AccountDetails, AccountProfile, AccountUserId } from './types.ts' +import { AccountUnauthorizedError, PlatformAuthError, requestAccount } from './protocol.ts' const user = z.object({ id: z.string().nullish(), @@ -15,15 +15,6 @@ const wallet = z.object({ currency: z.enum(['CNY', 'USD']), balance: z.string().regex(decimal), }) const summary = z.object({ normal_wallets: z.array(wallet), bonus_wallets: z.array(wallet) }) -// Protocol responses are JSON-decoded; metadata keeps any JSON value without field validation. -const bonusMetadata = z.custom>().optional() -const bonus = z.object({ - campaign: bonusMetadata, amount: bonusMetadata, currency: bonusMetadata, granted_at: bonusMetadata, - order_id: z.string(), title: z.string().nullish().transform(value => value ?? undefined), expires_at: z.string().nullish().transform(value => value ?? ''), msg: z.string(), -}) -// The shared response reader already unwraps biz_data, so the payload is the bonus list itself. -const unnotified = z.array(bonus) - /** Project Platform user data without retaining credentials or unneeded fields. * @param value - current or exchange user response. * @returns UI account profile. @@ -43,7 +34,7 @@ function projectProfile(value: z.infer): AccountProfile { } } -function accountPayload(schema: z.ZodType, value: unknown, field: 'profile' | 'balance' | 'bonus'): T { +function accountPayload(schema: z.ZodType, value: unknown, field: 'profile' | 'balance'): T { const parsed = schema.safeParse(value) if (!parsed.success) { console.error(`[deepseek-account] ${field} schema rejected`, { @@ -70,7 +61,7 @@ const queries: { [K in keyof AccountDetails]: { /** * Read one Platform account field without waiting for the other query. * @param field - profile or recharge and bonus wallet balances. - * @param origin - configured origin matching the stored grant issuer. + * @param origin - configured account API origin. * @param token - stored authorization token; response tokens are discarded. * @param signal - request and credential lifetime. * @param headers - validated deployment headers for the configured origin. @@ -86,38 +77,3 @@ export async function readAccountDetail(field: K return { status: 'failed' } } } - -/** - * Read the unnotified bonus list for one captured credential. - * @param origin - configured origin matching the stored grant issuer. - * @param token - captured account grant; the caller has already bound it to the account. - * @param signal - credential lifetime and request timeout. - * @param headers - deployment and client identity headers for the configured origin. - * @returns notifications in Platform order; a malformed payload is a protocol failure. - */ -export async function readUnnotifiedBonuses(origin: string, token: string, - signal: AbortSignal, headers: Record): Promise { - const parsed = accountPayload(unnotified, await requestUnnotifiedBonuses(origin, token, signal, headers), 'bonus') - return parsed.map(row => ({ - ...(row.campaign === undefined ? {} : { campaign: row.campaign }), - ...(row.amount === undefined ? {} : { amount: row.amount }), - ...(row.currency === undefined ? {} : { currency: row.currency }), - ...(row.granted_at === undefined ? {} : { grantedAt: row.granted_at }), - orderId: row.order_id as AccountBonusOrderId, expiresAt: row.expires_at, message: row.msg, - ...(row.title === undefined ? {} : { title: row.title }), - })) -} - -/** - * Record one displayed bonus as notified with the credential it was read under. - * @param origin - configured origin matching the stored grant issuer. - * @param token - captured account grant; the caller has already bound it to the account. - * @param orderId - granted bonus order the user saw. - * @param signal - credential lifetime and request timeout. - * @param headers - deployment and client identity headers for the configured origin. - * @returns after Platform records the acknowledgement; HTTP and business failures throw. - */ -export async function sendBonusNotified(origin: string, token: string, orderId: AccountBonusOrderId, - signal: AbortSignal, headers: Record): Promise { - await requestBonusNotified(origin, token, orderId, signal, headers) -} diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/credentials/deepseek-account/src/index.ts index 20b0a8b81d..8dddec9074 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/credentials/deepseek-account/src/index.ts @@ -1,42 +1,222 @@ -/** Account Service Definition shared by platform, API, and model consumers. */ +/** DeepSeek account service; browser approval never bypasses local cancellation. */ +import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto' +import type { ServerResponse } from 'node:http' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { arch, platform, release } from 'node:os' +import { promises as streamPromises } from 'node:stream' import { Context, Service } from '@deepseek-ai/cordis' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountUserId, AccountView, SignInAttemptId } from './types.ts' -export type { AccountBonusBatch, AccountBonusNotification, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountProfile, AccountUserId, AccountWallet, AccountLinks, AccountView, SignInAttemptId, SignInAttemptView, SignInErrorCode } from './types.ts' -export { isRunningAccountTask, installAccountTaskCancellation } from './account-tasks.ts' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import Schema from '@deepseek-ai/schemastery' +import { z } from 'zod' +import { installAccountTaskCancellation, isRunningAccountTask } from './account-tasks.ts' +import { mergePlatformCookies, platformClientHeaders, platformWireLocale } from './client-metadata.ts' +import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' +import { profile, readAccountDetail } from './details.ts' +import { readNotificationContent, readNotifications, sendNotificationEvent } from './notifications.ts' +import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' +import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' + +export type * from './types.ts' declare module '@deepseek-ai/cordis' { + interface Context { deepseekAccount: DeepSeekAccount } interface Events { /** Local grant removal has completed. * @mode emit */ 'deepseek-account/signed-out'(): void } - interface Context { - deepseekAccount: DeepSeekAccount +} + + +const KEY = credentialKey('deepseek-account-platform', 'default') +const DEVICE = credentialKey('deepseek-account-platform', 'device') +const grant = z.object({ version: z.literal(1), token: z.string().min(1), issuer: z.url() }) +const device = z.object({ id: z.uuid() }) + +/** 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. */ + embeddedPageDist?: string + /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ + inferenceOrigin?: string + /** Allow HTTP only on loopback for the development Mock. */ + allowLoopbackHttp?: boolean + /** Map authorization and completion pages to platformOrigin for private development proxies. */ + rewriteBrowserOrigin?: boolean + /** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */ + requestHeaders?: Record + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ + accountRequestHeaders?: Record + /** Deadline for each platform HTTP request. */ + requestTimeoutMs?: number + /** Deadline for recharge-wallet queries; timeout returns a failed balance outcome. */ + balanceTimeoutMs?: number + /** Additional logout attempts after the first request fails, at most five. */ + logoutMaxRetries?: number + /** Delay before the first logout retry; each later delay doubles. */ + logoutRetryDelayMs?: number + /** Upper bound for the entire local attempt, even if the server advertises a longer TTL. */ + attemptTimeoutMs?: number +} +/** Validated deployment choices. */ +const Config = Schema.object({ + platformOrigin: Schema.string().default('https://platform.deepseek.com'), + harnessOrigin: Schema.string().default('https://harness.deepseek.com'), + desktopPlatform: Schema.union([Schema.const('darwin'), Schema.const('win32'), Schema.const(null)]).default(null), + embeddedPageDist: Schema.string().default(''), + inferenceOrigin: Schema.string().default('https://api.deepseek.com'), + allowLoopbackHttp: Schema.boolean().default(false), + rewriteBrowserOrigin: Schema.boolean().default(false), + requestHeaders: Schema.dict(Schema.string().role('secret')).default({}), + accountRequestHeaders: Schema.dict(Schema.string().role('secret')).default({}), + requestTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), + balanceTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), + logoutMaxRetries: Schema.number().min(0).max(5).step(1).default(5), + logoutRetryDelayMs: Schema.number().min(1).max(60_000).default(1_000), + attemptTimeoutMs: Schema.number().min(1).max(3_600_000).default(600_000), +}) + +interface Attempt { + locale: 'en_US' | 'zh_CN' + clientHeaders: Record + view: SignInAttemptView + controller: AbortController + done: Promise + running: Promise + origin: string + loginSource: 'web' | 'desktop' + disposeCallback?: () => Promise + callback?: ServerResponse + initialProfile?: { token: string; value: AccountDetails['profile'] } + completionUrl?: string +} + +/** Account login, credentials, and client-safe Remote operations. */ +export class DeepSeekAccount extends TypertRemoteService { + static inject = ['credentials', 'authorization'] + static Config = Config + private readonly origin: string + private readonly harnessOrigin: string + private readonly embeddedPageDist: string + private readonly inferenceOrigin: string + private readonly rewriteBrowserOrigin: boolean + private readonly platform: 'darwin' | 'win32' | null + private readonly requestHeaders: Record + private readonly accountRequestHeaders: Record + private readonly requestTimeout: number + private readonly balanceTimeout: number + private readonly attemptTimeout: number + private readonly logoutPolicy: LogoutRetryPolicy + private readonly logoutLifetime = new AbortController() + private readonly revocations = new Set>() + private attempt: Attempt | undefined + private readonly listeners = new Set<(kind: 'snapshot' | 'credentials-changed' | 'identity') => void>() + /** + * Latest ready profile read and the grant token it was read with. Binding the token keeps a + * cached identity from answering for a credential that has since changed. + */ + private lastProfile: { readonly token: string; readonly profile: Extract } | undefined + private detailsLifetime = new AbortController() + private closed = false + private removing: Promise | undefined + + /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ + constructor(ctx: Context, config: Config = {}) { + super(ctx, 'deepseekAccount', { namespace: 'account' }) + installAccountTaskCancellation(ctx) + const resolved = Config(config) + this.embeddedPageDist = resolved.embeddedPageDist + this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp, 'platformOrigin') + this.harnessOrigin = platformOrigin(resolved.harnessOrigin, resolved.allowLoopbackHttp, 'harnessOrigin') + const inference = new URL(resolved.inferenceOrigin) + if (!['http:', 'https:'].includes(inference.protocol) || inference.username || inference.password + || inference.pathname !== '/' || inference.search || inference.hash) { + throw new Error('account: inferenceOrigin must be an HTTP(S) origin without credentials, path, query or fragment') + } + this.inferenceOrigin = inference.origin + this.rewriteBrowserOrigin = resolved.rewriteBrowserOrigin + this.platform = resolved.desktopPlatform + this.requestHeaders = platformHeaders(resolved.requestHeaders) + const accountHeaders = platformHeaders(resolved.accountRequestHeaders) + this.accountRequestHeaders = { ...this.requestHeaders, ...accountHeaders } + if (accountHeaders.cookie !== undefined) { + this.accountRequestHeaders.cookie = mergePlatformCookies(this.requestHeaders.cookie ?? '', accountHeaders.cookie) + } + this.requestTimeout = resolved.requestTimeoutMs + this.balanceTimeout = resolved.balanceTimeoutMs + this.attemptTimeout = resolved.attemptTimeoutMs + this.logoutPolicy = { + maxRetries: resolved.logoutMaxRetries, delayMs: resolved.logoutRetryDelayMs, requestTimeoutMs: this.requestTimeout, + } + ctx.authorization.registerFlow({ + key: KEY, label: 'DeepSeek', methods: [{ id: 'browser', label: 'DeepSeek' }], + run: (session) => { + const attempt = this.attempt + if (attempt === undefined) return Promise.reject(new PlatformAuthError('protocol')) + attempt.running = this.run(session, attempt) + return attempt.running + }, + }) + ctx.on('credentials/record-updated', (key) => { + if (key !== KEY) return + this.invalidateDetails() + this.changed('credentials-changed') + }) + ctx.effect(() => async () => { + this.closed = true + this.logoutLifetime.abort() + this.invalidateDetails() + const active = this.attempt + if (active !== undefined) { + if (active.view.phase !== 'committing') active.controller.abort() + await active.done + } + await this.removing + await Promise.all(this.revocations) + this.changed('snapshot') + }, 'account: active attempt lifetime') } -} -/** Host-only credentials for an embedded Platform document; never expose through account RPC. */ -export interface PlatformSession { - readonly origin: string - readonly token: string - /** Stable issuer account ID from the last successful profile read; null requires disposable browser storage. */ - readonly userId: AccountUserId | null - /** Optional dist query value selecting the embedded frontend deployment. */ - readonly embeddedPageDist?: string - /** Host-only deployment request headers; the consuming client adds its own dynamic identity, and neither reaches renderer bootstrap. */ - readonly requestHeaders?: Readonly> -} + async [Service.init](): Promise { + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined) return + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + if (parsed.data.issuer === this.origin) return + await this.ctx.credentials.deleteRecord(KEY) + } -/** Account operations; only Host consumers can obtain a request credential. */ -export abstract class DeepSeekAccount extends Service { - /** @param ctx - context owning this account implementation. */ - constructor(ctx: Context) { super(ctx, 'deepseekAccount') } /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ - abstract getState(): Promise + @Remote + async getState(): Promise { + const record = await this.ctx.credentials.readRecord(KEY) + if (record !== undefined && (record.kind !== 'grant' || !grant.safeParse(record.payload).success)) { + throw new PlatformAuthError('storage') + } + const attempt = this.attempt?.view ?? null + return { + status: record === undefined ? 'signed-out' : 'credential-stored', + // Credential removal can notify watchers before sign-out finishes clearing the attempt. + attempt: record === undefined && attempt?.phase === 'succeeded' ? null : attempt, + links: { usageUrl: new URL('/usage', this.origin).href, topUpUrl: new URL('/top_up', this.origin).href }, + } + } + /** * Query Platform profile independently of wallet balances. * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch @@ -44,27 +224,251 @@ export abstract class DeepSeekAccount extends Service { * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ - abstract getProfile(client: AccountClientMetadata): Promise + @Remote + async getProfile(client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + const result = await this.getDetail('profile', this.detailHeaders(client), { lifetime, stored }) + if (this.detailsLifetime !== lifetime) return null + if (result !== null) this.cacheProfile(stored.token, result) + if (result?.status !== 'failed') return result + // Only this same grant's last ready read may stand in for a failed refresh. + const cached = this.lastProfile?.token === stored.token ? this.lastProfile.profile : undefined + return cached ?? result + } + /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ - abstract getBalance(client: AccountClientMetadata): Promise + @Remote + getBalance(client: AccountClientMetadata): Promise { + return this.getDetail('balance', this.detailHeaders(client)) + } + /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ - abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise + @Remote + async getNotifications(client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return null + try { + const batch = await readNotifications(this.harnessOrigin, stored.token, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime ? batch : null + } catch (error) { + if (this.detailsLifetime !== lifetime) return null + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return null + } + throw error + } + } + /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ - abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise + @Remote + async getNotificationContent(id: AccountNotificationId, + client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return null + try { + const content = await readNotificationContent(this.harnessOrigin, stored.token, id, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime ? content : null + } catch (error) { + if (this.detailsLifetime !== lifetime) return null + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return null + } + throw error + } + } + + /** + * 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 { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return false + try { + await sendNotificationEvent(this.harnessOrigin, stored.token, id, event, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime + } catch (error) { + if (this.detailsLifetime !== lifetime) return false + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return false + } + throw error + } + } + + /** + * Cache one ready profile against the grant token it was read with, so identity reuse cannot cross + * a credential change. A stable ID that first appears or changes notifies identity-enabled watch consumers, so + * identity consumers re-read getPlatformSession; repeated IDs stay silent. + * @param token - grant the profile was read with. + * @param profile - profile outcome to record when it carries account data. + */ + private cacheProfile(token: string, profile: AccountDetails['profile']): void { + if (profile.status !== 'ready') return + // Identity publishers re-read the session snapshot; wake them only when the stable ID changes. + const previous = this.lastProfile?.profile.value.id || null + this.lastProfile = { token, profile } + if (previous !== (profile.value.id || null)) this.changed('identity') + } + + private async getDetail(field: K, headers: Record, + captured?: { lifetime: AbortController; stored: z.infer }): Promise { + const lifetime = captured?.lifetime ?? this.detailsLifetime + const stored = captured?.stored ?? await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + if (field === 'profile' && this.attempt?.initialProfile?.token === stored.token) { + const initial = this.attempt.initialProfile.value + delete this.attempt.initialProfile + return initial as AccountDetails[K] + } + try { + const details = await readAccountDetail(field, this.origin, stored.token, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(field === 'balance' ? this.balanceTimeout : this.requestTimeout)]), headers) + return this.detailsLifetime !== lifetime ? null : details + } catch (_unauthorized) { + // readAccountDetail exposes only authenticated credential rejection failures. + if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) + return null + } + } + + /** Deployment account headers plus the client identity headers derived from one call's metadata. */ + private detailHeaders(client: AccountClientMetadata): Record { + return { ...this.accountRequestHeaders, ...platformClientHeaders(this.platform, client) } + } + + /** + * 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 { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored?.token !== token || this.detailsLifetime !== lifetime) return + await this.expireCredential(token, lifetime) + } + + private async expireCredential(token: string, lifetime: AbortController): Promise { + this.removing ??= (async () => { + if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) + const record = await this.ctx.credentials.readRecord(KEY) + if (this.closed || this.detailsLifetime !== lifetime || record?.kind !== 'grant') return this.getState() + const current = grant.parse(record.payload) + if (current.token !== token || current.issuer !== this.origin) return this.getState() + await this.ctx.credentials.deleteRecord(KEY) + this.ctx.emit('deepseek-account/session-expired') + this.attempt = undefined + this.ctx.emit('deepseek-account/signed-out') + this.changed('snapshot') + return this.getState() + })().finally(() => { this.removing = undefined }) + await this.removing + } + + /** + * 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 }> { + const [record, session] = await Promise.all([ + this.ctx.credentials.readRecord(DEVICE), + this.getPlatformSession(), + ]) + const parsed = record?.kind === 'grant' ? device.safeParse(record.payload) : undefined + return { + ...parsed?.success ? { deviceId: parsed.data.id } : {}, + ...session?.userId == null ? {} : { userId: session.userId }, + osVersion: deviceOsVersion(), + } + } + + /** + * 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 { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + // Deployment headers only; the consuming client adds the identity of its own UI. + const requestHeaders = { ...this.accountRequestHeaders } + // Identity comes from the profile read for this same grant; an unknown ID requires disposable + // browser storage. A replaced credential never publishes the account its predecessor named. + return { origin: this.origin, token: stored.token, + userId: this.lastProfile?.token === stored.token ? this.lastProfile.profile.value.id || null : null, + ...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}), + requestHeaders } + } + + private async readCurrentGrant(lifetime: AbortController): Promise | null> { + if (this.closed) return null + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined || lifetime.signal.aborted) return null + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + // A private origin override must never forward a grant issued by another environment. + if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') + return parsed.data + } + + /** + * 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 { + if (this.closed || this.removing !== undefined) return undefined + const destination = new URL(url) + if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined) return undefined + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const result = grant.safeParse(record.payload) + if (!result.success) throw new PlatformAuthError('storage') + // Development grants cannot authenticate production model or file requests. + const issuer = new URL(result.data.issuer) + if (result.data.token.startsWith('dsh_mock_')) return undefined + if (this.inferenceOrigin === 'https://api.deepseek.com') { + if (['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname)) return undefined + } else if (issuer.origin !== this.origin) return undefined + return result.data.token + } + /** * Join an active attempt or start browser authorization. * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. @@ -72,103 +476,346 @@ export abstract class DeepSeekAccount extends Service { * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ - abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + @Remote + async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { + if (this.removing !== undefined) await this.removing + const origin = loginOrigin(callbackOrigin) + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== undefined && ['initializing', 'waiting-browser', 'exchanging', 'committing'].includes(this.attempt.view.phase)) { + return this.getState() + } + const previous = this.attempt + if (previous !== undefined) { + await previous.done + // Disposal can close the provider while the previous attempt settles. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== previous) return this.getState() + } + const attempt: Attempt = { + origin, loginSource, + locale: platformWireLocale(client.locale), + clientHeaders: platformClientHeaders(this.platform, client), + view: { id: randomUUID() as SignInAttemptId, phase: 'initializing' }, + controller: new AbortController(), done: Promise.resolve(), running: Promise.resolve(), + } + this.attempt = attempt + attempt.done = this.ctx.authorization.begin({ + key: KEY, signal: attempt.controller.signal, + interaction: { notify: () => undefined, prompt: () => Promise.reject(new PlatformAuthError('protocol')) }, + }).then((outcome) => { + this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' }) + if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) { + attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end() + } else attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() + }).catch((error: unknown) => { + const code = error instanceof PlatformAuthError ? error.code : 'protocol' + console.error('[deepseek-account] sign-in failed', { errorCode: code }) + this.update(attempt, { phase: code === 'expired' ? 'expired' : 'failed', errorCode: code }) + this.finishFailedCallback(attempt) + }).then(async () => { + // begin() may report cancellation before the HTTP work observes its signal. + await attempt.running.catch(() => undefined) + if (attempt.callback !== undefined) { + await streamPromises.finished(attempt.callback, { cleanup: true }).catch(() => undefined) + } + await attempt.disposeCallback?.() + }) + this.changed('snapshot') + return this.getState() + } + /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ - abstract cancelSignIn(id: SignInAttemptId): Promise + @Remote + async cancelSignIn(attemptId: SignInAttemptId): Promise { + const attempt = this.attempt + if (attempt?.view.id === attemptId) { + if (attempt.view.phase !== 'committing') { + attempt.controller.abort() + this.ctx.authorization.cancel(KEY) + } + await attempt.done + } + return this.getState() + } + /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ - abstract signOut(client: AccountClientMetadata): Promise + @Remote + signOut(client: AccountClientMetadata): Promise { + this.removing ??= (async () => { + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) + const record = await this.ctx.credentials.readRecord(KEY) + if (record !== undefined) { + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') + await this.ctx.credentials.deleteRecord(KEY) + this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) + } + this.attempt = undefined + this.ctx.emit('deepseek-account/signed-out') + this.changed('snapshot') + return this.getState() + })().finally(() => { this.removing = undefined }) + return this.removing + } + /** - * 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 { + return this.ctx.get('agents')?.list().some(isRunningAccountTask) ?? false + } + + /** + * 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'> { + const lifetime = AbortSignal.any([signal, this.logoutLifetime.signal]) + let pending = 0 + let wake: (() => void) | undefined + const stop = this.ctx.on('deepseek-account/session-expired', () => { pending++; wake?.() }) + const abort = (): void => { wake?.() } + lifetime.addEventListener('abort', abort, { once: true }) + try { + while (!lifetime.aborted) { + if (pending > 0) { pending--; yield 'session-expired'; continue } + await new Promise((resolve) => { wake = resolve }) + } + } finally { + stop() + lifetime.removeEventListener('abort', abort) + } + } + + /** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ - abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable + watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable { + return this.observeUpdates(signal, includeIdentityChanges) + } + /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ - abstract resolveToken(url: string): Promise - /** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ - abstract rejectToken(token: string): Promise - /** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ - abstract getPlatformSession(): Promise - /** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ - abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + @Remote({ name: 'watch', mode: 'stream' }) + watchState(signal: AbortSignal): AsyncIterable { + return this.observeUpdates(signal, false) + } + + private async *observeUpdates(signal: AbortSignal, includeIdentityChanges: boolean): AsyncIterable { + let pending: AccountUpdate['type'] | undefined = 'snapshot' + let wake: (() => void) | undefined + const changed = (kind: 'snapshot' | 'credentials-changed' | 'identity'): void => { + if (kind === 'identity' && !includeIdentityChanges) return + if (kind === 'credentials-changed' || pending === undefined) { + pending = kind === 'credentials-changed' ? kind : 'snapshot' + } + wake?.() + } + const abort = (): void => { wake?.() } + this.listeners.add(changed) + signal.addEventListener('abort', abort, { once: true }) + try { + while (!this.closed && !signal.aborted) { + if (pending !== undefined) { + const type = pending + pending = undefined + const lifetime = this.detailsLifetime + const state = await this.getState() + // A credential write during the read owns the next event and its replacement state. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Abort or disposal can occur during the state read. + if (lifetime !== this.detailsLifetime || signal.aborted || this.closed) continue + yield { type, state } + continue + } + await new Promise((resolve) => { wake = resolve }) + } + } finally { + this.listeners.delete(changed) + signal.removeEventListener('abort', abort) + } + } + + private revoke(token: string, headers: Record): void { + if (this.closed) return + const revocation = revokeAccount(this.origin, token, this.logoutPolicy, + this.logoutLifetime.signal, { ...this.requestHeaders, ...headers }).finally(() => { this.revocations.delete(revocation) }) + this.revocations.add(revocation) + } + + private invalidateDetails(): void { + this.lastProfile = undefined + this.detailsLifetime.abort() + this.detailsLifetime = new AbortController() + } + + private changed(kind: 'snapshot' | 'credentials-changed' | 'identity'): void { + for (const listener of this.listeners) listener(kind) + } + + private update(attempt: Attempt, value: Partial): void { + const { authorizeUrl: _url, ...rest } = attempt.view + attempt.view = { ...rest, ...value } + this.changed('snapshot') + } + + private async run(session: AuthorizationSession, attempt: Attempt): Promise { + const webServer = this.ctx.get('webServer') + if (webServer === undefined) throw new PlatformAuthError('protocol') + const verifier = randomBytes(32).toString('base64url') + const state = randomBytes(32).toString('base64url') + const challenge = createHash('sha256').update(verifier).digest('base64url') + let authorizeId: string | undefined + const code = Promise.withResolvers() + // Callback requests may precede initialization settlement; the rejection is observed immediately. + void code.promise.catch(() => undefined) + const deadline = new AbortController() + let expiresAt = Date.now() + this.attemptTimeout + const signal = AbortSignal.any([session.signal, deadline.signal]) + let timer = setTimeout(() =>{ deadline.abort() }, this.attemptTimeout) + const abort = (): void => { code.reject(new PlatformAuthError('expired')) } + signal.addEventListener('abort', abort, { once: true }) + try { + attempt.disposeCallback = this.ctx.effect(() => webServer.register({ + kind: 'exact', path: '/oauth/callback', handler: (req, res) => { + let url: URL + try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } + catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } + const receivedCode = url.searchParams.get('code') + const receivedState = url.searchParams.get('state') ?? '' + const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) + && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) + if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || !validState || !receivedCode + || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { + res.writeHead(400, { 'cache-control': 'no-store' }).end(); return + } + if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { + res.writeHead(410, { 'cache-control': 'no-store' }).end(); return + } + attempt.callback = res + code.resolve(receivedCode) + }, + }), 'account: browser callback') + signal.throwIfAborted() + const redirectUri = `${attempt.origin}/oauth/callback` + const init = initialization.safeParse(await this.request('auth_init', { + code_challenge: challenge, code_challenge_method: 'S256', state, redirect_uri: redirectUri, locale: attempt.locale, + login_source: attempt.loginSource, + }, signal, attempt.clientHeaders), { reportInput: true }) + if (!init.success) this.rejectPayload('auth_init', init.error) + const authorizeUrl = browserUrl(init.data.authorize_url, this.origin, '/dsh/authorize', this.rewriteBrowserOrigin) + authorizeId = init.data.authorize_id + signal.throwIfAborted() + const now = Date.now() + expiresAt = Math.min(expiresAt, now + init.data.expires_in * 1000) + const remaining = expiresAt - now + if (remaining <= 0) { deadline.abort(); signal.throwIfAborted() } + clearTimeout(timer) + timer = setTimeout(() =>{ deadline.abort() }, remaining) + this.update(attempt, { phase: 'waiting-browser', authorizeUrl, expiresAt }) + const receivedCode = await code.promise + signal.throwIfAborted() + this.update(attempt, { phase: 'exchanging' }) + const deviceRecord = await this.ctx.credentials.modifyRecord(DEVICE, current => Promise.resolve(current === undefined + ? { kind: 'grant', payload: { id: randomUUID() } } : undefined)) + if (deviceRecord?.kind !== 'grant') throw new PlatformAuthError('storage') + const identity = device.parse(deviceRecord.payload) + const result = exchange.safeParse(await this.request('auth_exchange', { + code: receivedCode, code_verifier: verifier, redirect_uri: redirectUri, + device_id: identity.id, device_model: `${platform()}-${arch()}`, os_version: deviceOsVersion(), + }, signal, attempt.clientHeaders), { reportInput: true }) + if (!result.success) this.rejectPayload('auth_exchange', result.error) + const completionUrl = new URL(browserUrl(result.data.authorized_url, this.origin, '/dsh/authorized', this.rewriteBrowserOrigin)) + completionUrl.searchParams.set('login_source', attempt.loginSource) + attempt.completionUrl = completionUrl.href + if (Date.now() >= expiresAt) deadline.abort() + signal.throwIfAborted() + if (result.data.user != null) { + try { attempt.initialProfile = { token: result.data.token, value: { status: 'ready', value: profile(result.data.user) } } } + catch { + // Invalid optional user data falls back to current without discarding a valid authorization. + } + } + this.update(attempt, { phase: 'committing' }) + clearTimeout(timer) + try { await session.commit({ kind: 'grant', payload: { version: 1, token: result.data.token, issuer: this.origin } }) } + catch { throw new PlatformAuthError('storage') } + } catch (error) { + if (deadline.signal.aborted) throw new PlatformAuthError('expired') + throw error + } finally { + if (signal.aborted && authorizeId !== undefined) this.cancelRequest(authorizeId, verifier, attempt.clientHeaders) + clearTimeout(timer) + signal.removeEventListener('abort', abort) + // begin() settles the browser response and removes only this attempt’s route. + } + } + + private rejectPayload(stage: string, error: z.ZodError): never { + console.error('[deepseek-account] payload rejected', { + stage, issues: error.issues.map(issue => ({ + path: issue.path, code: issue.code, + receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input, + })), + }) + throw new PlatformAuthError('protocol') + } + + private cancelRequest(authorizeId: string, verifier: string, headers: Record): void { + if (this.closed) return + const cancellation = this.request('auth_cancel', { authorize_id: authorizeId, code_verifier: verifier }, + this.logoutLifetime.signal, headers).then(() => undefined, () => { + // Remote cancellation failures never reverse local cancellation or expose verifier diagnostics. + }).finally(() => { this.revocations.delete(cancellation) }) + this.revocations.add(cancellation) + } + + private request(method: string, body: unknown, signal: AbortSignal, headers: Record): Promise { + return requestPlatform(this.origin, method, body, + AbortSignal.any([signal, AbortSignal.timeout(this.requestTimeout)]), { ...this.requestHeaders, ...headers }) + } + + private finishFailedCallback(attempt: Attempt): void { + if (attempt.loginSource === 'web') { + const nonce = randomBytes(16).toString('base64url') + const message = attempt.locale === 'zh_CN' ? '登录失败,请关闭此标签页并在原页面重试。' + : 'Sign-in failed. Close this tab and try again in the original tab.' + attempt.callback?.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', + 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'`, + 'referrer-policy': 'no-referrer', + }).end(`${message}` + + `

    ${message}

    `) + } else { + // Native account subscribers focus the login window; retain the browser’s Platform document. + attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() + } + } } export default DeepSeekAccount - -/** Merge Cookie header pairs by case-sensitive name, retaining unrelated cookies. - * @param base - existing request cookies. - * @param override - deployment cookies whose values take precedence. - * @returns one Cookie header with at most one pair per name. - */ -export function mergePlatformCookies(base: string, override: string): string { - const cookies = new Map() - for (const header of [base, override]) { - for (const pair of header.split(';')) { - const separator = pair.indexOf('=') - if (separator < 1) continue - cookies.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()) - } - } - return [...cookies].map(([name, value]) => `${name}=${value}`).join('; ') -} - -/** - * Identify native desktop API requests; null leaves non-desktop requests unchanged. - * @param platform - Operating system supplied by the desktop composition. - * @returns Platform request headers shared by account and update-policy clients. - */ -export function desktopClientHeaders(platform: 'darwin' | 'win32' | null): Record { - if (platform === null) return {} - return { 'x-client-platform': platform === 'win32' ? 'desktop-win' : 'desktop-mac' } -} - -/** - * Build the Platform client identity headers for one call. - * @param platform - Operating system supplied by the desktop composition; null identifies the client as web. - * @param client - identity of the requesting UI for this call. - * @returns the five client headers; the bundle ID is intentionally empty. - */ -export function platformClientHeaders(platform: 'darwin' | 'win32' | null, client: AccountClientMetadata): Record { - return { - 'x-client-bundle-id': '', - 'x-client-platform': 'web', - ...desktopClientHeaders(platform), - 'x-client-version': client.version, - 'x-client-locale': platformWireLocale(client.locale), - 'x-client-timezone-offset': String(client.timezoneOffsetSeconds), - } -} - -/** - * Reduce a caller's UI language to the region-tagged Platform locale. - * Shares one normalization with the header and with request body locale fields. - * @param locale - active UI language such as `zh-CN`, `zh_TW`, or `en-US`. - * @returns the region-tagged Platform locale for that language, `zh_CN` or `en_US`. - */ -export function platformWireLocale(locale: string): 'zh_CN' | 'en_US' { - return locale.toLowerCase().split(/[-_]/)[0] === 'zh' ? 'zh_CN' : 'en_US' +/** OS identification shared by login and credential-free identity reads. */ +function deviceOsVersion(): string { + return `${platform()} ${release()}` } diff --git a/packages/credentials/deepseek-account-platform/src/logout.ts b/packages/credentials/deepseek-account/src/logout.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/src/logout.ts rename to packages/credentials/deepseek-account/src/logout.ts diff --git a/packages/credentials/deepseek-account/src/notifications.ts b/packages/credentials/deepseek-account/src/notifications.ts new file mode 100644 index 0000000000..c998137248 --- /dev/null +++ b/packages/credentials/deepseek-account/src/notifications.ts @@ -0,0 +1,98 @@ +/** Validated, localized notification queries through the account API. */ +import { z } from 'zod' +import type { AccountNotification, AccountNotificationBatch, AccountNotificationEvent, AccountNotificationId } from './types.ts' +import { PlatformAuthError, requestNotificationContent, requestNotificationEvent, requestNotifications } from './protocol.ts' + +const action = z.object({ + label: z.string(), + style: z.enum(['primary', 'secondary']), + target: z.discriminatedUnion('type', [ + z.object({ type: z.literal('app_route'), name: z.literal('account') }), + z.object({ type: z.literal('dismiss') }), + ]), +}) +// The HTTP reader supplies JSON values; business data has no notification-specific fields. +const notification = z.object({ + id: z.string(), created_at: z.iso.datetime({ offset: true }), + display_until: z.iso.datetime({ offset: true }).nullable(), + title: z.string(), body: z.string(), actions: z.array(action), data: z.json().optional(), +}) +const list = z.object({ + next_poll_after: z.number().positive().max(2_147_483_647 / 1_000), + notifications: z.array(z.unknown()), +}) + +function project(value: z.infer): AccountNotification { + return { + id: value.id as AccountNotificationId, createdAt: value.created_at, + displayUntil: value.display_until, title: value.title, body: value.body, actions: value.actions, + ...(value.data === undefined ? {} : { data: value.data }), + } +} + +function parse(schema: z.ZodType, value: unknown): T { + const parsed = schema.safeParse(value) + if (!parsed.success) { + console.error('[deepseek-account] notification schema rejected', { + issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })), + }) + throw new PlatformAuthError('protocol') + } + return parsed.data +} + +/** + * Read unconsumed notifications for one captured account credential. + * @param origin - configured account API origin. + * @param token - captured account grant. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns supported notifications in server order and the next query delay in seconds; malformed entries are skipped, + * while HTTP and list-envelope failures reject. + */ +export async function readNotifications(origin: string, token: string, + signal: AbortSignal, headers: Record): Promise { + const value = parse(list, await requestNotifications(origin, token, signal, headers)) + const notifications = value.notifications.flatMap((entry, index) => { + const parsed = notification.safeParse(entry) + if (!parsed.success) { + console.error('[deepseek-account] skipping unsupported notification', { + index, issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })), + }) + return [] + } + return [project(parsed.data)] + }) + return { nextPollAfterSeconds: value.next_poll_after, notifications } +} + +/** + * Read localized content without changing notification consumption. + * @param origin - configured account API origin. + * @param token - captured token for this request's credential lifetime. + * @param id - notification whose content is requested. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns content with the requested identity; mismatched IDs and malformed responses reject. + */ +export async function readNotificationContent(origin: string, token: string, id: AccountNotificationId, + signal: AbortSignal, headers: Record): Promise { + const value = parse(notification, await requestNotificationContent(origin, token, id, signal, headers)) + if (value.id !== id) throw new PlatformAuthError('protocol') + return project(value) +} + +/** + * Report an interaction; the response's consumption decision never closes the local card. + * @param origin - configured account API origin. + * @param token - captured token for this request's credential lifetime. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns after the server accepts the event; HTTP and malformed responses reject. + */ +export async function sendNotificationEvent(origin: string, token: string, id: AccountNotificationId, + event: AccountNotificationEvent, signal: AbortSignal, headers: Record): Promise { + parse(z.object({ acked: z.boolean() }), await requestNotificationEvent(origin, token, id, event, signal, headers)) +} diff --git a/packages/credentials/deepseek-account-platform/src/protocol.ts b/packages/credentials/deepseek-account/src/protocol.ts similarity index 84% rename from packages/credentials/deepseek-account-platform/src/protocol.ts rename to packages/credentials/deepseek-account/src/protocol.ts index 54d1afd9ad..b7a6a234a6 100644 --- a/packages/credentials/deepseek-account-platform/src/protocol.ts +++ b/packages/credentials/deepseek-account/src/protocol.ts @@ -1,6 +1,6 @@ /** Validated platform HTTP messages and restricted browser destinations. */ import { z } from 'zod' -import type { AccountBonusOrderId, SignInErrorCode } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountNotificationEvent, AccountNotificationId, SignInErrorCode } from './types.ts' /** Protocol errors expose a stable code, never a response body or authorization URL. */ export class PlatformAuthError extends Error { @@ -17,14 +17,16 @@ export class AccountUnauthorizedError extends PlatformAuthError { * Accept HTTPS platform endpoints, or explicitly configured loopback development HTTP. * @param value - configured origin. * @param allowLoopbackHttp - development-only opt-in. + * @param field - configuration field named in validation errors. * @returns normalized origin. */ -export function platformOrigin(value: string, allowLoopbackHttp: boolean): string { +export function platformOrigin(value: string, allowLoopbackHttp: boolean, + field: 'platformOrigin' | 'harnessOrigin'): string { const url = new URL(value) const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) if (url.username || url.password || url.pathname !== '/' || url.search || url.hash || !(url.protocol === 'https:' || (allowLoopbackHttp && loopback && url.protocol === 'http:'))) { - throw new Error('account: platformOrigin must be an HTTPS origin or explicitly enabled loopback HTTP origin') + throw new Error(`account: ${field} must be an HTTPS origin or explicitly enabled loopback HTTP origin`) } return url.origin } @@ -113,33 +115,49 @@ export function requestAccount(origin: string, path: '/auth-api/v0/users/current } /** - * Read the granted bonuses Platform has not yet recorded as displayed. - * @param origin - configured origin matching the grant issuer. + * Read unconsumed account notifications in server order. + * @param origin - configured account API origin. * @param token - stored account grant. * @param signal - credential lifetime and request timeout. * @param headers - deployment and client identity headers for this origin. - * @returns successful business payload holding the unnotified bonus list. + * @returns successful business payload holding the notification list. */ -export function requestUnnotifiedBonuses(origin: string, token: string, +export function requestNotifications(origin: string, token: string, signal: AbortSignal, headers: Record): Promise { - return platformRequest(`${origin}/api/v0/users/get_unnotified_bonuses`, + return platformRequest(`${origin}/api/v0/users/notifications/list`, { method: 'GET', headers: accountHeaders(headers, token) }, signal) } /** - * Acknowledge an actually displayed bonus to Platform. - * @param origin - configured origin matching the grant issuer. + * Read localized notification content, including a consumed notification. + * @param origin - configured account API origin. * @param token - stored account grant. - * @param orderId - granted bonus order the user saw. + * @param id - notification requested by its owning account. * @param signal - credential lifetime and request timeout. * @param headers - deployment and client identity headers for this origin. - * @returns successful business payload, which carries no data. + * @returns successful business payload containing one notification. */ -export function requestBonusNotified(origin: string, token: string, orderId: AccountBonusOrderId, +export function requestNotificationContent(origin: string, token: string, id: AccountNotificationId, signal: AbortSignal, headers: Record): Promise { - return platformRequest(`${origin}/api/v0/users/ack_bonus_notified`, { + return platformRequest(`${origin}/api/v0/users/notifications/content?id=${encodeURIComponent(id)}`, + { method: 'GET', headers: accountHeaders(headers, token) }, signal) +} + +/** + * Report an account notification interaction to the events endpoint. + * @param origin - configured account API origin. + * @param token - stored account grant. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers for this origin. + * @returns successful business payload containing the consumption decision. + */ +export function requestNotificationEvent(origin: string, token: string, id: AccountNotificationId, + event: AccountNotificationEvent, signal: AbortSignal, headers: Record): Promise { + return platformRequest(`${origin}/api/v0/users/notifications/events`, { method: 'POST', headers: { ...accountHeaders(headers, token), 'content-type': 'application/json' }, - body: JSON.stringify({ order_id: orderId }), + body: JSON.stringify({ notification_id: id, type: event }), }, signal) } @@ -150,7 +168,7 @@ function accountHeaders(headers: Record, token: string): Record< /** * End the Platform session using its existing logout endpoint. - * @param origin - configured origin matching the grant issuer. + * @param origin - configured account API origin. * @param token - stored account token. * @param signal - logout request deadline. * @param headers - validated deployment headers for this origin. diff --git a/packages/credentials/deepseek-account/src/types.ts b/packages/credentials/deepseek-account/src/types.ts index 39f1f086fb..5ccd36303b 100644 --- a/packages/credentials/deepseek-account/src/types.ts +++ b/packages/credentials/deepseek-account/src/types.ts @@ -41,6 +41,13 @@ export interface AccountView { readonly attempt: SignInAttemptView | null } +/** Ordered account stream item; every item carries the latest safe state. */ +export interface AccountUpdate { + /** Initial state and progress use snapshot; credential writes and removal use credentials-changed. */ + readonly type: 'snapshot' | 'credentials-changed' + readonly state: AccountView +} + /** Platform account identifier supplied by the current-user endpoint. */ export type AccountUserId = Branded<'AccountUserId'> /** Display identity; contacts retain Platform masking. */ @@ -62,27 +69,33 @@ export interface AccountDetails { readonly balance: { readonly status: 'ready'; readonly value: readonly AccountWallet[]; readonly bonusWallets: readonly AccountWallet[] } | { readonly status: 'failed' } } -/** Identity of one granted bonus order; stable across devices and sign-ins. */ -export type AccountBonusOrderId = Branded<'AccountBonusOrderId'> -/** One granted bonus Platform has not yet recorded as displayed; copy is server-authored. */ -export interface AccountBonusNotification { - /** Server-localized plain-text title; absent responses use the localized bonus title. */ - readonly title?: string - readonly orderId: AccountBonusOrderId - /** Optional Platform metadata, forwarded without validation. */ - readonly campaign?: JsonValue - readonly amount?: JsonValue - readonly currency?: JsonValue - readonly grantedAt?: JsonValue - /** Platform expiry timestamp; an empty string means the notice never expires. */ - readonly expiresAt: string - /** Server-localized plain text ready for display. */ - readonly message: string +/** Opaque string notification identity; stable across devices, sign-ins, and languages. */ +export type AccountNotificationId = Branded<'AccountNotificationId'> +/** Presentation, any non-dismiss action click, or explicit dismissal; independent of backend consumption. */ +export type AccountNotificationEvent = 'displayed' | 'cta_clicked' | 'dismissed' +/** Client action supported by the account notification presentation. */ +export interface AccountNotificationAction { + readonly label: string + readonly style: 'primary' | 'secondary' + readonly target: { readonly type: 'app_route'; readonly name: 'account' } | { readonly type: 'dismiss' } } -/** Unnotified bonuses with the account they belong to, in Platform order. */ -export interface AccountBonusBatch { - readonly accountId: AccountUserId - readonly bonuses: readonly AccountBonusNotification[] +/** One account notification with server-localized plain text and actions. */ +export interface AccountNotification { + readonly id: AccountNotificationId + readonly createdAt: string + /** Display deadline; null means the notification never expires. */ + readonly displayUntil: string | null + readonly title: string + readonly body: string + readonly actions: readonly AccountNotificationAction[] + /** Optional business data, retained independently of the localized copy. */ + readonly data?: JsonValue +} +/** Unconsumed notifications in server order, without account-profile data. */ +export interface AccountNotificationBatch { + /** Positive delay in seconds before querying again, within the browser timer range. */ + readonly nextPollAfterSeconds: number + readonly notifications: readonly AccountNotification[] } declare module '@deepseek-ai/cordis' { @@ -97,3 +110,15 @@ declare module '@deepseek-ai/cordis' { 'deepseek-account/model-sign-in-required'(): void } } + +/** Host-only credentials for an embedded Platform document; never expose through account RPC. */ +export interface PlatformSession { + readonly origin: string + readonly token: string + /** Stable issuer account ID from the last successful profile read; null requires disposable browser storage. */ + readonly userId: AccountUserId | null + /** Optional dist query value selecting the embedded frontend deployment. */ + readonly embeddedPageDist?: string + /** Host-only deployment request headers; the consuming client adds its own dynamic identity, and neither reaches renderer bootstrap. */ + readonly requestHeaders?: Readonly> +} diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account/tests/account.spec.ts similarity index 98% rename from packages/credentials/deepseek-account-platform/tests/account.spec.ts rename to packages/credentials/deepseek-account/tests/account.spec.ts index 590fb0b7be..267616dab3 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account/tests/account.spec.ts @@ -11,7 +11,7 @@ import AuthorizationService from '@deepseek-ai/dsh-authorization' import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' import { credentialKey, credentialRef } from '@deepseek-ai/dsh-credentials' -import { Config, PlatformAccount } from '../src/index.ts' +import { DeepSeekAccount } from '../src/index.ts' import { browserUrl, platformHeaders, platformOrigin, loginOrigin } from '../src/protocol.ts' const cleanups: Array<() => Promise> = [] @@ -157,18 +157,18 @@ async function fixture( const authorization = ctx.plugin(AuthorizationService) await authorization await beforeAccount?.(ctx, origin) - const provider = ctx.plugin(PlatformAccount, { + const provider = ctx.plugin(DeepSeekAccount, { platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform, allowLoopbackHttp: true, requestHeaders, accountRequestHeaders, rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, }) await provider cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() }) - const account = ctx.deepseekAccount as PlatformAccount + const account = ctx.deepseekAccount const states = new AbortController() cleanups.push(async () => { states.abort() }) async function wait(phase: string) { - for await (const state of account.watch(states.signal)) if (state.attempt?.phase === phase) return state + for await (const { state } of account.watch(states.signal)) if (state.attempt?.phase === phase) return state throw new Error(`missing phase ${phase}`) } return { cancellations, cancellationReceived, holdCancel: () => { holdCancel = true }, @@ -307,9 +307,9 @@ it('allows real account credentials only on the exact official HTTPS origin', as }) it('restricts platform destinations to the configured origin and route', () => { - expect(() => platformOrigin('http://localhost:8081', false)).toThrow() - expect(platformOrigin('http://localhost:8081', true)).toBe('http://localhost:8081') - expect(() => platformOrigin('http://example.com', true)).toThrow() + expect(() => platformOrigin('http://localhost:8081', false, 'platformOrigin')).toThrow() + expect(platformOrigin('http://localhost:8081', true, 'platformOrigin')).toBe('http://localhost:8081') + expect(() => platformOrigin('http://example.com', true, 'platformOrigin')).toThrow() expect(() => browserUrl('https://evil.test/dsh/authorized', 'https://platform.deepseek.com', '/dsh/authorized')).toThrow() expect(() => browserUrl('https://platform.deepseek.com/other', 'https://platform.deepseek.com', '/dsh/authorized')).toThrow() }) @@ -719,7 +719,7 @@ it('never exports an embedded Platform token to a different configured issuer', await expect(f.account.getPlatformSession()).rejects.toThrow() }) -async function readDetails(account: Pick) { +async function readDetails(account: Pick) { const [profile, balance] = await Promise.all([account.getProfile(clientMetadata()), account.getBalance(clientMetadata())]) return profile === null || balance === null ? null : { profile, balance } } @@ -958,7 +958,7 @@ it('derives the client headers independently for profile, balance, and logout ca it('rejects unsupported native desktop platforms in configuration', () => { // @ts-expect-error Configuration files can name unsupported operating systems. - expect(() => Config({ desktopPlatform: 'linux' })).toThrow() + expect(() => DeepSeekAccount.Config({ desktopPlatform: 'linux' })).toThrow() }) it('retains successful profile data on current failure only for the same credential', async () => { @@ -1153,7 +1153,7 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con it.each(['ftp://api.example', 'https://user:password@api.example', 'https://api.example/path', 'https://api.example/?query=1', 'https://api.example/#fragment'])('rejects invalid inference origin %s', async (inferenceOrigin) => { - expect(() => new PlatformAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin') + expect(() => new DeepSeekAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin') }) it('rejects authorization begun without a local account attempt', async () => { @@ -1451,9 +1451,9 @@ it.each([false, true])('notifies only identity-enabled watchers on profile ident await storeAccount(f) expect(await f.account.getProfile(clientMetadata())).toEqual({ status: 'failed' }) const lifetime = new AbortController() - const states: Awaited>[] = [] + const states: Awaited>[] = [] const watching = (async () => { - for await (const state of f.account.watch(lifetime.signal, includeIdentityChanges)) states.push(state) + for await (const { state } of f.account.watch(lifetime.signal, includeIdentityChanges)) states.push(state) })() try { await expect.poll(() => states.length).toBe(1) diff --git a/packages/credentials/deepseek-account-platform/tests/authorization-response.spec.ts b/packages/credentials/deepseek-account/tests/authorization-response.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/authorization-response.spec.ts rename to packages/credentials/deepseek-account/tests/authorization-response.spec.ts diff --git a/packages/credentials/deepseek-account/tests/client-headers.spec.ts b/packages/credentials/deepseek-account/tests/client-headers.spec.ts index d46d936e44..c346aec13c 100644 --- a/packages/credentials/deepseek-account/tests/client-headers.spec.ts +++ b/packages/credentials/deepseek-account/tests/client-headers.spec.ts @@ -1,6 +1,6 @@ /** Platform client identity headers derived from one call's metadata. */ import { expect, it } from 'vitest' -import { platformClientHeaders } from '../src/index.ts' +import { platformClientHeaders } from '../src/client-metadata.ts' it.each([ ['darwin', 'desktop-mac'], ['win32', 'desktop-win'], [null, 'web'], diff --git a/packages/credentials/deepseek-account-platform/tests/details.spec.ts b/packages/credentials/deepseek-account/tests/details.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/details.spec.ts rename to packages/credentials/deepseek-account/tests/details.spec.ts diff --git a/packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts b/packages/credentials/deepseek-account/tests/diagnostics.spec.ts similarity index 92% rename from packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts rename to packages/credentials/deepseek-account/tests/diagnostics.spec.ts index fe2a60b14d..935eb27d5a 100644 --- a/packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts +++ b/packages/credentials/deepseek-account/tests/diagnostics.spec.ts @@ -1,7 +1,8 @@ import { expect, it, vi } from 'vitest' -import { browserUrl, logoutAccount, requestAccount, requestBonusNotified, requestPlatform, requestUnnotifiedBonuses } from '../src/protocol.ts' -import type { AccountBonusOrderId } from '@deepseek-ai/dsh-deepseek-account/types' -import { readAccountDetail, readUnnotifiedBonuses } from '../src/details.ts' +import { browserUrl, logoutAccount, requestAccount, requestNotificationEvent, requestPlatform, requestNotifications } from '../src/protocol.ts' +import type { AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' +import { readAccountDetail } from '../src/details.ts' +import { readNotifications } from '../src/notifications.ts' it.each(['/dsh/authorize', '/dsh/authorized'])('maps %s to the configured development origin and preserves query bytes', (path) => { const origin = 'http://localhost:8081' @@ -133,8 +134,8 @@ it('keeps successful authorization, account, bonus and logout requests silent', for (const path of ['/auth-api/v0/users/current', '/api/v0/users/get_user_summary'] as const) { await requestAccount(origin, path, 'private-token', signal, {}) } - await requestUnnotifiedBonuses(origin, 'private-token', signal, {}) - await requestBonusNotified(origin, 'private-token', 'fixture-order' as AccountBonusOrderId, signal, {}) + await requestNotifications(origin, 'private-token', signal, {}) + await requestNotificationEvent(origin, 'private-token', 'fixture-order' as AccountNotificationId, 'displayed', signal, {}) await logoutAccount(origin, 'private-token', signal, {}) fetcher.mockResolvedValueOnce(new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { email: 'private-email' } }, @@ -174,16 +175,16 @@ it.each([ }) -it('reports invalid bonus fields without logging bonus data', async () => { +it('reports skipped notification fields without logging notification data', async () => { const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ - code: 0, data: { biz_code: 0, biz_data: [{ order_id: 42, msg: 'private-message' }] }, + code: 0, data: { biz_code: 0, biz_data: { next_poll_after: 600, notifications: [{ id: 42, body: 'private-message' }] } }, }))) try { - await expect(readUnnotifiedBonuses('https://platform.deepseek.com', 'private-token', - new AbortController().signal, {})).rejects.toThrow('account: protocol') - expect(output.mock.calls[0]?.[0]).toBe('[deepseek-account] bonus schema rejected') - expect(JSON.stringify(output.mock.calls)).toContain('order_id') + await expect(readNotifications('https://platform.deepseek.com', 'private-token', + new AbortController().signal, {})).resolves.toEqual({ nextPollAfterSeconds: 600, notifications: [] }) + expect(output.mock.calls[0]?.[0]).toBe('[deepseek-account] skipping unsupported notification') + expect(JSON.stringify(output.mock.calls)).toContain('id') expect(JSON.stringify(output.mock.calls)).not.toContain('private-') } finally { fetcher.mockRestore() diff --git a/packages/credentials/deepseek-account-platform/tests/expected/web-exchange-failure.txt b/packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/expected/web-exchange-failure.txt rename to packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt diff --git a/packages/credentials/deepseek-account-platform/tests/logout.spec.ts b/packages/credentials/deepseek-account/tests/logout.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/logout.spec.ts rename to packages/credentials/deepseek-account/tests/logout.spec.ts diff --git a/packages/credentials/deepseek-account/tests/notifications.spec.ts b/packages/credentials/deepseek-account/tests/notifications.spec.ts new file mode 100644 index 0000000000..5f0edf8067 --- /dev/null +++ b/packages/credentials/deepseek-account/tests/notifications.spec.ts @@ -0,0 +1,630 @@ +/** Bonus notification reads and acknowledgements over the real Host HTTP path. */ +import { afterEach, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' +import { Context } from '@deepseek-ai/cordis' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AccountNotificationBatch, AccountNotificationId, AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import { DeepSeekAccount } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) + +const ORDER = '4c1b0000-0000-4000-8000-000000000000' +const SECOND_ORDER = '5d2c0000-0000-4000-8000-000000000000' +const USER = 'test-user' + +/** Client identity supplied with each account operation; only the locale's primary subtag selects the wire locale. */ +const clientMetadata = (locale = 'en-US'): AccountClientMetadata => ({ version: '1.2.3', locale, timezoneOffsetSeconds: 28_800 }) + +interface Recorded { + readonly method: string | undefined + readonly url: string | undefined + readonly token: string | undefined + readonly locale: string | undefined + readonly bundleId: string | undefined + readonly platform: string | undefined + readonly version: string | undefined + readonly timezoneOffset: string | undefined + readonly contentType: string | undefined + readonly body: string | undefined +} + +/** Read one request body; the acknowledgement carries its order id in JSON, so the fixture keeps the exact bytes. */ +function requestBody(req: IncomingMessage): Promise { + return new Promise((resolve, reject) => { + let body = '' + req.setEncoding('utf8') + req.on('data', (chunk: string) => { body += chunk }) + req.on('error', reject) + req.on('end', () => { resolve(body) }) + }) +} + +/** @param id - opaque notification ID. @param fields - wire fields overridden by the scenario. @returns a complete notification. */ +function wire(id: string, fields: Record = {}) { + return { id, created_at: '2026-10-21T08:00:00Z', display_until: null, + title: 'Product news', body: 'New features are available.', actions: [], ...fields } +} + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), 'dsh-bonus-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const requests: Recorded[] = [] + let profileId: string | null = USER + let profileBizCode = 0 + let profileStatus = 200 + let bonusBizCode = 0 + let bonusStatus = 200 + let nextPollAfter: unknown = 300 + let bonuses: unknown = [wire(ORDER), wire(SECOND_ORDER)] + let content: unknown = wire(ORDER) + let contentStatus = 200 + let contentBizCode = 0 + let beforeListResponse: (() => Promise) | undefined + let beforeEventResponse: (() => Promise) | undefined + let acked = true + let beforeContentResponse: (() => Promise) | undefined + let ackBizCode = 0 + let ackStatus = 200 + let beforeProfileResponse: (() => Promise) | undefined + let origin = '' + const handle = async (req: IncomingMessage, res: ServerResponse): Promise => { + expect(req.headers.authorization).toBeUndefined() + const body = await requestBody(req) + requests.push({ method: req.method, url: req.url, token: req.headers['x-dsh-auth-token'] as string | undefined, + locale: req.headers['x-client-locale'] as string | undefined, + bundleId: req.headers['x-client-bundle-id'] as string | undefined, + platform: req.headers['x-client-platform'] as string | undefined, + version: req.headers['x-client-version'] as string | undefined, + timezoneOffset: req.headers['x-client-timezone-offset'] as string | undefined, + contentType: req.headers['content-type'], body: body === '' ? undefined : body }) + res.setHeader('content-type', 'application/json') + if (req.url === '/auth-api/v0/users/current') { + await beforeProfileResponse?.() + res.writeHead(profileStatus).end(JSON.stringify({ code: profileStatus === 200 ? 0 : 1, data: { biz_code: profileBizCode, + biz_data: { id: profileId, email: 't***@example.invalid', id_profile: { name: 'Test', picture: null } } } })) + return + } + if (req.url === '/api/v0/users/notifications/list') { + await beforeListResponse?.() + res.writeHead(bonusStatus).end(JSON.stringify({ code: bonusStatus === 200 ? 0 : 1, + data: { biz_code: bonusBizCode, biz_data: { next_poll_after: nextPollAfter, notifications: bonuses } } })) + return + } + if (req.url?.startsWith('/api/v0/users/notifications/content?')) { + await beforeContentResponse?.() + res.writeHead(contentStatus).end(JSON.stringify({ code: contentStatus === 200 ? 0 : 1, + data: { biz_code: contentBizCode, biz_data: content } })) + return + } + // The exact path is the assertion: a query parameter would fall through to the 404 below. + if (req.url === '/api/v0/users/notifications/events') { + await beforeEventResponse?.() + res.writeHead(ackStatus).end(JSON.stringify(ackStatus === 200 + ? { code: 0, msg: '', data: { biz_code: ackBizCode, biz_msg: ackBizCode === 0 ? '' : 'NOTIFICATION_NOT_FOUND', biz_data: { acked } } } + : { code: 1, msg: 'INTERNAL', data: null })) + return + } + res.writeHead(404).end('{}') + } + const server = createServer((req, res) => { void handle(req, res).catch(() => { res.writeHead(500).end('{}') }) }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (!address || typeof address === 'string') throw new Error('missing listener') + origin = `http://127.0.0.1:${address.port}` + cleanups.push(async () => { + await new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }) + }) + const ctx = new Context() + const credentials = ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await credentials + const authorization = ctx.plugin(AuthorizationService) + await authorization + // The composed client identity is this fixture's choice; `null` is the web profile's documented setting. + const provider = ctx.plugin(DeepSeekAccount, { + platformOrigin: origin, harnessOrigin: origin, allowLoopbackHttp: true, requestTimeoutMs: 5_000, desktopPlatform: null, + }) + await provider + cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose() }) + const key = credentialKey('deepseek-account-platform', 'default') + return { + account: ctx.deepseekAccount, ctx, requests, key, + grant: async (token: string) => { + await ctx.credentials.modifyRecord(key, () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token, issuer: origin }, + })) + }, + signOut: async () => { + await ctx.credentials.deleteRecord(key) + }, + profileId: (value: string | null) => { profileId = value }, + failProfile: (bizCode = 17, status = 200) => { profileBizCode = bizCode; profileStatus = status }, + nextPollAfter: (value: unknown) => { nextPollAfter = value }, + notifications: (value: unknown) => { bonuses = value }, + content: (value: unknown) => { content = value }, + failContent: (bizCode = 0, status = 200) => { contentBizCode = bizCode; contentStatus = status }, + onContent: (hook: () => Promise) => { beforeContentResponse = hook }, + failBonuses: (bizCode = 17, status = 200) => { bonusBizCode = bizCode; bonusStatus = status }, + failAck: (bizCode = 0, status = 200) => { ackBizCode = bizCode; ackStatus = status }, + onList: (hook: () => Promise) => { beforeListResponse = hook }, + onEvent: (hook: () => Promise) => { beforeEventResponse = hook }, + acknowledged: (value: boolean) => { acked = value }, + onProfile: (hook: () => Promise) => { beforeProfileResponse = hook }, + } +} + +it('sends client identity headers on notification requests without a profile preflight', async () => { + const f = await fixture() + await f.grant('test-account-token') + const client = { version: '3.0.0', locale: 'zh-TW', timezoneOffsetSeconds: -18_000 } + await f.account.getNotifications(client) + await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', client) + expect(f.requests.map(request => [ + request.url, request.bundleId, request.platform, request.version, request.locale, request.timezoneOffset, + ])).toEqual([ + ['/api/v0/users/notifications/list', '', 'web', '3.0.0', 'zh_CN', '-18000'], + ['/api/v0/users/notifications/events', '', 'web', '3.0.0', 'zh_CN', '-18000'], + ]) +}) + +it('does not query the account identity across repeated notification reads and reports', async () => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata('en')) + await f.account.getNotifications(clientMetadata('en')) + await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')) + expect(f.requests.filter(request => request.url === '/auth-api/v0/users/current')).toHaveLength(0) +}) + +it('does not reuse a cached identity from another grant', async () => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + await f.grant('rotated-token') + await f.account.getNotifications(clientMetadata('en')) + expect(f.requests.map(request => [request.url, request.token])).toEqual([ + ['/auth-api/v0/users/current', 'test-account-token'], + ['/api/v0/users/notifications/list', 'rotated-token'], + ]) +}) + +it('leaves profile identity unknown when only notifications were queried', async () => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata()) + expect(await f.account.getPlatformSession()).toMatchObject({ userId: null, token: 'test-account-token' }) + expect(f.requests.map(request => request.url)).toEqual(['/api/v0/users/notifications/list']) +}) + +it.each([undefined, null, 0, -1, '300', 2_147_483.648])('rejects an invalid next_poll_after value: %s', async (delay) => { + const f = await fixture() + await f.grant('test-account-token') + f.nextPollAfter(delay) + await expect(f.account.getNotifications(clientMetadata())).rejects.toMatchObject({ code: 'protocol' }) +}) + +it.each([0.5, 300, 2_147_483.647])('preserves the server polling delay in seconds: %s', async (delay) => { + const f = await fixture() + await f.grant('test-account-token') + f.nextPollAfter(delay) + expect((await f.account.getNotifications(clientMetadata()))?.nextPollAfterSeconds).toBe(delay) +}) + +it('reads generic notifications in server order with account and client headers', async () => { + const f = await fixture() + await f.grant('test-account-token') + const result = await f.account.getNotifications(clientMetadata('zh-CN')) + expect(result).toEqual({ nextPollAfterSeconds: 300, notifications: [ + { id: ORDER as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Product news', body: 'New features are available.', actions: [] }, + { id: SECOND_ORDER as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Product news', body: 'New features are available.', actions: [] }, + ] }) + expect(f.requests).toEqual([ + { method: 'GET', url: '/api/v0/users/notifications/list', token: 'test-account-token', locale: 'zh_CN', + bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, + ]) +}) + +it.each(['list', 'content'] as const)('accepts a %s notification without a business classification', async (operation) => { + const f = await fixture() + await f.grant('test-account-token') + const value = wire(ORDER) + f.notifications([value]) + f.content(value) + const notification = operation === 'list' ? (await f.account.getNotifications(clientMetadata()))?.notifications[0] + : await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + expect(notification).toMatchObject({ id: ORDER, title: 'Product news', body: 'New features are available.', actions: [] }) + expect(notification).not.toHaveProperty('type') +}) + +it.each(['notice', '123', '', '产品公告/one?lang=zh&part=2#latest%'])('preserves the string ID %j across list, content, and events', async (value) => { + const f = await fixture() + await f.grant('test-account-token') + const id = value as AccountNotificationId + f.notifications([wire(id)]) + f.content(wire(id)) + expect((await f.account.getNotifications(clientMetadata()))?.notifications[0]?.id).toBe(id) + expect((await f.account.getNotificationContent(id, clientMetadata()))?.id).toBe(id) + expect(await f.account.reportNotificationEvent(id, 'dismissed', clientMetadata())).toBe(true) + expect([f.requests[0]?.url, f.requests[2]?.url]).toEqual([ + '/api/v0/users/notifications/list', + '/api/v0/users/notifications/events', + ]) + const contentUrl = new URL(f.requests[1]!.url!, 'https://fixture.invalid') + expect(contentUrl.pathname).toBe('/api/v0/users/notifications/content') + expect([...contentUrl.searchParams]).toEqual([['id', id]]) + expect(contentUrl.hash).toBe('') + expect(f.requests.at(-1)?.body).toBe(JSON.stringify({ notification_id: id, type: 'dismissed' })) +}) + +it('keeps action targets and business expiry separate from the display deadline', async () => { + const f = await fixture() + await f.grant('test-account-token') + const actions = [{ label: 'View balance', style: 'primary', target: { type: 'app_route', name: 'account' } }, + { label: 'Got it', style: 'secondary', target: { type: 'dismiss' } }] + const data = { order_id: 'business-order', expires_at: '2026-11-21T08:00:00Z', amount: '5.00' } + f.notifications([wire(ORDER, { display_until: '2026-10-28T08:00:00Z', actions, data })]) + expect((await f.account.getNotifications(clientMetadata()))?.notifications).toEqual([ + { id: ORDER, createdAt: '2026-10-21T08:00:00Z', displayUntil: '2026-10-28T08:00:00Z', + title: 'Product news', body: 'New features are available.', actions, data }, + ]) +}) + +it.each([ + ['zh-CN', 'zh_CN'], + ['en-US', 'en_US'], +])('selects %s copy through the locale header and never a language query', async (locale, wireLocale) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata(locale)) + expect(f.requests.map(request => request.locale)).toEqual([wireLocale]) + expect(f.requests.map(request => request.url)).toEqual([ + '/api/v0/users/notifications/list', + ]) +}) + +it.each([ + ['a non-string title', [wire(ORDER, { title: 42 })]], + ['a null title', [wire(ORDER, { title: null })]], + ['a non-string ID', [wire(ORDER, { id: 42 })]], + ['an invalid display deadline', [wire(ORDER, { display_until: '' })]], + ['an invalid creation time', [wire(ORDER, { created_at: 'yesterday' })]], + ['a missing body', [wire(ORDER, { body: undefined })]], + ['a non-array actions field', [wire(ORDER, { actions: null })]], + ['an unsupported action style', [wire(ORDER, { actions: [{ label: 'Open', style: 'danger', target: { type: 'dismiss' } }] })]], + ['an unsupported route', [wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'app_route', name: 'other' } }] })]], + ['an unsupported target', [wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'url', url: 'https://example.invalid' } }] })]], +])('skips malformed or unsupported notifications without losing valid neighbors: %s', async (_name, payload) => { + const f = await fixture() + await f.grant('test-account-token') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + f.notifications([wire('before'), ...payload, wire('after')]) + const result = await f.account.getNotifications(clientMetadata()) + expect(result?.notifications.map(value => value.id)).toEqual(['before', 'after']) + expect(result?.nextPollAfterSeconds).toBe(300) + expect(log).toHaveBeenCalledOnce() + expect(log.mock.calls[0]?.[0]).toBe('[deepseek-account] skipping unsupported notification') + expect(log.mock.calls[0]?.[1]).toMatchObject({ index: 1 }) + } finally { log.mockRestore() } +}) + +it('returns an empty batch when every notification is unsupported', async () => { + const f = await fixture() + await f.grant('test-account-token') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + f.notifications([wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'future' } }] })]) + expect(await f.account.getNotifications(clientMetadata())).toEqual({ notifications: [], nextPollAfterSeconds: 300 }) + } finally { log.mockRestore() } +}) + +it('rejects a notification payload that is not a list', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.notifications({}) + await expect(f.account.getNotifications(clientMetadata())).rejects.toThrow('account: protocol') +}) + +it('streams credential changes with current state and leaves profile reads silent', async () => { + const f = await fixture() + const lifetime = new AbortController() + const iterator = f.account.watch(lifetime.signal)[Symbol.asyncIterator]() + try { + expect(await iterator.next()).toMatchObject({ value: { type: 'snapshot', state: { status: 'signed-out' } } }) + await f.grant('first-token') + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + await f.account.getProfile(clientMetadata()) + const next = iterator.next() + await f.grant('second-token') + expect(await next).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + await f.signOut() + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'signed-out' } } }) + } finally { + lifetime.abort() + await iterator.return?.() + } +}) + +it('keeps a queued credential change ahead of a later profile snapshot', async () => { + const f = await fixture() + const lifetime = new AbortController() + const iterator = f.account.watch(lifetime.signal, true)[Symbol.asyncIterator]() + try { + expect(await iterator.next()).toMatchObject({ value: { type: 'snapshot' } }) + await f.grant('first-token') + await f.account.getProfile(clientMetadata()) + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } finally { + lifetime.abort() + await iterator.return?.() + } +}) + +it.each(['replacement', 'abort'] as const)('discards an opening snapshot invalidated by %s during the read', async (change) => { + const f = await fixture() + const lifetime = new AbortController() + const reading = Promise.withResolvers() + const release = Promise.withResolvers() + const readState = f.account.getState.bind(f.account) + vi.spyOn(f.account, 'getState').mockImplementationOnce(async () => { + const state = await readState() + reading.resolve(undefined) + await release.promise + return state + }) + const iterator = f.account.watch(lifetime.signal)[Symbol.asyncIterator]() + const first = iterator.next() + try { + await reading.promise + if (change === 'replacement') await f.grant('replacement-token') + else lifetime.abort() + release.resolve(undefined) + if (change === 'replacement') { + expect(await first).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } else expect(await first).toMatchObject({ done: true }) + } finally { + release.resolve(undefined) + lifetime.abort() + await first + await iterator.return?.() + } +}) + +it.each(['displayed', 'cta_clicked', 'dismissed'] as const)('reports %s with the grant, locale, and a JSON body', async (event) => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, event, clientMetadata('zh-CN'))).toBe(true) + expect(f.requests).toEqual([ + { method: 'POST', url: '/api/v0/users/notifications/events', token: 'test-account-token', locale: 'zh_CN', + bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800', + contentType: 'application/json', body: JSON.stringify({ notification_id: ORDER, type: event }) }, + ]) +}) + +it.each([ + ['the unnotified read', (f: Awaited>) => { + f.failBonuses(0, 401) + return f.account.getNotifications(clientMetadata('en')) + }, null], + ['the acknowledgement', (f: Awaited>) => { + f.failAck(0, 401) + return f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')) + }, false], +])('expires the rejected grant when %s returns HTTP 401', async (_name, run, signedOutOutcome) => { + const f = await fixture() + await f.grant('test-account-token') + const expired = vi.fn() + f.ctx.on('deepseek-account/session-expired', expired) + // A rejected authenticated request names an invalid credential, so the provider drops it locally + // exactly as the profile and balance reads do; the caller sees its signed-out outcome. + expect(await run(f)).toBe(signedOutOutcome) + expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) + expect(expired).toHaveBeenCalledOnce() +}) + +it.each([ + ['read', (f: Awaited>) => f.account.getNotifications(clientMetadata('en')), null], + ['acknowledgement', (f: Awaited>) => + f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')), false], +])('ignores a bonus %s rejection whose response cleanup overlaps a credential replacement', async (_name, run, outcome) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getProfile(clientMetadata()) + const response = new Response('', { status: 401 }) + const cancel = response.body!.cancel.bind(response.body) + // Credential changes can arrive while the response reader releases a rejected response body. + const cleanup = vi.spyOn(response.body!, 'cancel').mockImplementation(async () => { + await f.grant('replacement-token') + await cancel() + }) + const fetchResponse = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) + const expired = vi.fn() + f.ctx.on('deepseek-account/session-expired', expired) + try { + expect(await run(f)).toBe(outcome) + expect(cleanup).toHaveBeenCalledOnce() + expect(expired).not.toHaveBeenCalled() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) + } finally { cleanup.mockRestore(); fetchResponse.mockRestore() } +}) + +it('retains the grant when an acknowledgement returns HTTP 500', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(0, 500) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))) + .rejects.toThrow('account: network') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it('rejects the supplied NOTIFICATION_NOT_FOUND envelope as a business failure', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(1) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))) + .rejects.toThrow('account: protocol') + expect(f.requests[0]).toMatchObject({ + method: 'POST', url: '/api/v0/users/notifications/events', locale: 'en_US', + contentType: 'application/json', body: JSON.stringify({ notification_id: ORDER, type: 'displayed' }), + }) +}) + +it.each([ + ['a business failure', 1, 200, 'account: protocol'], + ['an HTTP failure', 0, 500, 'account: network'], +])('surfaces %s as a retryable acknowledgement failure', async (_name, bizCode, status, message) => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(bizCode, status) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).rejects.toThrow(message) +}) + +it('accepts an acked false response without treating it as a retryable failure', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.acknowledged(false) + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'dismissed', clientMetadata())).toBe(true) + expect(f.requests.map(request => request.url)).toEqual(['/api/v0/users/notifications/events']) + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it('returns signed-out outcomes without any request', async () => { + const f = await fixture() + expect(await f.account.getNotifications(clientMetadata('en'))).toBeNull() + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).toBe(false) + expect(f.requests).toEqual([]) +}) + +it('discards a list response invalidated by a credential change', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.onList(async () => { await f.grant('rotated-token') }) + expect(await f.account.getNotifications(clientMetadata())).toBeNull() + expect(f.requests.map(request => [request.url, request.token])).toEqual([ + ['/api/v0/users/notifications/list', 'test-account-token'], + ]) +}) + +it('queries notifications and reports events while profile data is unavailable', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failProfile(17, 503) + expect((await f.account.getNotifications(clientMetadata()))?.notifications).toHaveLength(2) + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toMatchObject({ id: ORDER }) + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata())).toBe(true) + expect(f.requests.map(request => request.url)).toEqual([ + '/api/v0/users/notifications/list', `/api/v0/users/notifications/content?id=${ORDER}`, '/api/v0/users/notifications/events', + ]) +}) + +it('reuses a cached identity for the same credential after a failed query', async () => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + f.failProfile() + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).resolves.toBe(true) +}) + +it('queries notifications independently of a profile without a user ID', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.profileId(null) + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + f.failProfile() + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata())).resolves.toBe(true) + expect(f.requests.at(-1)?.url).toBe('/api/v0/users/notifications/events') +}) + +it('reads localized content of a consumed notification without listing or acknowledging it', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.notifications([]) + f.content(wire(ORDER, { title: '产品公告', body: '新功能已上线', actions: [ + { label: '知道了', style: 'secondary', target: { type: 'dismiss' } }, + ] })) + const content = await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata('zh')) + expect(content).toMatchObject({ id: ORDER, title: '产品公告', body: '新功能已上线', + actions: [{ label: '知道了', style: 'secondary', target: { type: 'dismiss' } }] }) + expect(f.requests.map(request => request.url)).toEqual([ + `/api/v0/users/notifications/content?id=${ORDER}`, + ]) + expect(f.requests.at(-1)).toMatchObject({ method: 'GET', token: 'test-account-token', locale: 'zh_CN' }) +}) + +it('does not query notification content while signed out', async () => { + const f = await fixture() + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toBeNull() + expect(f.requests).toEqual([]) +}) + +it.each([ + ['a mismatched ID', wire(SECOND_ORDER)], + ['malformed content', { title: 'private-content' }], +])('rejects %s returned by the content endpoint', async (_name, content) => { + const f = await fixture() + await f.grant('test-account-token') + f.content(content) + await expect(f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())) + .rejects.toThrow('account: protocol') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it.each([401, 500])('handles a content HTTP %s without discarding a usable grant', async (status) => { + const f = await fixture() + await f.grant('test-account-token') + f.failContent(0, status) + const result = f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + if (status === 401) { + expect(await result).toBeNull() + expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) + } else { + await expect(result).rejects.toThrow('account: network') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) + } +}) + +it('discards content when the credential changes before its response', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.onContent(async () => { await f.grant('replacement-token') }) + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toBeNull() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) +}) + +it.each(['list', 'content', 'display'] as const)('discards a successful %s response whose reader cleanup overlaps credential replacement', async (operation) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getProfile(clientMetadata()) + const payload = operation === 'list' ? { next_poll_after: 300, notifications: [wire(ORDER)] } : operation === 'content' ? wire(ORDER) : { acked: true } + const response = new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: payload } })) + const body = response.body! + const reader = body.getReader() + const cancel = reader.cancel.bind(reader) + const cleanup = vi.spyOn(reader, 'cancel').mockImplementationOnce(async () => { + await f.grant('replacement-token') + await cancel() + }) + const getReader = vi.spyOn(body, 'getReader').mockReturnValue(reader) + const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) + try { + const result = operation === 'list' ? await f.account.getNotifications(clientMetadata()) + : operation === 'content' ? await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + : await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata()) + expect(result).toBe(operation === 'display' ? false : null) + expect(cleanup).toHaveBeenCalledOnce() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) + } finally { + fetcher.mockRestore() + getReader.mockRestore() + cleanup.mockRestore() + if (body.locked) { await reader.cancel(); reader.releaseLock() } + } +}) diff --git a/packages/credentials/deepseek-account/tests/origins.spec.ts b/packages/credentials/deepseek-account/tests/origins.spec.ts new file mode 100644 index 0000000000..bd947d88b6 --- /dev/null +++ b/packages/credentials/deepseek-account/tests/origins.spec.ts @@ -0,0 +1,92 @@ +/** Notification destinations are independent of Platform account and browser destinations. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account' +import { DeepSeekAccount, type Config } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + while (cleanups.length) await cleanups.pop()!() + vi.restoreAllMocks() +}) + +async function fixture(issuer: string, config: Config = {}) { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-origin-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await ctx.plugin(AuthorizationService) + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token: 'fixture-token', issuer }, + })) + await ctx.plugin(DeepSeekAccount, config) + return ctx.deepseekAccount +} + +it('routes only notification APIs to Harness while account APIs and pages stay on Platform', async () => { + const account = await fixture('https://platform.deepseek.com') + expect(await account.getState()).toMatchObject({ status: 'credential-stored', links: { + usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up', + } }) + expect(await account.getPlatformSession()).toMatchObject({ origin: 'https://platform.deepseek.com', token: 'fixture-token' }) + const id = 'f487920c-a8d5-59b6-90f0-b787adc97980' as AccountNotificationId + const content = { id, created_at: '2026-10-28T06:12:11Z', display_until: null, title: 'News', body: 'Content', actions: [] } + const requests: string[] = [] + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + if (typeof input !== 'string') throw new Error('expected a URL string') + const url = input + requests.push(url) + const path = new URL(url).pathname + const payload = path === '/auth-api/v0/users/current' ? { id: 'account', email: '' } + : path === '/api/v0/users/get_user_summary' ? { normal_wallets: [], bonus_wallets: [] } + : path.endsWith('/list') ? { notifications: [content], next_poll_after: 600 } + : path.endsWith('/content') ? content : { acked: true } + return new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: payload } })) + }) + const client = { version: 'test', locale: 'en', timezoneOffsetSeconds: 0 } + expect(await account.getProfile(client)).toMatchObject({ status: 'ready' }) + expect(await account.getBalance(client)).toMatchObject({ status: 'ready' }) + expect((await account.getNotifications(client))?.notifications[0]?.id).toBe(id) + expect((await account.getNotificationContent(id, client))?.id).toBe(id) + expect(await account.reportNotificationEvent(id, 'dismissed', client)).toBe(true) + expect(requests).toEqual([ + 'https://platform.deepseek.com/auth-api/v0/users/current', + 'https://platform.deepseek.com/api/v0/users/get_user_summary', + 'https://harness.deepseek.com/api/v0/users/notifications/list', + `https://harness.deepseek.com/api/v0/users/notifications/content?id=${id}`, + 'https://harness.deepseek.com/api/v0/users/notifications/events', + ]) +}) + +it('keeps private grants and embedded pages on Platform while allowing a notification origin override', async () => { + const rejected = await fixture('https://platform.deepseek.com', { platformOrigin: 'https://private.example' }) + expect(await rejected.getState()).toMatchObject({ status: 'signed-out' }) + const account = await fixture('https://private.example', { + platformOrigin: 'https://private.example', harnessOrigin: 'https://notifications.example', + requestHeaders: { 'x-deployment': 'base' }, accountRequestHeaders: { 'x-account': 'account' }, + }) + expect(await account.getPlatformSession()).toMatchObject({ + origin: 'https://private.example', token: 'fixture-token', + requestHeaders: { 'x-deployment': 'base', 'x-account': 'account' }, + }) + const fetcher = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + expect(input).toBe('https://notifications.example/api/v0/users/notifications/list') + expect(init?.headers).toMatchObject({ 'x-deployment': 'base', 'x-account': 'account', 'x-dsh-auth-token': 'fixture-token' }) + return new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { notifications: [], next_poll_after: 600 } } })) + }) + await account.getNotifications({ version: 'test', locale: 'en', timezoneOffsetSeconds: 0 }) + expect(fetcher).toHaveBeenCalledOnce() +}) + +it.each(['http://remote.example', 'https://notifications.example/path'])( + 'rejects the invalid notification origin %s during initialization', async (harnessOrigin) => { + await expect(fixture('https://platform.deepseek.com', { harnessOrigin })).rejects.toThrow('harnessOrigin') + }, +) diff --git a/packages/credentials/deepseek-account/tests/remote.spec.ts b/packages/credentials/deepseek-account/tests/remote.spec.ts new file mode 100644 index 0000000000..e33fc547da --- /dev/null +++ b/packages/credentials/deepseek-account/tests/remote.spec.ts @@ -0,0 +1,87 @@ +/** Account Remote exports retain their wire names and exclude Host credentials. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it } from 'vitest' +import { DeepSeekAccount } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-remote-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await ctx.plugin(AuthorizationService) + const provider = ctx.plugin(DeepSeekAccount) + await provider + return { ctx, account: ctx.deepseekAccount, provider } +} + +it('binds only client-safe operations to the existing account namespace', async () => { + const { account } = await fixture() + expect(account.typertRemote.service instanceof DeepSeekAccount).toBe(true) + expect(account.typertRemote.serviceKey).toBe('deepseekAccount') + expect(account.typertRemote.namespace).toBe('account') + expect(remoteMethods(account).map(method => method.exportName ?? method.method).sort()).toEqual([ + 'cancelSignIn', 'getBalance', 'getNotificationContent', 'getNotifications', 'getProfile', 'getState', + 'hasRunningAccountTasks', 'reportNotificationEvent', 'signOut', 'startSignIn', 'watch', 'watchExpiry', + ]) + expect(remoteMethods(account).filter(method => method.mode === 'stream').map(method => method.exportName ?? method.method).sort()) + .toEqual(['watch', 'watchExpiry']) +}) + +it('streams initial state and credential changes and ends on cancellation', async () => { + const { ctx, account } = await fixture() + const lifetime = new AbortController() + const stream = account.watchState(lifetime.signal)[Symbol.asyncIterator]() + try { + expect(await stream.next()).toMatchObject({ done: false, value: { type: 'snapshot', state: { status: 'signed-out' } } }) + const next = stream.next() + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token: 'fixture-token', issuer: 'https://platform.deepseek.com' }, + })) + expect(await next).toMatchObject({ done: false, value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } finally { lifetime.abort() } + expect(await stream.next()).toEqual({ done: true, value: undefined }) +}) + +it('delivers expiry only to current subscribers and stops on disconnect or provider disposal', async () => { + const { ctx, account, provider } = await fixture() + ctx.emit('deepseek-account/session-expired') + const lifetime = new AbortController() + const stream = account.watchExpiry(lifetime.signal)[Symbol.asyncIterator]() + const first = stream.next() + ctx.emit('deepseek-account/session-expired') + expect(await first).toEqual({ done: false, value: 'session-expired' }) + const next = stream.next() + lifetime.abort() + expect(await next).toEqual({ done: true, value: undefined }) + const reopened = account.watchExpiry(new AbortController().signal)[Symbol.asyncIterator]().next() + await provider.dispose() + expect(await reopened).toEqual({ done: true, value: undefined }) +}) + +it('reports running account requests and excludes absent, idle, and other-provider tasks', async () => { + const { ctx, account } = await fixture() + expect(account.hasRunningAccountTasks()).toBe(false) + const active: Array> = [] + const task = (status: Agent['status'], provider?: string): Pick => ({ + status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], + }) + ctx.provide('agents', { list: () => active } as Context['agents']) + active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) + expect(account.hasRunningAccountTasks()).toBe(false) + active.push(task('running', 'deepseek-account')) + expect(account.hasRunningAccountTasks()).toBe(true) + active.pop() + expect(account.hasRunningAccountTasks()).toBe(false) +}) diff --git a/packages/credentials/deepseek-account/tsconfig.json b/packages/credentials/deepseek-account/tsconfig.json index a0da11ddaa..e4add1d675 100644 --- a/packages/credentials/deepseek-account/tsconfig.json +++ b/packages/credentials/deepseek-account/tsconfig.json @@ -22,6 +22,21 @@ }, { "path": "../../llm/llm" + }, + { + "path": "../authorization" + }, + { + "path": "../credentials" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../host/webserver" + }, + { + "path": "../../typert/protocol" } ] } diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 52f8e69cd1..851fed865d 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: a33264258ae8b2f6 - zh: 0d250e4610050228 + en: c7e1b7d87ccccd2e + zh: 42d864b918a6175c /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0c2dd86b5f6b489d - zh: 2f0fce0affa48f59 + en: eaf062b1439ed8b3 + zh: d7c6a68779774825 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: d62a9841cc34dfdd - zh: 5aa4ffb331c5bb93 + en: 10101427d1e0589b + zh: c981cec12f64eb75 /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 0f795ca1c607af01 - zh: a05ac28fb2313d6e + en: 4124d453778daf7b + zh: 33cab3137381942e /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index d4c84d4fe6..c4e36aaba3 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,17 +36,19 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button. - **Header button** — appears when the Session has bound change requests or its directory is inside a Git checkout, and shows or hides the tab. A red dot marks an open change request with failed checks, requested changes, or conflicts. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. -- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. +- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. + +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, and `maxCachedDiffBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). -All files opens a searchable directory tree. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. +All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. ----- @@ -56,7 +58,7 @@ All files opens a searchable directory tree. Single-child directories share a ro
    Implementation internals — click to expand -`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` for every change. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. +`ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --short HEAD`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `branches` runs `symbolic-ref` and `for-each-ref --count=`; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes card: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. @@ -67,11 +69,11 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. | Source | Responsibility | |---|---| @@ -82,13 +84,18 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/git.ts`](src/git.ts) | Git queries under Session permissions | | [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order | | [`src/diff.ts`](src/diff.ts) | Patch parsing, untracked files as additions, and numstat records | -| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, new-side text, and the `branch` scope summary | +| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, branch commits, new-side text, and the `branch` scope summary | +| [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view | +| [`src/client/section-reach.ts`](src/client/section-reach.ts) | When file sections draw their lines | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | Commit picker | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | Viewed marks kept in the browser | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | @@ -111,7 +118,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t ## Model Experience -Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, and local Branch quotes the base the view compared with. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. #### KV Cache effect @@ -130,9 +137,14 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. - **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. -- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. +- **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. +- **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws. +- **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. +- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. +- **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. +- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 65ed82f12e..ebe5c653ef 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,17 +36,19 @@ kind: "package-reference" - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 +- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 + +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles` 与 `maxCachedDiffBytes` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 -“全部文件”打开可搜索的目录树;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 +“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 ----- @@ -56,7 +58,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
    实现细节——点击展开 -`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,每次变化都发布新的 `ForgePanelState`。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 +`ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更卡片统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 @@ -67,11 +69,11 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内时才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。 | 源码 | 职责 | |---|---| @@ -82,13 +84,18 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 | | [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 | | [`src/diff.ts`](src/diff.ts) | 补丁解析、把未跟踪文件表示为新增,以及 numstat 记录 | -| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、新版本文本与 `branch` 范围摘要 | +| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、分支提交、新版本文本与 `branch` 范围摘要 | +| [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | +| [`src/client/section-reach.ts`](src/client/section-reach.ts) | 文件段何时绘制各行 | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | 提交选择器 | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | 保存在浏览器中的已审阅标记 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -111,7 +118,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 #### KV Cache 影响 @@ -130,9 +137,14 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 - **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 -- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 +- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 +- **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 +- **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 +- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 +- **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 +- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 7ab090b292..8dd840d825 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -71,7 +71,8 @@ "diff": "^9.0.0", "zod": "4.6.6", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "picomatch": "^4.0.7" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -115,7 +116,8 @@ "@deepseek-ai/dsh-timeout": "workspace:*", "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-session-query": "workspace:*", - "@deepseek-ai/dsh-api-remote-access": "workspace:*" + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@types/picomatch": "^4.0.3" }, "files": [ "locale/*.json", diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 9795e3558c..5a90b9e6b3 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -75,6 +75,7 @@ const FAILURE: Record = { 'not-found': 'change.failure.notFound', 'unauthenticated': 'change.failure.unauthenticated', 'too-large': 'change.failure.unavailable', + 'stale': 'change.failure.unavailable', 'unavailable': 'change.failure.unavailable', } @@ -89,6 +90,12 @@ const CHECK_RANK: Record = { failure: 0, pending: 1, success: 2, neutral: 3, skipped: 3, cancelled: 3, } +/** The unresolved thread count, with `+` when the provider counted only some threads. */ +function threadCount(snapshot: ChangeRequestSnapshot, locale: string): string { + const count = snapshot.unresolvedThreads.toLocaleString(locale) + return snapshot.threadsTruncated ? `${count}+` : count +} + function failureOf(entry: ForgePanelChangeRequest): ForgeFailure | undefined { return entry.update !== null && 'failure' in entry.update ? entry.update.failure : undefined } @@ -434,7 +441,8 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { {t('change.row.review')} - {snapshot.unresolvedThreads > 0 ? t('change.review.threads', { review, count: snapshot.unresolvedThreads }) : review} + {snapshot.unresolvedThreads > 0 || snapshot.threadsTruncated + ? t('change.review.threads', { review, count: threadCount(snapshot, locale) }) : review}
    diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index 7fae97d78d..995bae454d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -1,11 +1,11 @@ /** Changed-file navigation shared by the toolbar menu and wide diff pane, with a disclosure column on every row. */ -import { useMemo, useState, type ReactNode } from 'react' +import { useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' import clsx from 'clsx' import { FileTypeIcon, IconChevronDownOutlineRegular, IconFolderCloseRegular, Input, Menu, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeDiffFile } from '../types.ts' import { Counts } from './DiffFile.tsx' -import { changedFileTree, filterFileTree, type ChangedFileNode } from './file-tree.ts' +import { changedFileTree, filesInTreeOrder, filterFileTree, type ChangedFileNode } from './file-tree.ts' import type { NS } from './locales.ts' import css from './ChangedFiles.module.css' @@ -62,6 +62,23 @@ function Rows({ nodes, depth, props }: { }) } +/** + * Scroll only the row container to show a row that is not wholly visible; a visible row stays where it is. + * `scrollIntoView` would also scroll every scrollable ancestor, moving the menu card or the page behind it, and + * its `container` option is not yet supported widely enough, so the offset is measured here. + * @param container - the scrolling rows. + * @param row - the row to show. + * @param align - `center` places the row mid-view with its neighbors; `nearest` scrolls by the least distance. + */ +function revealRow(container: HTMLElement, row: HTMLElement, align: 'center' | 'nearest'): void { + const top = container.getBoundingClientRect().top + container.clientTop + const bottom = top + container.clientHeight + const box = row.getBoundingClientRect() + if (box.top >= top && box.bottom <= bottom) return + if (align === 'center') container.scrollTop += (box.top + box.bottom - top - bottom) / 2 + else container.scrollTop += box.top < top ? box.top - top : box.bottom - bottom +} + /** * Render searchable directory navigation without reading file contents. * @param props - changed files, per-tab choices, navigation actions, and localized copy. @@ -70,11 +87,36 @@ function Rows({ nodes, depth, props }: { export function ChangedFiles(props: ChangedFilesProps): ReactNode { const tree = useMemo(() => changedFileTree(props.files), [props.files]) const nodes = useMemo(() => filterFileTree(tree, props.state.query), [tree, props.state.query]) + const order = useMemo(() => filesInTreeOrder(tree), [tree]) + const selectedIndex = order.findIndex(file => file.path === props.state.selected) + const rows = useRef(null) + const query = useRef(props.state.query) + // A changed filter shows its results from the top. + useLayoutEffect(() => { + if (query.current === props.state.query) return + query.current = props.state.query + const container = rows.current + /* v8 ignore next -- the ref is attached before layout effects run. */ + if (container === null) return + container.scrollTop = 0 + }, [props.state.query]) + const mounted = useRef(false) + // The toolbar menu mounts these rows at the top on every opening, so mounting centers the selected file. Later, a + // file step in the diff, or files arriving or reordering around a selection, scrolls by the least distance; a + // refresh that keeps the selected file's position leaves the reader's scroll alone. + useLayoutEffect(() => { + const align = mounted.current ? 'nearest' : 'center' + mounted.current = true + const container = rows.current + const row = container?.querySelector('[aria-current="true"]') + if (container == null || row == null) return + revealRow(container, row, align) + }, [props.state.selected, selectedIndex]) return
    { props.filter(event.target.value) }} onKeyDown={(event) => { if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() }} />
    -
    +
    {nodes.length === 0 ?
    {props.t('diff.noMatchingFiles')}
    : }
    diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 47193f0887..8f9ea2c8e6 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -91,21 +91,96 @@ } .headerEnd { - flex: none; + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + min-width: 0; margin-left: auto; } + .toolbar { display: flex; flex: none; - align-items: center; - gap: 4px; + align-items: stretch; box-sizing: border-box; - min-height: 38px; - padding: 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); } +/* Spans the file tree's width with the tree's search inset, and its divider continues the tree's border. */ +.lensCell { + display: none; + flex: none; + align-items: center; + box-sizing: border-box; + width: var(--forge-tree-width); + padding: 0 8px; + border-inline-end: 0.5px solid var(--dsw-alias-border-l3); +} + +.toolbar[data-tree='right'] .lensCell { + order: 1; + border-inline-start: 0.5px solid var(--dsw-alias-border-l3); + border-inline-end: 0; +} + +.toolbarMain { + display: flex; + flex: 1; + flex-wrap: wrap; + align-items: center; + gap: 0 4px; + box-sizing: border-box; + min-width: 0; + min-height: 38px; + padding: 5px 8px; +} + +.lensMenu { + display: inline-flex; +} + +@container forge-changes (min-width: 760px) { + .toolbar:not([data-tree='hidden']) .lensCell { + display: flex; + } + + .toolbar:not([data-tree='hidden']) .lensMenu { + display: none; + } +} + +.spacer { + flex: 1; +} + +.progressSlot { + display: inline-flex; +} + +/* Breaks the toolbar's review controls onto a second row where one row is too narrow for them. */ +.rowBreak { + display: none; +} + +@container forge-changes (max-width: 640px) { + .reviewRow { + order: 2; + } + + .rowBreak { + display: block; + flex-basis: 100%; + order: 1; + height: 4px; + } + + .progressSlot { + margin-left: auto; + } +} + .select { display: inline-flex; flex: 0 1 auto; @@ -173,7 +248,6 @@ flex: none; align-items: center; gap: 2px; - margin-left: auto; } .tool { @@ -272,9 +346,12 @@ } .files { + --forge-files-inset: 10px; flex: 1; + box-sizing: border-box; min-width: 0; min-height: 0; + padding: var(--forge-files-inset); overflow: auto; } @@ -303,14 +380,34 @@ text-align: center; } +/* Each file is one card, so a file's last collapsed-context strip and the next file's header no longer read as adjacent + rows. Diffs share R16; clip, unlike hidden, keeps the card from becoming the sticky header's scroll container. */ .file { - border-bottom: 0.5px solid var(--dsw-alias-border-l3); + overflow: clip; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-lg); + background: var(--forge-changes-bg); } -/* Above the comment plus (z-index 1) of rows scrolled beneath it. */ +.file + .file { + margin-top: 12px; +} + +@container forge-changes (max-width: 380px) { + .files { + --forge-files-inset: 6px; + } + + .file + .file { + margin-top: 8px; + } +} + +/* Above the comment plus (z-index 1) of rows scrolled beneath it. Sticky offsets start inside the list's padding, + so the negative inset keeps a stuck header flush with the scroll area's top edge. */ .fileHeader { position: sticky; - top: 0; + top: calc(-1 * var(--forge-files-inset, 0px)); z-index: 2; display: flex; align-items: center; @@ -319,7 +416,8 @@ min-height: 36px; padding: 0 4px 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); - background: var(--forge-changes-bg); + /* The hover tint over the view background stays opaque while code scrolls beneath the sticky header. */ + background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg); } /* A bare chevron: its rotation shows whether the file is expanded, so it takes no fill in any state. */ @@ -348,10 +446,23 @@ border-bottom: 0; } +/* The file's own information gives way inside this box, so the counts, the viewed mark, and the menu after it stay + whole at any width. */ +.fileTitle { + display: flex; + flex: 1 1 0; + align-items: center; + gap: 6px; + min-width: 0; + overflow: hidden; +} + .fileIcon { flex: none; } +/* The path shares the shortage with the badge in proportion to their widths, so the longer path keeps the larger part + and stays under the pointer for its full-path tooltip. */ .filePath { display: flex; flex: 0 1 auto; @@ -371,8 +482,73 @@ transform: rotate(-90deg); } -.badge { +/* Capped rather than shrunk, so a long path never truncates the tag; a longer translation ends in an ellipsis. */ +.changedTag { flex: none; + max-width: 30%; +} + +.changedText { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +/* The viewed mark: a native checkbox with its label as one bordered chip, peer to the file menu button. */ +.viewed { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + box-sizing: border-box; + height: 24px; + padding: 0 8px 0 6px; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: var(--dsw-radius-sm); + color: var(--dsw-alias-label-secondary); + white-space: nowrap; + cursor: pointer; + user-select: none; +} + +.viewed input { + margin: 0; + accent-color: var(--dsw-alias-state-business-primary); + cursor: pointer; +} + +.viewed:has(input:checked) { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .viewed:hover { + color: var(--dsw-alias-label-primary); + } +} + +.viewed:has(input:focus-visible) { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.viewed input:focus-visible { + outline: none; +} + +@container forge-changes (max-width: 520px) { + .viewed { + padding: 0 6px; + } + + .viewedLabel { + display: none; + } +} + +.badge { + flex: 0 1 auto; + min-width: 0; max-width: 50%; overflow: hidden; padding: 0 6px; @@ -391,6 +567,12 @@ font: var(--dsw-font-markdown-code-block); } +/* An expanded file the reader has not scrolled near yet: one 22px row (`.line`) per drawn line, so the scroll + range and the positions of the files below stay close to their drawn values. */ +.unreached { + height: calc(var(--forge-rows) * 22px); +} + /* One intrinsic-width track paints every unwrapped unified row across the scrolled width. */ .code:not([data-wrap]):not([data-split]) { display: grid; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 983c6b58a3..dd01665747 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -5,9 +5,15 @@ * layout. The view reads the changes when it opens, on each navigation, on * refresh, and when the change request's head or the checkout's `branch` * scope summary changes; a read keeps the previous changes on screen until it settles. + * File sections receive values that keep their identity across renders, so a + * render of the view redraws only the sections whose own values changed, and + * an expanded file draws its lines once its section comes near the scrollport. */ -import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' +import { + useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent, + type ReactNode, +} from 'react' import clsx from 'clsx' import { Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, @@ -21,10 +27,10 @@ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-rig import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, - ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, + ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' -import type { ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import type { ReviewActions } from './ReviewComposer.tsx' @@ -32,8 +38,12 @@ import { SubmitReview } from './SubmitReview.tsx' import type { ReviewSelection, ReviewSource } from './review.ts' import { BaseMenu } from './BaseMenu.tsx' import { parseChangesAddress, type ChangesSource } from './changes-address.ts' -import type { createChangesStore } from './changes-store.ts' -import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx' +import type { ChangesLens, createChangesStore } from './changes-store.ts' +import { CommitMenu } from './CommitMenu.tsx' +import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' +import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts' +import { Counts, DiffFile, type DiffFileAction, type DiffFileHandlers } from './DiffFile.tsx' +import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx' @@ -68,8 +78,16 @@ export interface ChangesTabInjected { readonly diffBases: (query: string, signal: AbortSignal) => Promise> /** Read the new side of one file in a local scope. */ readonly localText: (scope: ForgeLocalScope, path: string) => Promise> - /** Read the changes of a change request by its binding URL; `signal` aborts the read. */ - readonly changeRequestDiff: (url: string, signal: AbortSignal) => Promise> + /** List the commits of the `branch` scope compared with `base`, or with the automatic fork point for null; `signal` aborts the read. */ + readonly localCommits: (base: string | null, signal: AbortSignal) => Promise> + /** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */ + readonly changeRequestDiff: ( + url: string, commits: ForgeCommitRange | null, signal: AbortSignal, + ) => Promise> + /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */ + readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise> + /** The Session's viewed marks, kept in the browser. */ + readonly viewedFiles: ViewedFiles /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Open a URL outside the app. */ @@ -106,8 +124,10 @@ type ChangesData = readonly files: readonly ForgeDiffFile[] /** Binding URL of the change request. */ readonly url: string - /** Head commit the files describe, which supplies unchanged lines. */ + /** Commit the files end at, the head or the last chosen commit, which supplies unchanged lines. */ readonly headSha: string + /** Commits the files cover, or null for the whole change request. */ + readonly commits: ForgeCommitRange | null /** Commits the checkout's branch has beyond the head, or null. */ readonly localAhead: number | null /** Web page of each file at the head. */ @@ -148,6 +168,8 @@ const FAILURE: Partial> = { 'forgePanel/no-fork-point': 'diff.noForkPoint', 'forgePanel/diff-too-large': 'diff.tooLarge', 'forgePanel/filter-config-failed': 'diff.filterConfigFailed', + 'forgePanel/commits-missing': 'commits.missing', + 'forgePanel/commits-not-linear': 'commits.notLinear', } /** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */ @@ -171,6 +193,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T async function readChanges( source: ChangesSource, scope: ForgeLocalScope, + commits: ForgeCommitRange | null, reads: Pick, signal: AbortSignal, ): Promise> { @@ -180,10 +203,10 @@ async function readChanges( const { files, base, omitted } = result.value return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } - const result = await reads.changeRequestDiff(source.url, signal) + const result = await reads.changeRequestDiff(source.url, commits, signal) if (!result.ok) return result const { files, headSha, localAhead, fileUrls } = result.value - return { ok: true, value: { kind: 'change', files, url: source.url, headSha, localAhead, fileUrls } } + return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } } } /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ @@ -191,25 +214,51 @@ function baseRefOf(scope: ForgeLocalScope): string | null { return scope.kind === 'branch' ? scope.base : null } +/** The commits a local scope shows, or null for all of them and for scopes other than `branch`. */ +function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null { + return scope.kind === 'branch' ? scope.commits : null +} + /** The source review comments on loaded changes record: the change request head, or the local scope with its base. */ function reviewSourceOf(data: ChangesData): ReviewSource { return data.kind === 'local' - ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope) } - : { kind: 'change', url: data.url, headSha: data.headSha } + ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope) } + : { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits } } -/** The files that start expanded: every file until those above it change more than {@link OPEN_LINES} lines. */ -function initiallyOpen(files: readonly ForgeDiffFile[]): ReadonlySet { +/** + * Identity of a diff source for viewed marks: the change request or local scope with its base ref and chosen commits. + * A change request's marks stay across head commits, so a file whose change a new push altered reads as changed. + */ +function viewedSourceOf(source: ReviewSource): string { + return JSON.stringify(source.kind === 'local' + ? ['local', source.scope, source.baseRef, source.commits] + : ['change', source.url, source.commits]) +} + +/** + * The files that start expanded: every file not marked viewed until those above it change more than {@link OPEN_LINES} lines. + * @param files - every file in display order. + * @param marks - the viewed marks when the files loaded. + * @returns the paths of the expanded files. + */ +function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): ReadonlySet { const open = new Set() let above = 0 for (const file of files) { if (above > OPEN_LINES) break + if (viewedStateOf(marks, file.path, file.digest) === 'viewed') continue open.add(file.path) above += drawnLines(file) } return open } +/** Whether a file shows under a lens while test files hide or not. */ +function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean { + return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens) +} + /** What a rename badge names: the old file name, or the old path when only the directory changed. */ function renamedFrom(previous: string, path: string): string { const name = pathPartsOf(previous).name @@ -231,9 +280,11 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { return parts.join(' · ') } -function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onReview, t }: { +function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: { readonly url: string readonly entry: ForgePanelChangeRequest | undefined + /** Commit picker left of the review button. */ + readonly commitMenu: ReactNode readonly reviewCount: number readonly reviewDisabled: boolean readonly onReview: () => void @@ -249,9 +300,12 @@ function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onRev {snapshot === null ? url : snapshot.title} {number !== null && {t('change.number', { number })}} - + + {commitMenu} + + - )} + {(scope === 'branch' || creatable) && + {scope === 'branch' && commitMenu} + {creatable && } + }
    ) } @@ -369,8 +426,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { * @returns the view body. */ export function ChangesTab({ - useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, changeRequestDiff, - changeRequestText, + useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, + changeRequestText, changeRequestCommits, viewedFiles, openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -423,6 +480,7 @@ export function ChangesTab({ const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) const [treePosition, setTreePosition] = useState('left') + const [treeWidth, setTreeWidth] = useState(0) const treeId = useId() const [chosen, setChosen] = useState>>({}) // Each navigation applies once; its file, if it names one, opens and scrolls into view. @@ -447,7 +505,18 @@ export function ChangesTab({ const state = snapshot?.state ?? null const scope = choices?.scope ?? 'branch' const base = choices?.base ?? null - const localScope = useMemo((): ForgeLocalScope => scope === 'branch' ? { kind: 'branch', base: base?.ref ?? null } : { kind: scope }, [scope, base]) + const chosenCommits = choices?.commits ?? null + const lens = choices?.lens ?? 'all' + const hideTests = choices?.hideTests ?? false + const localScope = useMemo((): ForgeLocalScope => scope === 'branch' + ? { kind: 'branch', base: base?.ref ?? null, commits: chosenCommits } : { kind: scope }, [scope, base, chosenCommits]) + const changeCommits = source.kind === 'change' ? chosenCommits : null + const changeUrlOf = source.kind === 'change' ? source.url : '' + const listChangeCommits = useCallback( + (signal: AbortSignal) => changeRequestCommits(changeUrlOf, signal), [changeRequestCommits, changeUrlOf], + ) + const baseRef = base?.ref ?? null + const listLocalCommits = useCallback((signal: AbortSignal) => localCommits(baseRef, signal), [localCommits, baseRef]) const split = choices?.split ?? true const wrap = choices?.wrap ?? true const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined @@ -456,17 +525,34 @@ export function ChangesTab({ const pending = entry !== undefined && entry.ref !== null && entry.update === null const head = entry?.snapshot?.headSha ?? (pending ? null : '') const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head - const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : 'change' + const headCommit = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.commit : null + // The commits change with the head of a change request, with the local HEAD, branch, or base, and on a refresh. + const commitsVersion = `${attempt}\n${source.kind === 'local' + ? `${baseRef ?? ''}\n${headCommit ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? ''}` + const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}` const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null) const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null) // Names the read the inputs ask for; it is in flight until `finished` matches it. const read = version === null ? null : `${dataKey}\n${navigation.revision}\n${attempt}\n${version}` const [finished, setFinished] = useState(null) + // A change request read refused because the head moved past its status stays in flight until a status later than + // the one the read started with arrives; one that arrived during the read starts the next read at once. + const statusAt = entry?.update?.fetchedAt ?? null + const latestStatusAt = useRef(statusAt) + useEffect(() => { latestStatusAt.current = statusAt }, [statusAt]) + const [refused, setRefused] = useState<{ readonly read: string; readonly statusAt: number | null } | null>(null) + const waiting = refused !== null && refused.read === read && refused.statusAt === statusAt useEffect(() => { - if (!tab.visible || read === null || read === finished) return + if (!tab.visible || read === null || read === finished || waiting) return const controller = new AbortController() - void readChanges(source, localScope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { + const readAt = latestStatusAt.current + void readChanges(source, localScope, changeCommits, { localDiff, changeRequestDiff }, controller.signal).then((result) => { if (controller.signal.aborted) return + if (!result.ok && result.error.code === 'forgePanel/stale-head') { + setRefused({ read, statusAt: readAt }) + setFailure(null) + return + } setFinished(read) if (result.ok) { setLoaded({ key: dataKey, data: result.value }) @@ -476,9 +562,15 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, source, localScope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null - const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests]) + const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item, + allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record, [allFiles, hideTests]) + const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data]) + const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource) + const marks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -487,17 +579,35 @@ export function ChangesTab({ const latest = useRef(data) useEffect(() => { latest.current = data }, [data]) const [revealed, setRevealed] = useState>(new Set()) - const initial = useMemo(() => initiallyOpen(files), [files]) + // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays + // collapsed while it is marked viewed unless the reader expands it; a file whose change differs from its mark expands + // like an unmarked one. + const initial = useMemo(() => initiallyOpen(allFiles, marks), [allFiles]) + const expandedByDefault = (file: ForgeDiffFile): boolean => initial.has(file.path) && viewedStateOf(marks, file.path, file.digest) !== 'viewed' + const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file) const sections = useRef(new Map()) - const scrollport = useRef(null) + const scrollport = useRef(null) + const reach = useMemo(() => new SectionReach(), []) + const attachScrollport = useCallback((element: HTMLDivElement | null) => { + scrollport.current = element + reach.attach(element) + }, [reach]) // A short final file cannot align with the viewport top; retain its jump until the reader scrolls away. const jumpPosition = useRef<{ readonly data: ChangesData; readonly top: number } | null>(null) useLayoutEffect(() => { if (!tab.visible || wanted === null || data === null) return + // A file the lens or the test switch hides is shown before the view scrolls to it. + const hidden = allFiles.find(file => file.path === wanted && !shownBy(file, lens, hideTests)) + if (hidden !== undefined) { + if (lens !== 'all') actions.lensed(tab.id, 'all') + if (hideTests && hidden.layer === 'test') actions.toggledTests(tab.id) + return + } + // The browser's scroll anchoring keeps the section in place while the sections above it draw their lines. sections.current.get(wanted)?.scrollIntoView({ block: 'start' }) if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop } setWanted(null) - }, [tab.visible, wanted, data]) + }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id]) const refresh = (): void => { setAttempt(value => value + 1) } const root = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.root : null // A chosen base branch that is gone or shares no history with HEAD offers the automatic fork point instead. @@ -507,8 +617,10 @@ export function ChangesTab({ const failureText = baseFailure ?? t(message ?? 'diff.error') const changeUrl = source.kind === 'change' ? entry?.snapshot?.url ?? source.url : null const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed') - const automaticBase = baseFailure !== undefined && ( + const automaticBase = baseFailure !== undefined ? ( + ) : (failed === 'forgePanel/commits-missing' || failed === 'forgePanel/commits-not-linear') && ( + ) /** Apply a change to the unchanged lines of `owner`, unless newer changes replaced it. */ @@ -553,7 +665,8 @@ export function ChangesTab({ return list } - const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { @@ -563,9 +676,9 @@ export function ChangesTab({ }} t={t} /> const recordActions: ReviewActions = { - source: data !== null ? reviewSourceOf(data) : source.kind === 'local' - ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope) } - : { kind: 'change', url: source.url, headSha: '' }, + source: shownSource ?? (source.kind === 'local' + ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } + : { kind: 'change', url: source.url, headSha: '', commits: changeCommits }), records: queue, addToInput: addReviewToInput, openLink, } const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] @@ -578,26 +691,37 @@ export function ChangesTab({ setChosen(value => ({ ...value, [path]: true })) setWanted(path) } + /** + * The file being read: the file last jumped to while the scroll stays there, else the first file whose section still + * reaches below the viewport top, so the gap between two cards at the top belongs to the file after it; past the last + * section, the last file. + */ + const currentIndex = (viewport: HTMLElement): number => { + const remembered = jumpPosition.current + const index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop + ? files.findIndex(file => file.path === treeState.selected) : -1 + if (index >= 0) return index + const top = viewport.getBoundingClientRect().top + const reading = files.findIndex((file) => { + const section = sections.current.get(file.path) + return section !== undefined && section.getBoundingClientRect().bottom > top + 1 + }) + return reading >= 0 ? reading : Math.max(0, files.length - 1) + } + /** Whether a key press belongs to a field, a comment, a menu, or a text selection rather than to the file list. */ + const typing = (container: HTMLElement, origin: EventTarget): boolean => { + const selection = window.getSelection() + return !(origin instanceof HTMLElement) || !container.contains(origin) + || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment], [role="menu"]') !== null + || (selection !== null && !selection.isCollapsed) + } const navigateFiles = (event: KeyboardEvent): void => { if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) return const viewport = event.currentTarget - const origin = event.target - const selection = window.getSelection() - if (!(origin instanceof HTMLElement) || !viewport.contains(origin) - || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment]') !== null - || (selection !== null && !selection.isCollapsed)) return - const remembered = jumpPosition.current - let index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop - ? files.findIndex(file => file.path === treeState.selected) : -1 - if (index < 0) { - const top = viewport.getBoundingClientRect().top - index = Math.max(0, files.findLastIndex((file) => { - const section = sections.current.get(file.path) - return section !== undefined && section.getBoundingClientRect().top <= top + 1 - })) - } + if (typing(viewport, event.target)) return + const index = currentIndex(viewport) event.preventDefault() event.stopPropagation() const next = files[index + (event.key === 'ArrowRight' ? 1 : -1)] @@ -605,6 +729,89 @@ export function ChangesTab({ viewport.focus({ preventScroll: true }) jump(next.path) } + /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */ + const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => { + if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { + report('viewed.saveFailed') + return + } + const section = sections.current.get(file.path) + const viewport = scrollport.current + if (viewed && section !== undefined && viewport !== null + && section.getBoundingClientRect().top < viewport.getBoundingClientRect().top) setWanted(file.path) + // A new mark collapses the file through its default; clearing a mark expands it. + setChosen(({ [file.path]: _choice, ...value }) => viewed ? value : { ...value, [file.path]: true }) + } + /** The shown file whose section holds an element or a text node, if any. */ + const fileAt = (target: EventTarget | null | undefined): ForgeDiffFile | undefined => { + const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null + const path = element?.closest('[data-forge-diff-file]')?.getAttribute('data-forge-diff-file') + return files.find(file => file.path === path) + } + // `V` marks or clears the file being read, from anywhere in the tab except fields, comments, and menus: the file + // holding the focus, else the one holding the text cursor, as after clicking its code, else the file at the top. + const toggleViewed = (event: KeyboardEvent): void => { + const viewport = scrollport.current + if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey + || event.key.toLowerCase() !== 'v' || viewport === null || data === null || typing(event.currentTarget, event.target)) return + const file = fileAt(event.target) ?? fileAt(window.getSelection()?.anchorNode) ?? files[currentIndex(viewport)] + /* v8 ignore next -- the files region renders only while files show, so its position always names one */ + if (file === undefined) return + event.preventDefault() + markViewed(data, file, viewedStateOf(marks, file.path, file.digest) !== 'viewed') + } + + // What the section handlers and comment actions read when they run, replaced on every render. The assignment happens + // during render rather than in an effect because the file menus read their actions while this same render draws them; + // an effect would hand them the previous diff's links. A render React discards leaves values derived from the same + // props and state, which the retried render assigns again. + const live = useRef({ data, expandedByDefault, expand, markViewed, fileActions, publishReview, report, t }) + live.current = { data, expandedByDefault, expand, markViewed, fileActions, publishReview, report, t } + const handlers = useMemo((): DiffFileHandlers => ({ + toggle: (file) => { + const byDefault = live.current.expandedByDefault(file) + setChosen(value => ({ ...value, [file.path]: !(value[file.path] ?? byDefault) })) + }, + reveal: (path) => { setRevealed(value => new Set([...value, path])) }, + expand: (file, index) => { + const { data: owner, expand: open } = live.current + /* v8 ignore next -- sections render only while changes are loaded */ + if (owner !== null) open(owner, file, index) + }, + view: (file, viewed) => { + const { data: owner, markViewed: mark } = live.current + /* v8 ignore next -- sections render only while changes are loaded */ + if (owner !== null) mark(owner, file, viewed) + }, + actions: (file) => { + const { data: owner, fileActions: list } = live.current + /* v8 ignore next -- sections render only while changes are loaded */ + return owner === null ? [] : list(owner, file) + }, + section: (path, element) => { + if (element === null) sections.current.delete(path) + else sections.current.set(path, element) + }, + reach, + }), [reach]) + const reviewStarted = reviewState.comments.length > 0 + const publishingBlocked = reviewState.uncertain !== null + // Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments. + const publishable = data?.kind === 'change' && data.commits === null + const fileReview = useMemo((): ReviewActions | undefined => shownSource === null ? undefined : { + source: shownSource, + addToInput: addReviewToInput, + records: queue, openLink, reviewStarted, + onQuoted: (selection) => { if (!queue.recordAgent(selection)) live.current.report('review.saveFailed') }, + publishingBlocked, + ...publishable ? { + queue: selection => queue.add(selection), + publish: selection => selection.source.kind === 'change' + ? live.current.publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, + url => queue.published(selection, url)) + : Promise.resolve(live.current.t('review.stale')), + } : {}, + }, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, publishable]) let body: ReactNode if (data === null) { @@ -635,10 +842,12 @@ export function ChangesTab({ } } else if (data.files.length === 0) { body =
    {orphanRecords}
    {t('diff.empty')}
    + } else if (files.length === 0) { + body =
    {orphanRecords}
    {t('lens.empty')}
    } else { body = ( -
    { if (jumpPosition.current?.top !== event.currentTarget.scrollTop) jumpPosition.current = null }}> @@ -649,36 +858,18 @@ export function ChangesTab({ key={path} visible={tab.visible} file={file} - review={{ source: reviewSourceOf(data), - addToInput: addReviewToInput, - records: queue, openLink, reviewStarted: reviewState.comments.length > 0, - onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, - publishingBlocked: reviewState.uncertain !== null, - ...data.kind === 'local' ? {} : { - queue: selection => queue.add(selection), - publish: selection => selection.source.kind === 'change' - ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, - url => queue.published(selection, url)) - : Promise.resolve(t('review.stale')), - }, - }} - expanded={chosen[path] ?? initial.has(path)} - onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? initial.has(path)) })) }} + review={fileReview} + expanded={isExpanded(file)} large={drawnLines(file) > LARGE_FILE_LINES} revealed={revealed.has(path)} - onReveal={() => { setRevealed(value => new Set([...value, path])) }} text={current.texts[path]} open={current.open[path] ?? NO_GAPS} - onExpand={(index) => { expand(data, file, index) }} split={split} wrap={wrap} badge={badgeOf(file, data, t)} tooltip={pathTooltipOf(file, t)} - actions={fileActions(data, file)} - sectionRef={(element) => { - if (element === null) sections.current.delete(path) - else sections.current.set(path, element) - }} + viewed={viewedStateOf(marks, path, file.digest)} + handlers={handlers} t={t} /> ) @@ -694,7 +885,7 @@ export function ChangesTab({ jump, } // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise. - const anyExpanded = files.some(file => chosen[file.path] ?? initial.has(file.path)) + const anyExpanded = files.some(isExpanded) const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll') const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft') let additions = 0 @@ -703,13 +894,22 @@ export function ChangesTab({ additions += file.additions deletions += file.deletions } + const viewedCount = files.filter(file => viewedStateOf(marks, file.path, file.digest) === 'viewed').length + const treeShown = allFiles.length > 0 && treePosition !== 'hidden' + const lensProps = { lens, counts: lensCounts, hideTests, choose: (next: ChangesLens) => { actions.lensed(tab.id, next) }, t } + const commitMenu = source.kind === 'local' && scope !== 'branch' ? null : { actions.committed(tab.id, next) }} t={t} /> + const toolbarStyle: CSSProperties & { '--forge-tree-width': string } = { '--forge-tree-width': `${treeWidth}px` } return ( -
    +
    {source.kind === 'local' ? { actions.based(tab.id, next) }} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} + diffBases={diffBases} choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu} + createChangeRequest={createChangeRequest} t={t} /> + : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
    {t('review.unknown')} @@ -718,45 +918,58 @@ export function ChangesTab({
    } {!reviewOpen && reviewError !== null && reviewState.uncertain === null && {reviewError}} -
    - {tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } - {files.length > 0 && } - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + - + {allFiles.length > 0 && } +
    {data !== null && failed !== null && ( {body} - {files.length > 0 && } + {allFiles.length > 0 && }
    ) diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css new file mode 100644 index 0000000000..5cf60040eb --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css @@ -0,0 +1,139 @@ +/* Commit picker trigger in the changes header and its menu of commits, oldest first. */ +.anchor { + flex: 0 1 auto; + min-width: 0; +} + +.trigger { + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + box-sizing: border-box; + min-width: 0; + max-width: 100%; + height: 28px; + padding: 0 6px 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.chosen .triggerName { + font-family: var(--ds-font-family-code); +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .trigger:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; +} + +.trigger svg { + flex: none; +} + +.triggerName { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.menu { + width: min(400px, calc(100vw - 24px)); +} + +.rows { + max-height: 360px; + overflow: auto; + padding: 4px; + color: var(--dsw-alias-label-primary); + font-size: 12px; +} + +.option { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-width: 0; +} + +.allTitle { + flex: 1; + min-width: 0; +} + +.sha { + flex: none; + color: var(--dsw-alias-label-secondary); + font-family: var(--ds-font-family-code); +} + +.title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.meta { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; +} + +.check { + display: inline-flex; + flex: none; + color: var(--dsw-alias-state-business-primary); +} + +.unchecked { + visibility: hidden; +} + +.label { + padding: 6px 8px 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 8px; + color: var(--dsw-alias-label-secondary); +} + +.note { + padding: 8px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; +} + +/* Why a Shift click left the shown commits unchanged; outside the scrolled rows so it stays in view. */ +.rejected { + padding: 8px 12px; + border-top: 0.5px solid var(--dsw-alias-border-l3); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; +} diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx new file mode 100644 index 0000000000..17ba7fbd89 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx @@ -0,0 +1,186 @@ +/** + * Commit picker of the changes header: every commit, or one commit, or with Shift a run of consecutive commits of a + * change request or of the local `branch` scope, listed oldest first like the code host's commit list. A run is + * accepted only when each of its commits has the one listed before it as its first parent. + */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, Menu, MenuItemButton, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { rangeStart } from '../commit-range.ts' +import type { ForgeCommitRange, ForgeLocalCommits } from '../types.ts' +import { formatAgo } from './format.ts' +import type { NS } from './locales.ts' +import css from './CommitMenu.module.css' + +/** Characters of a commit object name the picker shows. */ +const SHORT = 7 + +/** Props of the commit picker. */ +export interface CommitMenuProps extends PropsLocale { + /** Commits shown, or null for all of them. */ + readonly chosen: ForgeCommitRange | null + /** Whether the owning tab is visible; a hidden tab keeps the menu closed. */ + readonly visible: boolean + /** Read the commits; null means the source cannot show single commits. `signal` aborts the read. */ + readonly list: (signal: AbortSignal) => Promise> + /** Which commits a truncated list keeps: a change request lists its oldest ones, the local branch its newest ones. */ + readonly kept: 'oldest' | 'newest' + /** Changes when the commits may have changed, such as a new head commit or a refresh; the commits are read once per value. */ + readonly version: string + /** Show consecutive commits, or every commit for null. */ + readonly choose: (commits: ForgeCommitRange | null) => void +} + +/** + * Name the shown commits on the trigger. + * @param chosen - the shown commits, or null for all of them. + * @param t - forge panel copy. + * @returns the label. + */ +export function commitsLabel(chosen: ForgeCommitRange | null, t: PropsLocale['t']): string { + if (chosen === null) return t('commits.all') + if (chosen.from === chosen.to) return chosen.from.slice(0, SHORT) + return t('commits.range', { from: chosen.from.slice(0, SHORT), to: chosen.to.slice(0, SHORT) }) +} + +/** + * Render the trigger and, while open, the commit list. A click shows one commit; a Shift click shows the commits + * from the last commit clicked without Shift to the clicked one. + * @param props - the shown commits, the listing read, the choose action, and copy. + * @returns the trigger with its portalled menu, or nothing when the source cannot show single commits. + */ +export function CommitMenu({ chosen, visible, list, kept, version, choose, t }: CommitMenuProps): ReactNode { + const [open, setOpen] = useState(false) + const [attempt, setAttempt] = useState(0) + const [rejected, setRejected] = useState(false) + const [listing, setListing] = useState<{ + readonly key: string + readonly result: RemoteResult + } | null>(null) + const shift = useRef(false) + const anchor = useRef(chosen?.from ?? null) + const loaded = useRef(null) + const shown = visible && open + const key = `${version}\n${String(attempt)}` + const current = listing?.key === key ? listing.result : null + // The list is read once per version, which also tells whether the source has commits to pick, and again on a retry. + useEffect(() => { + if (!visible || loaded.current === key) return + const controller = new AbortController() + void list(controller.signal).then((result) => { + if (controller.signal.aborted) return + loaded.current = key + setListing({ key, result }) + }) + return () => { controller.abort() } + }, [visible, key, list]) + if (current?.ok === true && current.value === null) return null + const commits = current?.ok === true && current.value !== null ? current.value : null + const close = (): void => { + setOpen(false) + setRejected(false) + } + const pick = (sha: string | null): void => { + if (sha === null || commits === null) { + close() + anchor.current = null + if (chosen !== null) choose(null) + return + } + const order = commits.commits.map(commit => commit.sha) + const start = shift.current && anchor.current !== null && order.includes(anchor.current) ? anchor.current : sha + const [from, to] = order.indexOf(start) <= order.indexOf(sha) ? [start, sha] : [sha, start] + // Two ends cannot name a run that leaves the first-parent line, so the menu stays open and says why. + if (rangeStart(commits.commits, { from, to }) === 'not-linear') { + setRejected(true) + return + } + close() + if (!shift.current || start === sha) anchor.current = sha + if (from !== chosen?.from || to !== chosen.to) choose({ from, to }) + } + const inChosen = (index: number): boolean => { + if (chosen === null || commits === null) return false + const order = commits.commits.map(commit => commit.sha) + return index >= order.indexOf(chosen.from) && index <= order.indexOf(chosen.to) && order.includes(chosen.from) + } + + let body: ReactNode + if (current === null) { + body =
    {t('commits.loading')}
    + } else if (!current.ok || commits === null) { + body = ( +
    + {t('commits.failed')} + +
    + ) + } else { + const now = Date.now() + body = <> + { pick(null) }}> + + {t('commits.all')} + {t('commits.count', { count: commits.commits.length })} + {chosen === null && } + + + {commits.commits.length > 0 &&
    {t('commits.shiftHint')}
    } + {commits.commits.map((commit, index) => { + const selected = inChosen(index) + return ( + { pick(commit.sha) }}> + + {commit.sha.slice(0, SHORT)} + {commit.title} + {formatAgo(commit.authoredAt, now, t) ?? ''} + + + + ) + })} + {commits.truncated && ( +
    + {t(kept === 'oldest' ? 'commits.truncatedOldest' : 'commits.truncatedNewest', { count: commits.commits.length })} +
    + )} + + } + + const label = commitsLabel(chosen, t) + return ( + + + + )} + > + {/* Rows report activation without the event, so the modifier is read while the click or key travels to them. */} +
    { shift.current = event.shiftKey }} + onKeyDownCapture={(event) => { shift.current = event.shiftKey }}> + {body} +
    + {rejected &&
    {t('commits.notLinear')}
    } +
    + ) +} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index eb7e21e6b0..10a039cc6d 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -1,20 +1,22 @@ /** * One file of the changes view: a sticky header with the path, badges, line * counts, and file actions, then its hunks unified or side by side with the - * unchanged lines between them collapsed into rows that expand them. + * unchanged lines between them collapsed into rows that expand them. A section + * draws and highlights its lines once it comes within reach of the scrollport; + * it redraws only when its own props change. */ -import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' import clsx from 'clsx' import { flushSync } from 'react-dom' import { FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, - Tooltip, + Tag, Tooltip, languageForPath, Menu, MenuItemButton, useCodeHighlighter, type CodeHighlighter, type HighlightSpan, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeDiffFile } from '../types.ts' -import { segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } from './diff-rows.ts' +import { drawnLines, segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } from './diff-rows.ts' import { codeSideAt, readCodeSelection } from './code-selection.ts' import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -23,6 +25,8 @@ import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx' import reviewCss from './ReviewComposer.module.css' import { FileLabel } from './FileLabel.tsx' import type { ForgePanelKey, NS } from './locales.ts' +import type { ViewedState } from './viewed-files.ts' +import type { SectionReach } from './section-reach.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -38,30 +42,45 @@ export interface DiffFileAction { /** New side of a file: its lines once read, `loading` while a read runs, or undefined before any. */ export type DiffFileText = readonly string[] | 'loading' | undefined +/** + * What every file section of one changes view calls. The view passes the same + * object on every render, so a section redraws only when its own values change. + */ +export interface DiffFileHandlers { + /** Expand or collapse a file. */ + readonly toggle: (file: ForgeDiffFile) => void + /** Show a large file anyway. */ + readonly reveal: (path: string) => void + /** Expand one gap of a file. */ + readonly expand: (file: ForgeDiffFile, index: number) => void + /** Mark a file viewed, which also collapses it, or clear the mark. */ + readonly view: (file: ForgeDiffFile, viewed: boolean) => void + /** Rows of a file's menu, read whenever the menu draws. */ + readonly actions: (file: ForgeDiffFile) => readonly DiffFileAction[] + /** Receive a file's section element, which scrolling to the file targets, or null once it unmounts. */ + readonly section: (path: string, element: HTMLElement | null) => void + /** Tells each expanded section when it comes within reach of the scrollport, which draws its lines. */ + readonly reach: SectionReach +} + /** Props of one file section. */ export interface DiffFileProps { /** Whether the owning tab is visible and may show temporary menus. */ readonly visible: boolean /** Comment destinations and the source being reviewed. */ - readonly review?: ReviewActions + readonly review?: ReviewActions | undefined /** The file and its hunks. */ readonly file: ForgeDiffFile /** Whether the section shows its lines. */ readonly expanded: boolean - /** Expand or collapse the section. */ - readonly onToggle: () => void /** Whether the file shows the large-file notice instead of its lines until revealed. */ readonly large: boolean /** Whether the user revealed a large file. */ readonly revealed: boolean - /** Show a large file anyway. */ - readonly onReveal: () => void /** The file's new side, which supplies collapsed unchanged lines. */ readonly text: DiffFileText /** Indexes of the expanded gaps. */ readonly open: ReadonlySet - /** Expand one gap. */ - readonly onExpand: (index: number) => void /** Whether deletions and additions show in two columns; a file with only additions or only deletions keeps one. */ readonly split: boolean /** Whether long lines wrap. */ @@ -70,10 +89,10 @@ export interface DiffFileProps { readonly badge: string /** Hover text of the path: both paths of a renamed file, else the path. */ readonly tooltip: string - /** Rows of the file's menu. */ - readonly actions: readonly DiffFileAction[] - /** Receives the section element, which scrolling to the file targets. */ - readonly sectionRef: (element: HTMLElement | null) => void + /** Whether the reader marked this change viewed, or marked an earlier change of the file. */ + readonly viewed: ViewedState + /** Actions shared by every section of the view. */ + readonly handlers: DiffFileHandlers /** Forge panel copy. */ readonly t: Translate } @@ -139,8 +158,8 @@ function pairKind(pair: SplitRow): 'context' | 'change' { } /** The hunks of one file with their collapsed and expanded unchanged lines. */ -function Lines({ file, text, open, onExpand, split, wrap, review, visible, comments, t }: Pick & { readonly comments: FileReviewState }): ReactNode { +function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, t }: Pick & { readonly comments: FileReviewState }): ReactNode { const lines = typeof text === 'object' ? text : undefined const columns = split && file.additions > 0 && file.deletions > 0 const singleSide = file.status === 'added' ? 'R' : file.status === 'deleted' ? 'L' : null @@ -313,7 +332,7 @@ function Lines({ file, text, open, onExpand, split, wrap, review, visible, comme for (const [at, segment] of prepared.entries()) { if (segment.kind === 'gap') { rows.push() @@ -369,8 +388,13 @@ function Lines({ file, text, open, onExpand, split, wrap, review, visible, comme }}>{rows}
    } +/** Whether a file's body draws its hunks line by line rather than a note or a collapsed strip. */ +function drawsLines(file: ForgeDiffFile, large: boolean, revealed: boolean): boolean { + return !file.binary && !file.oversized && file.hunks.length > 0 && (!large || revealed) +} + function Body(props: DiffFileProps): ReactNode { - const { file, large, revealed, onReveal, review, t } = props + const { file, large, revealed, handlers, review, t } = props const comments = useFileReview(review, file.path) const records = review === undefined ? null : comments.threads.map(thread => ) @@ -380,7 +404,7 @@ function Body(props: DiffFileProps): ReactNode { if (large && !revealed) { // A large file starts as one collapsed strip, drawn and opened like the collapsed unchanged lines. return ( - <>{records} @@ -390,9 +414,10 @@ function Body(props: DiffFileProps): ReactNode { } /** File actions live only while their owning tab is visible. */ -function FileMenu({ name, actions, t }: { +function FileMenu({ name, file, handlers, t }: { readonly name: string - readonly actions: readonly DiffFileAction[] + readonly file: ForgeDiffFile + readonly handlers: DiffFileHandlers readonly t: Translate }): ReactNode { const [menuOpen, setMenuOpen] = useState(false) @@ -417,7 +442,7 @@ function FileMenu({ name, actions, t }: { )} > - {actions.map(action => ( + {handlers.actions(file).map(action => ( { @@ -433,35 +458,63 @@ function FileMenu({ name, actions, t }: { } /** - * Render one file of a diff. - * @param props - the file, its section and gap state, layout choices, menu actions, and copy. + * Render one file of a diff. Until the section first comes within reach of the scrollport, an expanded file that + * draws lines shows a box of about their height instead. + * @param props - the file, its section and gap state, layout choices, shared actions, and copy. * @returns the file section. */ -export function DiffFile(props: DiffFileProps): ReactNode { - const { file, expanded, onToggle, badge, tooltip, actions, sectionRef, t } = props +function DiffFileSection(props: DiffFileProps): ReactNode { + const { file, expanded, large, revealed, badge, tooltip, viewed, handlers, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) + const element = useRef(null) + const [reached, setReached] = useState(false) + const waiting = expanded && !reached && drawsLines(file, large, revealed) + useEffect(() => { + /* v8 ignore next -- React attaches the section before it runs effects */ + if (!waiting || element.current === null) return + return handlers.reach.observe(element.current, () => { setReached(true) }) + }, [waiting, handlers.reach]) + const sectionRef = useCallback((node: HTMLElement | null) => { + element.current = node + handlers.section(file.path, node) + }, [handlers, file.path]) + const placeholder: CSSProperties & { '--forge-rows': number } = { '--forge-rows': drawnLines(file) } return ( -
    +
    - - - + + + + + + {viewed === 'changed' && ( + {t('viewed.changed')} + )} + + {badge !== '' && {badge}} - - {badge !== '' && {badge}} {!file.binary && } - {props.visible && } + + {props.visible && }
    - {expanded && } + {expanded && (waiting ?
    : )}
    ) } + +/** One file of a diff, redrawn only when its props change. */ +export const DiffFile = memo(DiffFileSection) diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx index b055655814..a4995615f1 100644 --- a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx @@ -15,12 +15,14 @@ export type FileTreePosition = 'right' | 'left' | 'hidden' /** * Render a keyboard- and pointer-resizable tree beside the diff. - * @param props - tree rows, pane position, and the toggle's controlled element id. + * @param props - tree rows, pane position, the toggle's controlled element id, and the receiver of the shown width. * @returns the bounded pane and its resize separator. */ -export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { +export function FileTreePane({ position, id, onWidth, ...props }: ChangedFilesProps & { readonly position: FileTreePosition readonly id: string + /** Receives the pane's width in pixels whenever it changes, so the toolbar can align a cell with it. */ + readonly onWidth: (width: number) => void }): ReactNode { const pane = useRef(null) const drag = useRef<{ pointer: number; x: number; width: number } | null>(null) @@ -41,6 +43,7 @@ export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { return () => { observer.disconnect() } }, []) const shown = Math.min(width, maximum) + useLayoutEffect(() => { onWidth(shown) }, [shown, onWidth]) const direction = position === 'left' ? 1 : -1 const resize = (next: number): void => { setWidth(Math.round(Math.max(MIN_WIDTH, Math.min(maximum, next)))) } return
    @@ -93,9 +96,11 @@ None. Provider output reaches only host-side watchers. - **GitHub CLI on the host** — `gh` must be installed and signed in for each configured host; tokens in environment variables are not forwarded. Hosts missing from `hosts` are never read, including references retained across configuration changes. A status fetch returns `unavailable` for those references; a head lookup rejects before starting `gh`. -- **First 100 review threads** — unresolved threads after the first 100 are not counted. +- **Review thread bound** — a status read counts at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks. +- **Batch deadline** — continuation pages of a pull request with many review threads lengthen its host's polling batch; a batch that outlives `ctx.forge`'s `fetchTimeoutMs` reports `unavailable` for every pull request in it, not only for the one with many threads. +- **Rewritten base branch** — the diff starts from the merge base of the head and the base commit GitHub recorded at the pull request's last update. After the base branch is force-pushed, that merge base can differ from the one GitHub's pull request view uses, so the patch can include or omit commits until the pull request is updated. - **No fork discovery** — head lookups exclude pull requests whose head is in another repository. -- **Rate limits** — every poll costs one GraphQL query per host, plus one query per additional page of 100 check records, against the signed-in account’s rate limit. +- **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request, and a second REST request when the base commit changed after the latest status. All count against the signed-in account’s rate limit. - **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 1ac57ffa7d..d867f19592 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -34,17 +34,19 @@ kind: "package-reference" hosts: [github.com, ghe.example.com] ``` -即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs` 与 `maxOutputBytes` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 +即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes`、`maxReviewThreads` 与 `maxCommits` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads` 与 `maxCommits` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 -轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。 +轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应(包括评审讨论分页)的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。 + +每次状态读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响;不发布不完整的计数。 未完成的检查运行(check run),以及结论已过期、缺失或无法识别的已完成运行,均映射为 `pending`。其他已完成的检查映射为 `success`、`failure`(失败、超时、启动失败或需要操作)、`cancelled`、`skipped` 或 `neutral`。已取消的检查使汇总保持未通过状态。检查运行保留其开始与完成时间。提交状态上下文把 `SUCCESS` 映射为 `success`,把 `FAILURE` 与 `ERROR` 映射为 `failure`,其余状态均映射为 `pending`,且不带时间。GraphQL 的 `NOT_FOUND` 错误转为 `not-found` 失败。响应不含 GraphQL data 或 errors 时(包括 HTTP 错误 JSON),使用 stderr 的首条诊断或响应体的 message。认证诊断转为 `unauthenticated`;超出输出大小上限的检查分页转为 `too-large`;限流与其他失败转为 `unavailable`。head 查找在拒绝时保留相同诊断。 pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。每个状态快照把 `baseRefOid` 作为 `baseSha` 携带(GitHub 返回的不是完整提交时省略);拿到它时,`diff` 在 GraphQL 查询确认 head 的同时就开始这次比较,head 已过时或基准提交不同时会取消提前开始的比较并等它结束,然后才返回。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 @@ -63,8 +65,9 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 | [`src/index.ts`](src/index.ts) | 配置校验与提供方注册 | | [`src/provider.ts`](src/provider.ts) | URL 映射、按主机分组与失败分类 | | [`src/graphql.ts`](src/graphql.ts) | 构造查询,并校验和映射响应 | +| [`src/compare.ts`](src/compare.ts) | 经 compare API 读取两个提交之间的补丁,供所有 diff 读取共用 | | [`src/gh.ts`](src/gh.ts) | 在宿主上执行 `gh`,清理环境变量并施加限制 | -| [`src/urls.ts`](src/urls.ts) | 解析远端 URL 与 pull request URL | +| [`src/urls.ts`](src/urls.ts) | 解析远端 URL 与 pull request URL,并校验写入请求的名称与提交 |
    @@ -93,9 +96,11 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 - **宿主需要 GitHub CLI**——必须安装 `gh` 并为每个已配置主机登录;环境变量中的令牌不会被转发。不在 `hosts` 中的主机永远不会被读取,包括配置变更后保留的引用。状态读取为这些引用返回 `unavailable`;head 查找会在启动 `gh` 前拒绝。 -- **前 100 个评审讨论**——前 100 个之后的未解决讨论不计入。 +- **评审讨论上限**——每次状态读取每个 pull request 最多统计 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出。 +- **批次时限**——评审讨论很多的 pull request 的续页会拉长其主机的轮询批次;批次超过 `ctx.forge` 的 `fetchTimeoutMs` 时,批次内每个 pull request 都报告 `unavailable`,而不只是讨论很多的那个。 +- **基准分支被改写**——diff 从 head 与 GitHub 在 pull request 最后一次更新时记录的基准提交的合并基准开始。基准分支被强制推送后,该合并基准可能不同于 GitHub pull request 页面使用的合并基准,因此在 pull request 更新前,补丁可能多出或缺少提交。 - **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。 -- **速率限制**——每次轮询以已登录账号的速率配额为每个主机消耗一次 GraphQL 查询;检查记录每多一页(100 条),再消耗一次查询。 +- **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求;最新状态之后基准提交有变化时再多一次 REST 请求。这些都计入已登录账号的速率配额。 - **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。 diff --git a/packages/experimental/forge-github/src/commits.ts b/packages/experimental/forge-github/src/commits.ts new file mode 100644 index 0000000000..e00c101571 --- /dev/null +++ b/packages/experimental/forge-github/src/commits.ts @@ -0,0 +1,102 @@ +/** GitHub pull request commit listing through GraphQL, pinned to one head commit across pages. */ + +import type { ChangeRequestRef, ForgeCommit, ForgeCommitList, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import { checkedRepository } from './urls.ts' + +/** Commits GitHub returns per GraphQL page, its connection maximum. */ +const PAGE = 100 + +/** One page of a pull request's commits with its head; `cursor` continues after the previous page. */ +export const COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + headRefOid + commits(first: $first, after: $cursor) { + totalCount + pageInfo { hasNextPage endCursor } + nodes { commit { oid messageHeadline authoredDate author { name user { login } } parents(first: 1) { nodes { oid } } } } + } + } + } +}` + +const pageSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ + headRefOid: z.string(), + commits: z.object({ + totalCount: z.number().int().nonnegative(), + pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), + nodes: z.array(z.object({ + commit: z.object({ + oid: z.string(), + messageHeadline: z.string(), + authoredDate: z.string(), + author: z.object({ name: z.string().nullable(), user: z.object({ login: z.string() }).nullable() }).nullable(), + parents: z.object({ nodes: z.array(z.object({ oid: z.string() })) }), + }), + })), + }), + }).nullable(), + }).nullable(), + }), +}) + +/** Runs one `gh` GraphQL request; resolves to its parsed JSON body, or why GitHub did not answer it. */ +export type GraphqlReader = (args: readonly string[], signal: AbortSignal) => Promise< + { readonly ok: true; readonly body: unknown } | { readonly ok: false; readonly failure: ForgeFailure }> + +/** + * List a pull request's commits oldest first, at most `limit`, reading pages until the limit or the last commit. + * Every page must report the head and commit count of the first page, so the list never mixes two pushes, and a cursor + * no earlier page returned, so the listing ends. + * @param read - runs one GraphQL request. + * @param ref - validated pull request address. + * @param limit - most commits listed. + * @param signal - cancellation of every page. + * @returns the commits at one head, or why GitHub did not list them. + */ +export async function listCommits( + read: GraphqlReader, + ref: ChangeRequestRef, + limit: number, + signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const commits: ForgeCommit[] = [] + const cursors = new Set() + let first: { readonly head: string; readonly total: number } | undefined + let cursor: string | null = null + for (;;) { + const body = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE, limit - commits.length)}`, + ...cursor === null ? [] : ['-f', `cursor=${cursor}`], + ], signal) + if (!body.ok) return body.failure + const parsed = pageSchema.safeParse(body.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the commit listing' } + const pull = parsed.data.data.repository?.pullRequest + if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` } + const { headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage, endCursor } } } = pull + first ??= { head, total } + if (head !== first.head || total !== first.total) { + return { code: 'unavailable', message: 'The pull request head changed while its commits were read' } + } + for (const { commit } of pull.commits.nodes) { + commits.push({ + sha: commit.oid, + parent: commit.parents.nodes[0]?.oid ?? null, + title: commit.messageHeadline, + author: commit.author?.user?.login ?? commit.author?.name ?? null, + authoredAt: commit.authoredDate, + }) + } + if (!hasNextPage || commits.length >= limit) return { headSha: head, commits, truncated: total > commits.length } + if (endCursor === null || cursors.has(endCursor)) return { code: 'unavailable', message: 'GitHub commit pagination did not advance' } + cursors.add(endCursor) + cursor = endCursor + } +} diff --git a/packages/experimental/forge-github/src/compare.ts b/packages/experimental/forge-github/src/compare.ts new file mode 100644 index 0000000000..3598b4f807 --- /dev/null +++ b/packages/experimental/forge-github/src/compare.ts @@ -0,0 +1,43 @@ +/** Reads GitHub's patch between two commits through the REST compare endpoint. */ + +import type { ForgeFailure, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge' +import { isCommit } from './urls.ts' + +/** Runs one reading `gh` command and maps a refusal to a failure, as the provider's reads do. */ +export type GhTextReader = (args: readonly string[], signal: AbortSignal) => Promise + +/** `gh` option that prints a response containing terminal escape sequences; `gh` 2.97 added it. */ +const ALLOW_ESCAPES = '--allow-escape-sequences' + +/** What a `gh` older than 2.97 reports for {@link ALLOW_ESCAPES}, before it sends any request. */ +const UNKNOWN_ALLOW_ESCAPES = `unknown flag: ${ALLOW_ESCAPES}` + +/** + * Read the unified patch from the merge base of `base` and `head` to `head`, as + * GitHub computes the diff of a pull request with that base and head commit. + * Both ends are commit object names, so the answer never follows a moving + * branch. The patch keeps terminal escape sequences that file contents hold: + * `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`, + * and an older `gh`, which rejects that option, prints them unchanged, so a + * rejection of the option alone repeats the read without it. + * GitHub returns the patch however many files it changes; `read` bounds its size. + * @param read - runs `gh` with the provider's output limit and failure mapping. + * @param repository - repository that holds both commits, with an owner and name already checked for inlining. + * @param base - commit whose merge base with `head` starts the patch. + * @param head - commit the patch ends at. + * @param signal - cancellation of the read. + * @returns the patch with `a/` and `b/` path prefixes, or why GitHub did not provide it. + * @throws when `base` or `head` is not a full commit object name. + */ +export async function readComparison( + read: GhTextReader, repository: ForgeRepository, base: string, head: string, signal: AbortSignal, +): Promise { + for (const commit of [base, head]) { + if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + } + const { host, owner, name } = repository + const request = ['-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`] + const patch = await read(['api', '--hostname', host, ALLOW_ESCAPES, ...request], signal) + if (typeof patch === 'string' || !patch.message.startsWith(UNKNOWN_ALLOW_ESCAPES)) return patch + return await read(['api', '--hostname', host, ...request], signal) +} diff --git a/packages/experimental/forge-github/src/graphql.ts b/packages/experimental/forge-github/src/graphql.ts index a7d0a8d16b..ec97758af6 100644 --- a/packages/experimental/forge-github/src/graphql.ts +++ b/packages/experimental/forge-github/src/graphql.ts @@ -7,7 +7,7 @@ import type { Mergeability, MergeMethod, ReviewDecision, } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' -import { checkedRepository } from './urls.ts' +import { checkedRepository, isCommit } from './urls.ts' const CHECK_FIELDS = `pageInfo { hasNextPage endCursor } nodes { @@ -19,17 +19,34 @@ const CHECK_FIELDS = `pageInfo { hasNextPage endCursor } ... on StatusContext { context state targetUrl createdAt } }` -const PULL_REQUEST_FIELDS = `number url title state isDraft updatedAt closedAt +/** Most nodes GitHub returns in one connection page. */ +const PAGE_SIZE = 100 + +const THREAD_FIELDS = 'pageInfo { hasNextPage endCursor } nodes { isResolved }' + +/** + * Pull request fields of one snapshot. + * @param threads - review threads the first page holds, at most {@link PAGE_SIZE}. + * @returns the selection of the snapshot fragment. + */ +function pullRequestFields(threads: number): string { + return `id number url title state isDraft updatedAt closedAt author { login } - headRefName headRefOid baseRefName additions deletions mergeable mergeStateStatus reviewDecision - reviewThreads(first: 100) { nodes { isResolved } } - commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: 100) { + headRefName headRefOid baseRefName baseRefOid additions deletions mergeable mergeStateStatus reviewDecision + reviewThreads(first: ${threads}) { ${THREAD_FIELDS} } + commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: ${PAGE_SIZE}) { ${CHECK_FIELDS} } } } } }` +} /** Continue reading the same commit's rollup even if the pull request head moves. */ export const CHECKS_QUERY = `query($id: ID!, $cursor: String!) { - node(id: $id) { ... on StatusCheckRollup { contexts(first: 100, after: $cursor) { ${CHECK_FIELDS} } } } + node(id: $id) { ... on StatusCheckRollup { contexts(first: ${PAGE_SIZE}, after: $cursor) { ${CHECK_FIELDS} } } } +}` + +/** Continue counting a pull request's review threads; variables `id`, `cursor`, and the integer `first`. */ +export const THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) { + node(id: $id) { ... on PullRequest { reviewThreads(first: $first, after: $cursor) { ${THREAD_FIELDS} } } } }` const REPOSITORY_FIELDS = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod' @@ -42,6 +59,11 @@ export const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: Strin } }` +/** Head and base commits of one pull request; variables `owner` and `name` are strings, `number` is an integer. */ +export const PULL_REQUEST_COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid baseRefOid } } +}` + const checkRunSchema = z.object({ __typename: z.literal('CheckRun'), id: z.string(), @@ -66,19 +88,40 @@ const statusContextSchema = z.object({ targetUrl: z.string().nullable(), }) -const checkPageSchema = z.object({ - pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), - nodes: z.array(z.unknown()), -}) +const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }) + +/** Position of a connection page within its connection. */ +type PageInfo = z.infer + +const checkPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.unknown()) }) + +const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.object({ isResolved: z.boolean() })) }) + +/** One validated connection page or a failure that prevents publishing a partial count. */ +export type PageResult = { readonly ok: true; readonly page: T } | { readonly ok: false; readonly failure: ForgeFailure } /** One validated page of check contexts or a failure that prevents publishing a partial count. */ -export type CheckPageResult = { readonly ok: true; readonly page: z.infer } - | { readonly ok: false; readonly failure: ForgeFailure } +export type CheckPageResult = PageResult> + +/** One validated page of review threads or a failure that prevents publishing a partial count. */ +export type ThreadPageResult = PageResult> /** Opaque GitHub node id that pins check pagination to one commit's rollup. */ type RollupId = Branded<'GitHubStatusCheckRollupId'> +/** Opaque GitHub node id of a pull request. */ +type PullRequestId = Branded<'GitHubPullRequestId'> + +/** Continuation reads that complete one snapshot response. */ +export interface SnapshotPages { + /** Read the next page of a pull request's review threads, holding at most `first` threads. */ + readonly threads: (id: PullRequestId, cursor: string, first: number) => Promise + /** Read the next check page of a rollup; omission keeps the first check page with its truncation flag. */ + readonly checks?: (id: RollupId, cursor: string) => Promise +} + const pullRequestSchema = z.object({ + id: z.string().transform(value => value as PullRequestId), url: z.string(), title: z.string(), state: z.enum(['OPEN', 'CLOSED', 'MERGED']), @@ -89,12 +132,14 @@ const pullRequestSchema = z.object({ headRefName: z.string(), headRefOid: z.string(), baseRefName: z.string(), + // Only the diff read's head start uses the base commit, so a missing or malformed one leaves the rest of the status intact. + baseRefOid: z.unknown().transform(value => typeof value === 'string' && isCommit(value) ? value : undefined), additions: z.number().int().nonnegative(), deletions: z.number().int().nonnegative(), mergeable: z.string(), mergeStateStatus: z.string(), reviewDecision: z.string().nullable(), - reviewThreads: z.object({ nodes: z.array(z.object({ isResolved: z.boolean() })) }), + reviewThreads: threadPageSchema, commits: z.object({ nodes: z.array(z.object({ commit: z.object({ @@ -143,6 +188,11 @@ const headSchema = z.object({ }), }) +const pullRequestCommitsSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ + headRefOid: z.string().refine(isCommit), + baseRefOid: z.string().refine(isCommit), +}) }) }) }) + type PullRequestNode = z.infer type RepositoryNode = z.infer @@ -169,16 +219,19 @@ export interface SnapshotQuery { readonly document: string /** Change requests keyed by alias path `r.p`. */ readonly targets: ReadonlyMap + /** Most review threads counted per change request. */ + readonly maxReviewThreads: number } /** * Build one query that reads every change request in `refs`, grouping them by * repository. Owners, names, and numbers are validated before they are inlined. * @param refs - change requests on one host. + * @param maxReviewThreads - positive integer bound on the review threads counted per change request. * @returns the document and its alias targets. * @throws when an owner, name, or number cannot be inlined safely. */ -export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery { +export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThreads: number): SnapshotQuery { const repositories = new Map }>() for (const ref of refs) { const { owner, name } = checkedRepository(ref) @@ -201,22 +254,26 @@ export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery const owner = JSON.stringify(repository.owner) fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(' ')} }`) } - return { document: `query { ${fields.join(' ')} }\nfragment ChangeRequestFields on PullRequest { ${PULL_REQUEST_FIELDS} }`, targets } + const document = `query { ${fields.join(' ')} } +fragment ChangeRequestFields on PullRequest { ${pullRequestFields(Math.min(PAGE_SIZE, maxReviewThreads))} }` + return { document, targets, maxReviewThreads } } /** * Map a snapshot response, including GitHub's partial-error form, into one * result per alias target. Path-scoped errors apply to their repository or * pull request; errors without a path apply to every unresolved target. A - * repository without readable merge settings offers no merge. Polling returns + * repository without readable merge settings offers no merge. Review threads + * are counted across pages up to `query.maxReviewThreads`. Polling returns * the first check page; an explicit detail read can complete its pagination. + * A continuation page that fails or does not advance fails its target. * @param body - parsed JSON printed by `gh api graphql`. * @param query - the query that produced the response. - * @param readChecks - optional detail reader for the same commit; omission returns the first page with its truncation flag. - * @returns a snapshot with its check truncation flag, or a failure, for every target. + * @param pages - continuation reads of review threads and, for a detail read, of checks on the same commit. + * @returns a snapshot with its check and thread truncation flags, or a failure, for every target. */ export async function mapSnapshotResponse( - body: unknown, query: SnapshotQuery, readChecks?: (id: RollupId, cursor: string) => Promise, + body: unknown, query: SnapshotQuery, pages: SnapshotPages, ): Promise> { const results = new Map() const parsed = responseSchema.safeParse(body) @@ -235,23 +292,14 @@ export async function mapSnapshotResponse( const node = pullRequestSchema.safeParse(raw) const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias]) if (node.success) { + const { id, reviewThreads } = node.data const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup - if (rollup !== undefined && rollup !== null) { - const cursors = new Set() - while (readChecks !== undefined && rollup.contexts.pageInfo.hasNextPage) { - const cursor = rollup.contexts.pageInfo.endCursor - if (cursor === null || cursors.has(cursor)) { - results.set(key, { code: 'unavailable', message: 'GitHub check pagination did not advance' }) - break - } - cursors.add(cursor) - const next = await readChecks(rollup.id, cursor) - if (!next.ok) { results.set(key, next.failure); break } - rollup.contexts.nodes.push(...next.page.nodes) - rollup.contexts.pageInfo = next.page.pageInfo - } - } - if (!results.has(key)) results.set(key, toSnapshot(ref, node.data, settings.success ? settings.data : undefined)) + const { checks } = pages + const failure = await readPages(reviewThreads, query.maxReviewThreads, 'review thread', + async (cursor, first) => await pages.threads(id, cursor, first)) + ?? (rollup === undefined || rollup === null || checks === undefined ? undefined + : await readPages(rollup.contexts, Number.POSITIVE_INFINITY, 'check', async cursor => await checks(rollup.id, cursor))) + results.set(key, failure ?? toSnapshot(ref, node.data, settings.success ? settings.data : undefined)) } else if (error !== undefined) results.set(key, { code: error.type === 'NOT_FOUND' ? 'not-found' : 'unavailable', message: error.message }) else if (raw === null || raw === undefined) results.set(key, { code: 'not-found', message: 'pull request not found' }) else results.set(key, { code: 'unavailable', message: 'unexpected pull request fields' }) @@ -259,21 +307,86 @@ export async function mapSnapshotResponse( return results } +/** + * Append the following pages of a connection until it ends or holds `limit` nodes. + * @param connection - first page, extended in place. + * @param limit - most nodes to hold. + * @param label - what the connection lists, for failure messages. + * @param read - reads the page after `cursor`, holding at most `first` nodes. + * @returns a failure that prevents publishing the partial connection, or undefined once it ended or is full. + */ +async function readPages( + connection: { nodes: T[]; pageInfo: PageInfo }, + limit: number, + label: string, + read: (cursor: string, first: number) => Promise>, +): Promise { + const cursors = new Set() + while (connection.pageInfo.hasNextPage && connection.nodes.length < limit) { + const cursor = connection.pageInfo.endCursor + if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: `GitHub ${label} pagination did not advance` } + cursors.add(cursor) + const next = await read(cursor, Math.min(PAGE_SIZE, limit - connection.nodes.length)) + if (!next.ok) return next.failure + connection.nodes.push(...next.page.nodes) + connection.pageInfo = next.page.pageInfo + } + return undefined +} + /** * Validate a continuation response before adding its checks to the snapshot. * @param body - parsed GraphQL response for a rollup node. * @returns the complete page or a failure; partial-error pages are not accepted. */ export function mapCheckPageResponse(body: unknown): CheckPageResult { + return mapPageResponse(body, z.object({ contexts: checkPageSchema }).transform(node => node.contexts), 'check') +} + +/** + * Validate a continuation response of {@link THREADS_QUERY} before counting its review threads. + * @param body - parsed GraphQL response for a pull request node. + * @returns the complete page or a failure; partial-error pages are not accepted. + */ +export function mapThreadPageResponse(body: unknown): ThreadPageResult { + return mapPageResponse(body, z.object({ reviewThreads: threadPageSchema }).transform(node => node.reviewThreads), 'review thread') +} + +/** + * Validate one continuation response of a `node(id:)` query. + * @param body - parsed GraphQL response. + * @param page - schema that maps the node to its connection page. + * @param label - what the connection lists, for failure messages. + * @returns the page, or a failure for an error, a missing node, or unexpected fields. + */ +function mapPageResponse(body: unknown, page: z.ZodType, label: string): PageResult { const parsed = z.object({ - data: z.object({ node: z.object({ contexts: checkPageSchema }).nullable() }).nullable().optional(), + data: z.object({ node: page.nullable() }).nullable().optional(), errors: z.array(z.object({ message: z.string() })).optional(), }).safeParse(body) - if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) { - return { ok: true, page: parsed.data.data.node.contexts } - } + if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) return { ok: true, page: parsed.data.data.node } return { ok: false, failure: { code: 'unavailable', - message: parsed.success ? parsed.data.errors?.[0]?.message ?? 'GitHub check page is unavailable' : 'unexpected GitHub check page' } } + message: parsed.success ? parsed.data.errors?.[0]?.message ?? `GitHub ${label} page is unavailable` : `unexpected GitHub ${label} page` } } +} + +/** Head and base commits of a pull request as one read of {@link PULL_REQUEST_COMMITS_QUERY} named them. */ +export interface PullRequestCommits { + /** Commit at the head of the pull request. */ + readonly head: string + /** Commit of the base branch GitHub recorded with that head, whose merge base with it starts the pull request's diff. */ + readonly base: string +} + +/** + * Map a read of {@link PULL_REQUEST_COMMITS_QUERY}. + * @param body - parsed JSON printed by `gh api graphql`. + * @returns both commits, or undefined when the response does not name them as full commit object names. + */ +export function mapPullRequestCommitsResponse(body: unknown): PullRequestCommits | undefined { + const parsed = pullRequestCommitsSchema.safeParse(body) + if (!parsed.success) return undefined + const { headRefOid, baseRefOid } = parsed.data.data.repository.pullRequest + return { head: headRefOid, base: baseRefOid } } /** @@ -355,6 +468,7 @@ function toSnapshot( headBranch: node.headRefName, headSha: node.headRefOid, baseBranch: node.baseRefName, + ...node.baseRefOid === undefined ? {} : { baseSha: node.baseRefOid }, additions: node.additions, deletions: node.deletions, mergeability: mergeability(node.mergeable), @@ -366,6 +480,7 @@ function toSnapshot( checksRollup: summary, checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false, unresolvedThreads: node.reviewThreads.nodes.filter(thread => !thread.isResolved).length, + threadsTruncated: node.reviewThreads.pageInfo.hasNextPage, updatedAt: node.updatedAt, closedAt: node.closedAt, } diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index a0bc66126a..7daff01956 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -20,6 +20,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 } export const Config: z = z.object({ @@ -27,6 +31,8 @@ export const Config: z = z.object({ hosts: z.array(z.string()).default(['github.com']), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), + maxReviewThreads: z.number().default(1_000), + maxCommits: z.number().default(250), }) const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i @@ -41,8 +47,8 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } - if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) { - throw new Error('forge-github: maxOutputBytes must be a positive safe integer') + for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits'] as const) { + if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } - ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes)) + ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved)) } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index ca56473956..d94a277bb8 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -2,13 +2,20 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, - ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, + ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' +import { listCommits } from './commits.ts' +import type { GraphqlReader } from './commits.ts' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts' import type { GhOutput, GhRunner } from './gh.ts' -import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery } from './graphql.ts' -import { checkedRepository, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' +import { readComparison } from './compare.ts' +import { + CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse, + mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY, +} from './graphql.ts' +import type { PageResult, SnapshotPages } from './graphql.ts' +import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i @@ -17,13 +24,23 @@ const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i const HTTP_STATUS = /\(HTTP (\d{3})\)/ /** - * GitHub's error code for an answer over its size limits, such as a diff over - * 300 files: `gh pr diff` prints it after the field, and `gh api` returns it in the JSON error body. + * GitHub's error code for an answer over its size limits, such as a file over + * the contents API limit: `gh api` returns it in the JSON error body. */ const TOO_LARGE = /\btoo_large\b/ -/** A full SHA-1 or SHA-256 object name. */ -const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i +/** HTTP status GitHub answers when it refuses to render a diff over its limits. */ +const NOT_ACCEPTABLE = '406' + +/** Bounds on what one read retains or counts. */ +export interface GitHubLimits { + /** Maximum combined JSON bytes retained by an explicit check read. */ + readonly maxOutputBytes: number + /** Most review threads counted per pull request in one status read. */ + readonly maxReviewThreads: number + /** Most commits one commit listing returns. */ + readonly maxCommits: number +} /** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */ export class GitHubProvider implements ForgeProvider { @@ -39,9 +56,9 @@ export class GitHubProvider implements ForgeProvider { /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. - * @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read. + * @param limits - bounds on retained check bytes, counted review threads, and listed commits. */ - constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly maxOutputBytes: number) { + constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) } @@ -93,10 +110,7 @@ export class GitHubProvider implements ForgeProvider { return results.get(changeRequestKey(ref))! } catch (error) { if (signal.aborted) throw signal.reason - if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) { - return { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message } - } - throw error + return processFailure(error) } } @@ -133,19 +147,56 @@ export class GitHubProvider implements ForgeProvider { const { host, owner, name } = checkedRepository(ref) const failure = this.hostFailure(host) if (failure !== undefined) return { code: 'failed', message: failure.message } - if (!COMMIT.test(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`) + if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`) return await this.act([ 'api', '--hostname', host, '--method', 'PUT', `repos/${owner}/${name}/pulls/${ref.number}/merge`, '-f', `merge_method=${request.method}`, '-f', `sha=${request.headSha}`, ], signal) } - /** Read the pull request's diff with `gh pr diff`, which GitHub computes against the merge base. */ - async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise { + /** + * Read the pull request's diff at `headSha`. One GraphQL read names the + * current head and the base commit GitHub recorded with it; a head other + * than `headSha` returns `stale`. Otherwise the compare endpoint reads the + * patch from the merge base of that base commit and `headSha`, as the pull + * request's own diff does, with both ends fixed. Given the `base` the latest + * status recorded with `headSha`, the comparison from it runs while the + * GraphQL read confirms the head; a stale head or another base commit + * cancels that comparison and waits for it to end before the read returns. + */ + async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise { const { host, owner, name } = checkedRepository(ref) const failure = this.hostFailure(host) if (failure !== undefined) return failure - return await this.read(['pr', 'diff', String(ref.number), '--repo', `${host}/${owner}/${name}`, '--color', 'never'], signal) + if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`) + if (base !== undefined && !isCommit(base)) throw new Error(`forge-github: invalid base commit ${JSON.stringify(base)}`) + const compare = async (from: string, operation: AbortSignal): Promise => + await readComparison(async (args, inner) => await this.read(args, inner), ref.repository, from, headSha, operation) + const speculation = new AbortController() + const early = base === undefined ? undefined : { base, patch: compare(base, AbortSignal.any([signal, speculation.signal])) } + // The early comparison is observed here, so a cancelled or unused one never rejects unhandled. + const settled = early?.patch.then(() => undefined, () => undefined) + const discard = async (): Promise => { + speculation.abort() + await settled + } + try { + const output = await this.read([ + 'api', 'graphql', '--hostname', host, + '-f', `query=${PULL_REQUEST_COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`, + ], signal) + if (typeof output !== 'string') return output + const commits = mapPullRequestCommitsResponse(parseJson(output)) + if (commits === undefined) return { code: 'unavailable', message: 'unexpected GitHub response to the pull request commit read' } + if (commits.head.toLowerCase() !== headSha.toLowerCase()) { + return { code: 'stale', message: `the pull request head moved from ${headSha} to ${commits.head}` } + } + if (early?.base.toLowerCase() === commits.base.toLowerCase()) return await early.patch + await discard() + return await compare(commits.base, signal) + } finally { + await discard() + } } /** Read one file at a commit through the contents API in its raw form. */ @@ -153,13 +204,28 @@ export class GitHubProvider implements ForgeProvider { const { host, owner, name } = checkedRepository(ref) const failure = this.hostFailure(host) if (failure !== undefined) return failure - if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) return await this.read([ 'api', '--hostname', host, '-H', 'Accept: application/vnd.github.raw+json', `repos/${owner}/${name}/contents/${encodedPath(path)}?ref=${commit}`, ], signal) } + /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */ + async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { + const { host } = checkedRepository(ref) + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + return await listCommits(this.graphql, ref, this.limits.maxCommits, signal) + } + + /** Read the changes between two commits through the compare API in its diff form. */ + async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return failure + return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal) + } + fileUrl(ref: ChangeRequestRef, commit: string, path: string): string { const { host, owner, name } = ref.repository return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}` @@ -195,10 +261,21 @@ export class GitHubProvider implements ForgeProvider { if (output.exitCode === 0) return output.stdout const { message, status } = refusal(output) if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message } - if (TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message } + if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message } return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message } } + /** Run one GraphQL request; a refusal, a body that is not GraphQL, and GraphQL errors become failures. */ + private readonly graphql: GraphqlReader = async (args, signal) => { + const output = await this.read(args, signal) + if (typeof output !== 'string') return { ok: false, failure: output } + const body = parseJson(output) + if (!hasGraphqlFields(body)) return { ok: false, failure: { code: 'unavailable', message: 'unexpected GitHub response' } } + const errors = typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors) ? body.errors : [] + if (errors.length > 0) return { ok: false, failure: responseFailure({ exitCode: 0, stdout: output, stderr: '' }, errors[0]) } + return { ok: true, body } + } + /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */ private async act(args: readonly string[], signal: AbortSignal): Promise { const output = await this.attempt(args, signal) @@ -232,34 +309,67 @@ export class GitHubProvider implements ForgeProvider { signal: AbortSignal, completeChecks = false, ): Promise> { - const query = snapshotQuery(refs) + const query = snapshotQuery(refs, this.limits.maxReviewThreads) const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal) const body = parseJson(output.stdout) - if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query) + // A complete check read retains every response it reads, so all of them share one byte budget. let bytes = Buffer.byteLength(output.stdout) const tooLarge: ForgeFailure = { code: 'too-large', message: 'GitHub check details exceed the output size limit' } - if (bytes > this.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) - if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, async (id, cursor) => { - signal.throwIfAborted() - let page: GhOutput - try { - page = await this.gh(['api', 'graphql', '--hostname', host, - '-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], signal) - } catch (error) { - if (signal.aborted) throw signal.reason - if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) { - return { ok: false, failure: { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message } } - } - throw error - } + const overBudget = (page: GhOutput): boolean => { + if (!completeChecks) return false bytes += Buffer.byteLength(page.stdout) - if (bytes > this.maxOutputBytes) return { ok: false, failure: tooLarge } + return bytes > this.limits.maxOutputBytes + } + const continuation = async ( + variables: readonly string[], map: (value: unknown) => PageResult, + ): Promise> => { + const page = await this.continuation(host, variables, signal) + if (!('stdout' in page)) return { ok: false, failure: page } + if (overBudget(page)) return { ok: false, failure: tooLarge } const value = parseJson(page.stdout) - return hasGraphqlFields(value) ? mapCheckPageResponse(value) : { ok: false, failure: responseFailure(page, value) } - }) + return hasGraphqlFields(value) ? map(value) : { ok: false, failure: responseFailure(page, value) } + } + const threads: SnapshotPages['threads'] = async (id, cursor, first) => await continuation( + ['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], mapThreadPageResponse) + if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads }) + if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) + if (hasGraphqlFields(body)) { + return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => await continuation( + ['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], mapCheckPageResponse) }) + } const failure = responseFailure(output, body) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const)) } + + /** + * Run one continuation query of a snapshot read. + * @param host - host the snapshot was read from. + * @param variables - `gh api graphql` field flags, the query first. + * @param signal - cancellation of the snapshot read. + * @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit. + * @throws with `signal.reason` when the read is cancelled. + */ + private async continuation(host: string, variables: readonly string[], signal: AbortSignal): Promise { + signal.throwIfAborted() + try { + return await this.gh(['api', 'graphql', '--hostname', host, ...variables], signal) + } catch (error) { + if (signal.aborted) throw signal.reason + return processFailure(error) + } + } +} + +/** + * Report a `gh` invocation that did not run to an exit code. + * @param error - what the runner threw. + * @returns `too-large` for output over its limit, `unavailable` for a `gh` that cannot start or times out. + * @throws `error` when it is any other failure. + */ +function processFailure(error: unknown): ForgeFailure { + if (error instanceof GhOutputLimitError) return { code: 'too-large', message: error.message } + if (error instanceof GhUnavailableError || error instanceof GhTimeoutError) return { code: 'unavailable', message: error.message } + throw error } /** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */ diff --git a/packages/experimental/forge-github/src/urls.ts b/packages/experimental/forge-github/src/urls.ts index 539abe3a58..a3a2a7f3c3 100644 --- a/packages/experimental/forge-github/src/urls.ts +++ b/packages/experimental/forge-github/src/urls.ts @@ -5,6 +5,9 @@ import type { ChangeRequestRef, ForgeRepository } from '@deepseek-ai/dsh-experim /** Characters GitHub permits in owner and repository names. */ const SEGMENT = /^[A-Za-z0-9_.-]+$/ +/** A full SHA-1 or SHA-256 object name. */ +const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i + /** Host, owner, and repository name addressed by a URL. */ export interface GitHubLocation { /** Lowercase host name. */ @@ -38,6 +41,15 @@ export function checkedRepository(ref: ChangeRequestRef): ForgeRepository { return ref.repository } +/** + * Whether a value is a full commit object name that can be inlined into a request. + * @param value - candidate commit. + * @returns whether it is 40 or 64 hexadecimal digits. + */ +export function isCommit(value: string): boolean { + return COMMIT.test(value) +} + /** * Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/owner/name`, * `ssh://[user@]host[:port]/owner/name`, `git://host/owner/name`, and the diff --git a/packages/experimental/forge-github/tests/compare.spec.ts b/packages/experimental/forge-github/tests/compare.spec.ts new file mode 100644 index 0000000000..271a898715 --- /dev/null +++ b/packages/experimental/forge-github/tests/compare.spec.ts @@ -0,0 +1,44 @@ +import type { ForgeFailure } from '@deepseek-ai/dsh-experimental-forge' +import { describe, expect, it } from 'vitest' +import { readComparison } from '../src/compare.ts' +import { demo } from './fixtures.ts' + +const signal = new AbortController().signal +const [base, head] = ['a'.repeat(40), 'b'.repeat(64)] + +describe('compare read', () => { + it('reads the diff media type of the three-dot comparison, keeping escape sequences, and returns what the reader returns', async () => { + const calls: (readonly string[])[] = [] + const refused: ForgeFailure = { code: 'too-large', message: 'Not Acceptable' } + let answer: string | ForgeFailure = 'diff --git a/x b/x\n' + const read = async (args: readonly string[]) => { calls.push(args); return answer } + + await expect(readComparison(read, demo, base, head, signal)).resolves.toBe('diff --git a/x b/x\n') + answer = refused + await expect(readComparison(read, demo, base, head, signal)).resolves.toBe(refused) + expect(calls[0]).toEqual([ + 'api', '--hostname', 'github.com', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', `repos/octo/demo/compare/${base}...${head}`, + ]) + }) + + it('repeats a read that an older gh rejects for the escape option without that option, and no other failure', async () => { + const calls: (readonly string[])[] = [] + const answers: (string | ForgeFailure)[] = [ + { code: 'unavailable', message: 'unknown flag: --allow-escape-sequences' }, 'diff --git a/x b/x\n', + { code: 'unavailable', message: 'Server Error' }, + ] + const read = async (args: readonly string[]) => { calls.push(args); return answers.shift()! } + + await expect(readComparison(read, demo, base, head, signal)).resolves.toBe('diff --git a/x b/x\n') + expect(calls[1]).toEqual(['api', '--hostname', 'github.com', '-H', 'Accept: application/vnd.github.diff', `repos/octo/demo/compare/${base}...${head}`]) + await expect(readComparison(read, demo, base, head, signal)).resolves.toEqual({ code: 'unavailable', message: 'Server Error' }) + expect(calls).toHaveLength(3) + }) + + it.each([['base', 'main', head], ['head', base, 'HEAD']])('refuses a %s that is not a full commit object name before reading', async (_label, from, to) => { + const calls: (readonly string[])[] = [] + await expect(readComparison(async (args) => { calls.push(args); return '' }, demo, from, to, signal)) + .rejects.toThrow(`forge-github: invalid commit ${JSON.stringify(from === base ? to : from)}`) + expect(calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge-github/tests/fixtures.ts b/packages/experimental/forge-github/tests/fixtures.ts index 5eacc54a6b..bc5d1297b0 100644 --- a/packages/experimental/forge-github/tests/fixtures.ts +++ b/packages/experimental/forge-github/tests/fixtures.ts @@ -42,6 +42,7 @@ export function repositorySettings(overrides: Record = {}): Rec /** A pull request node with the fields the snapshot query selects. */ export function pullRequestNode(number: number, overrides: Record = {}, contexts: unknown[] = [], rollupState: string | null = 'SUCCESS'): Record { return { + id: `pull-${number}`, number, url: `https://github.com/octo/demo/pull/${number}`, title: `Change ${number}`, @@ -53,12 +54,13 @@ export function pullRequestNode(number: number, overrides: Record ({ isResolved })) } +} diff --git a/packages/experimental/forge-github/tests/gh.spec.ts b/packages/experimental/forge-github/tests/gh.spec.ts index 84246e36ac..c3a6d33035 100644 --- a/packages/experimental/forge-github/tests/gh.spec.ts +++ b/packages/experimental/forge-github/tests/gh.spec.ts @@ -24,7 +24,9 @@ async function fakeGh(): Promise { ' echo) printf "%s|" "$@"; printf "\\nprompt=%s token=%s pager=[%s]\\n" "$GH_PROMPT_DISABLED" "${GH_TOKEN:-unset}" "$GH_PAGER" ;;', ' input) cat ;;', ' fail) echo oops >&2; exit 3 ;;', - ' sleep) sleep 5 ;;', + // exec, so the deadline kill reaches the process holding the pipes; a + // child sleep would outlive the shell and keep the runner's close pending. + ' sleep) exec sleep 5 ;;', ' big) head -c 5000 /dev/zero | tr "\\0" x ;;', 'esac', '', diff --git a/packages/experimental/forge-github/tests/graphql.spec.ts b/packages/experimental/forge-github/tests/graphql.spec.ts index 80a96bae20..36bb799343 100644 --- a/packages/experimental/forge-github/tests/graphql.spec.ts +++ b/packages/experimental/forge-github/tests/graphql.spec.ts @@ -1,17 +1,25 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge' import { describe, expect, it } from 'vitest' -import { mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery, type CheckPageResult } from '../src/graphql.ts' -import { checkRun, demo, pull, pullRequestNode, repositorySettings, statusContext } from './fixtures.ts' +import { + mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse, mapSnapshotResponse, mapThreadPageResponse, snapshotQuery, +} from '../src/graphql.ts' +import type { SnapshotPages, ThreadPageResult } from '../src/graphql.ts' +import { checkRun, demo, pull, pullRequestNode, repositorySettings, statusContext, threadPage } from './fixtures.ts' -const noMoreChecks = async (): Promise => { throw new Error('Unexpected check page') } +const MAX_THREADS = 1_000 + +const noMorePages: SnapshotPages = { + threads: async () => { throw new Error('Unexpected review thread page') }, + checks: async () => { throw new Error('Unexpected check page') }, +} const other = { ...demo, name: 'other' } /** Map one pull request node of a repository with `settings`, or without readable merge settings when it is null. */ async function single(node: unknown, settings: Record | null = repositorySettings()): Promise { - const query = snapshotQuery([pull(1)]) - const results = await mapSnapshotResponse({ data: { r0: { ...settings, p0: node } } }, query, noMoreChecks) + const query = snapshotQuery([pull(1)], MAX_THREADS) + const results = await mapSnapshotResponse({ data: { r0: { ...settings, p0: node } } }, query, noMorePages) const result = results.get(changeRequestKey(pull(1))) if (result === undefined || 'code' in result) throw new Error(`expected a snapshot, received ${JSON.stringify(result)}`) return result @@ -20,7 +28,7 @@ async function single(node: unknown, settings: Record | null = describe('snapshot query', () => { it('groups change requests by repository and aliases each one', () => { const upper = { ...demo, owner: 'Octo', name: 'Demo' } - const query = snapshotQuery([pull(1), pull(2, upper), pull(1, upper), pull(7, other)]) + const query = snapshotQuery([pull(1), pull(2, upper), pull(1, upper), pull(7, other)], MAX_THREADS) expect([...query.targets]).toEqual([['r0.p0', pull(1)], ['r0.p1', pull(2, upper)], ['r1.p0', pull(7, other)]]) const settings = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod' @@ -30,13 +38,20 @@ describe('snapshot query', () => { }) it('refuses owners, names, and numbers that cannot be inlined', () => { - expect(() => snapshotQuery([pull(1, { ...demo, owner: 'oc"to' })])).toThrow('forge-github: invalid repository "oc\\"to/demo"') - expect(() => snapshotQuery([pull(1.5)])).toThrow('forge-github: invalid pull request number 1.5') - expect(() => snapshotQuery([pull(0)])).toThrow('forge-github: invalid pull request number 0') + expect(() => snapshotQuery([pull(1, { ...demo, owner: 'oc"to' })], MAX_THREADS)).toThrow('forge-github: invalid repository "oc\\"to/demo"') + expect(() => snapshotQuery([pull(1.5)], MAX_THREADS)).toThrow('forge-github: invalid pull request number 1.5') + expect(() => snapshotQuery([pull(0)], MAX_THREADS)).toThrow('forge-github: invalid pull request number 0') }) }) describe('snapshot mapping', () => { + it.each([['missing', undefined], ['null', null], ['not a full commit', 'HEAD~1']])( + 'keeps the status and leaves out the base commit when GitHub reports it %s', async (_case, baseRefOid) => { + const snapshot = await single(pullRequestNode(1, { baseRefOid })) + expect(snapshot).not.toHaveProperty('baseSha') + expect(snapshot.headSha).toBe('f'.repeat(40)) + }) + it('maps the pull request fields into a provider-neutral snapshot', async () => { expect((await single(pullRequestNode(1, {}, [checkRun('lint', 'COMPLETED', 'SUCCESS')])))).toEqual({ ref: pull(1), @@ -48,6 +63,7 @@ describe('snapshot mapping', () => { headBranch: 'topic-1', headSha: 'f'.repeat(40), baseBranch: 'master', + baseSha: 'b'.repeat(40), additions: 128, deletions: 14, mergeability: 'mergeable', @@ -65,6 +81,7 @@ describe('snapshot mapping', () => { checksRollup: 'success', checksTruncated: false, unresolvedThreads: 2, + threadsTruncated: false, updatedAt: '2026-10-09T01:02:03Z', closedAt: null, }) @@ -260,7 +277,7 @@ describe('snapshot mapping', () => { }) it('maps path-scoped and global errors from the partial-error response', async () => { - const query = snapshotQuery([pull(1), pull(2), pull(7, other)]) + const query = snapshotQuery([pull(1), pull(2), pull(7, other)], MAX_THREADS) const body = { data: { r0: { p0: pullRequestNode(1), p1: null }, r1: null }, errors: [ @@ -269,7 +286,7 @@ describe('snapshot mapping', () => { ], } - const results = await mapSnapshotResponse(body, query, noMoreChecks) + const results = await mapSnapshotResponse(body, query, noMorePages) expect(results.get(changeRequestKey(pull(1)))).toMatchObject({ state: 'open' }) expect(results.get(changeRequestKey(pull(2)))).toEqual({ code: 'not-found', message: 'Could not resolve to a PullRequest with the number of 2.' }) @@ -277,8 +294,8 @@ describe('snapshot mapping', () => { }) it('applies an error without a path to every unresolved change request', async () => { - const query = snapshotQuery([pull(1), pull(2)]) - const results = (await mapSnapshotResponse({ data: null, errors: [{ message: 'API rate limit exceeded' }] }, query, noMoreChecks)) + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) + const results = (await mapSnapshotResponse({ data: null, errors: [{ message: 'API rate limit exceeded' }] }, query, noMorePages)) expect([...results.values()]).toEqual([ { code: 'unavailable', message: 'API rate limit exceeded' }, @@ -287,30 +304,93 @@ describe('snapshot mapping', () => { }) it('reports a query validation error whose path names a fragment instead of a response alias', async () => { - const query = snapshotQuery([pull(1)]) + const query = snapshotQuery([pull(1)], MAX_THREADS) const results = await mapSnapshotResponse({ errors: [{ path: ['fragment ChangeRequestFields', 'invalidField'], - message: 'Field invalidField does not exist' }] }, query, noMoreChecks) + message: 'Field invalidField does not exist' }] }, query, noMorePages) expect([...results.values()]).toEqual([{ code: 'unavailable', message: 'Field invalidField does not exist' }]) }) it('reports missing nodes, malformed nodes, and malformed bodies', async () => { - const query = snapshotQuery([pull(1), pull(2)]) + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) - expect([...(await mapSnapshotResponse({ data: { r0: { p0: null, p1: { title: 7 } } } }, query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse({ data: { r0: { p0: null, p1: { title: 7 } } } }, query, noMorePages)).values()]).toEqual([ { code: 'not-found', message: 'pull request not found' }, { code: 'unavailable', message: 'unexpected pull request fields' }, ]) - expect([...(await mapSnapshotResponse({}, query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse({}, query, noMorePages)).values()]).toEqual([ { code: 'unavailable', message: 'unexpected GitHub response' }, { code: 'unavailable', message: 'unexpected GitHub response' }, ]) - expect([...(await mapSnapshotResponse('not json', query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse('not json', query, noMorePages)).values()]).toEqual([ { code: 'unavailable', message: 'unexpected GitHub response' }, { code: 'unavailable', message: 'unexpected GitHub response' }, ]) }) }) +describe('review thread counting', () => { + /** Map pull request 1, whose first page holds `first` and whose following pages hold `rest`, counting at most `max` threads. */ + async function counted(max: number, first: readonly boolean[], rest: readonly (readonly boolean[])[]) { + const reads: [string, string, number][] = [] + const threads: SnapshotPages['threads'] = async (id, cursor, size) => { + reads.push([id, cursor, size]) + const index = Number(cursor.slice('page-'.length)) + const resolved = rest[index - 1] + if (resolved === undefined) throw new Error(`Unexpected review thread page ${cursor}`) + const more = index < rest.length || size < resolved.length + return { ok: true, page: threadPage(resolved.slice(0, size), more ? `page-${index + 1}` : null) } + } + const query = snapshotQuery([pull(1)], max) + const node = pullRequestNode(1, { reviewThreads: threadPage(first, rest.length > 0 ? 'page-1' : null) }) + const results = await mapSnapshotResponse({ data: { r0: { ...repositorySettings(), p0: node } } }, query, { threads }) + const result = results.get(changeRequestKey(pull(1))) + return { result, reads, document: query.document } + } + const hundred = (unresolved: number): boolean[] => Array.from({ length: 100 }, (_, index) => index >= unresolved) + + it('counts unresolved threads across every page of a pull request with more than 100 threads', async () => { + const { result, reads } = await counted(MAX_THREADS, hundred(1), [hundred(2), [false, true, false]]) + + expect(result).toMatchObject({ unresolvedThreads: 5, threadsTruncated: false }) + expect(reads).toEqual([['pull-1', 'page-1', 100], ['pull-1', 'page-2', 100]]) + }) + + it.each([ + ['exactly the bound', 203, 5, false, [100, 3]], + ['one thread below the total', 202, 4, true, [100, 2]], + ['a bound inside the second page', 150, 3, true, [50]], + ] as const)('stops counting at %s and marks the count as a lower bound past it', async (_label, max, unresolved, truncated, sizes) => { + const { result, reads } = await counted(max, hundred(1), [hundred(2), [false, true, false]]) + + expect(result).toMatchObject({ unresolvedThreads: unresolved, threadsTruncated: truncated }) + expect(reads.map(([, , size]) => size)).toEqual(sizes) + }) + + it('reads a first page no larger than a bound below 100', async () => { + const { result, reads, document } = await counted(2, [false, false], [[false]]) + + expect(document).toContain('reviewThreads(first: 2)') + expect(result).toMatchObject({ unresolvedThreads: 2, threadsTruncated: true }) + expect(reads).toEqual([]) + expect((await counted(MAX_THREADS, [false], [])).document).toContain('reviewThreads(first: 100)') + }) + + it.each([ + ['a failed page', { ok: false, failure: { code: 'unavailable', message: 'Rate limited' } }, 'Rate limited'], + ['a page that repeats its cursor', { ok: true, page: threadPage([false], 'page-1') }, 'GitHub review thread pagination did not advance'], + ['a page without a cursor', { ok: true, page: { pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] } }, + 'GitHub review thread pagination did not advance'], + ] satisfies [string, ThreadPageResult, string][])('fails the pull request for %s without losing another one', async (_label, page, message) => { + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) + const body = { data: { r0: { ...repositorySettings(), p0: pullRequestNode(1, { reviewThreads: threadPage(hundred(0), 'page-1') }), p1: pullRequestNode(2) } } } + + const results = await mapSnapshotResponse(body, query, { threads: async () => page }) + + expect(results.get(changeRequestKey(pull(1)))).toEqual({ code: 'unavailable', message }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + }) +}) + describe('check page mapping', () => { it('validates the next page', () => { const page = { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [statusContext('ci', 'SUCCESS')] } @@ -326,6 +406,33 @@ describe('check page mapping', () => { }) }) +describe('review thread page mapping', () => { + it('validates the next page', () => { + const page = threadPage([true, false], 'next') + expect(mapThreadPageResponse({ data: { node: { reviewThreads: page } } })).toEqual({ ok: true, page }) + }) + + it.each([ + [{ data: { node: null } }, 'GitHub review thread page is unavailable'], + [{ data: { node: { reviewThreads: threadPage([true]) } }, errors: [{ message: 'Rate limited' }] }, 'Rate limited'], + [{ data: { node: { reviewThreads: { nodes: [] } } } }, 'unexpected GitHub review thread page'], + ])('rejects unavailable, partial, or malformed pages', (body, message) => { + expect(mapThreadPageResponse(body)).toEqual({ ok: false, failure: { code: 'unavailable', message } }) + }) +}) + +describe('pull request commit mapping', () => { + const answer = (headRefOid: string, baseRefOid: string) => ({ data: { repository: { pullRequest: { headRefOid, baseRefOid } } } }) + + it('returns the head and base commits, or nothing for a response that does not name both as commit object names', () => { + expect(mapPullRequestCommitsResponse(answer('a'.repeat(40), 'b'.repeat(64)))).toEqual({ head: 'a'.repeat(40), base: 'b'.repeat(64) }) + expect(mapPullRequestCommitsResponse(answer('a'.repeat(40), 'main'))).toBeUndefined() + expect(mapPullRequestCommitsResponse(answer('HEAD', 'b'.repeat(40)))).toBeUndefined() + expect(mapPullRequestCommitsResponse({ data: { repository: { pullRequest: null } } })).toBeUndefined() + expect(mapPullRequestCommitsResponse('not json')).toBeUndefined() + }) +}) + describe('head branch lookup mapping', () => { const body = (defaultBranch: string | null, nodes: { number: number; isCrossRepository: boolean }[]) => ({ data: { repository: { defaultBranchRef: defaultBranch === null ? null : { name: defaultBranch }, pullRequests: { nodes } } }, diff --git a/packages/experimental/forge-github/tests/plugin.spec.ts b/packages/experimental/forge-github/tests/plugin.spec.ts index a214182694..d522b04b5a 100644 --- a/packages/experimental/forge-github/tests/plugin.spec.ts +++ b/packages/experimental/forge-github/tests/plugin.spec.ts @@ -56,6 +56,10 @@ describe('forge-github plugin', () => { [{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'], + [{ maxCommits: 0 }, 'forge-github: maxCommits must be a positive safe integer'], + [{ maxCommits: 2.5 }, 'forge-github: maxCommits must be a positive safe integer'], + [{ maxReviewThreads: 0 }, 'forge-github: maxReviewThreads must be a positive safe integer'], + [{ maxReviewThreads: 2.5 }, 'forge-github: maxReviewThreads must be a positive safe integer'], ])('rejects %j at load', async (config, message) => { const context = await forge() diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index ce513e0ab8..d923d7425e 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -1,9 +1,11 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from '../src/gh.ts' import type { GhOutput, GhRunner } from '../src/gh.ts' +import { PULL_REQUEST_COMMITS_QUERY, THREADS_QUERY } from '../src/graphql.ts' import { GitHubProvider } from '../src/provider.ts' -import { checkRun, demo, pull, pullRequestNode } from './fixtures.ts' +import type { GitHubLimits } from '../src/provider.ts' +import { checkRun, demo, pull, pullRequestNode, threadPage } from './fixtures.ts' const enterprise = { forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' } const signal = new AbortController().signal @@ -23,8 +25,10 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } } +const limits: GitHubLimits = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 } + function provider(run: GhRunner): GitHubProvider { - return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608) + return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits) } describe('GitHub provider addressing', () => { @@ -46,7 +50,7 @@ describe('GitHub provider addressing', () => { it('uses a configured HTTP port for URL mapping and GitHub queries', async () => { const gh = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1) } } })) - const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608) + const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], limits) const repository = subject.repositoryFromRemote('https://ghe.example.com:8443/team/repo.git')! const ref = { repository, number: 1 } expect(subject.changeRequestFromUrl(subject.changeRequestUrl(ref))).toEqual(ref) @@ -69,6 +73,47 @@ describe('GitHub provider fetch', () => { expect(gh.calls).toHaveLength(1) }) + it('counts review threads past the first page while polling, bounded by maxReviewThreads', async () => { + const many = pullRequestNode(1, { reviewThreads: threadPage(Array.from({ length: 100 }, () => true), 'threads-1') }) + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) + ? output({ data: { node: { reviewThreads: threadPage([false, false], 'threads-2') } } }) + : output({ data: { r0: { p0: many, p1: pullRequestNode(2) } } })) + + const results = await new GitHubProvider(gh.run, ['github.com'], { ...limits, maxReviewThreads: 102 }).fetch([pull(1), pull(2)], signal) + + expect(results.get(changeRequestKey(pull(1)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: true }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + expect(gh.calls).toHaveLength(2) + expect(gh.calls[1]).toEqual(['api', 'graphql', '--hostname', 'github.com', + '-f', `query=${THREADS_QUERY}`, '-f', 'id=pull-1', '-f', 'cursor=threads-1', '-F', 'first=2']) + }) + + it.each([ + [new GhTimeoutError('timed out'), 'unavailable'], + [new GhOutputLimitError('too much output'), 'too-large'], + [new GhUnavailableError('gh missing'), 'unavailable'], + ] as const)('fails only the pull request whose review thread page cannot be read', async (error, code) => { + const many = pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) + const gh = fakeGh((args) => { + if (args.includes(`query=${THREADS_QUERY}`)) throw error + return output({ data: { r0: { p0: many, p1: pullRequestNode(2) } } }) + }) + + const results = await provider(gh.run).fetch([pull(1), pull(2)], signal) + + expect(results.get(changeRequestKey(pull(1)))).toEqual({ code, message: error.message }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ title: 'Change 2' }) + }) + + it('reports a review thread page that GitHub refuses', async () => { + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) + ? output({ message: 'API rate limit exceeded' }, 1, 'gh: API rate limit exceeded (HTTP 403)') + : output({ data: { r0: { p0: pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) } } })) + + await expect(provider(gh.run).fetchChecks(pull(1), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'gh: API rate limit exceeded (HTTP 403)' }) + }) + it.each([ [new GhTimeoutError('timed out'), 'unavailable'], [new GhOutputLimitError('too much output'), 'too-large'], @@ -92,13 +137,27 @@ describe('GitHub provider fetch', () => { const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(last.stdout) for (const limit of [total, total - 1, Buffer.byteLength(first.stdout) - 1]) { const gh = fakeGh(args => args.includes('id=fixed-rollup') ? last : first) - const result = await new GitHubProvider(gh.run, ['github.com'], limit).fetchChecks(pull(1), signal) + const result = await new GitHubProvider(gh.run, ['github.com'], { ...limits, maxOutputBytes: limit }).fetchChecks(pull(1), signal) if (limit === total) expect(result).toMatchObject({ checksTruncated: false }) else expect(result).toMatchObject({ code: 'too-large' }) expect(gh.calls).toHaveLength(limit < Buffer.byteLength(first.stdout) ? 1 : 2) } }) + it('counts review thread pages toward the byte budget of a complete detail read, but not of polling', async () => { + const first = output({ data: { r0: { p0: pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) } } }) + const page = output({ data: { node: { reviewThreads: threadPage([false, false]) } } }) + const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(page.stdout) + for (const limit of [total, total - 1]) { + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) ? page : first) + const subject = new GitHubProvider(gh.run, ['github.com'], { ...limits, maxOutputBytes: limit }) + const result = await subject.fetchChecks(pull(1), signal) + if (limit === total) expect(result).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + else expect(result).toEqual({ code: 'too-large', message: 'GitHub check details exceed the output size limit' }) + expect((await subject.fetch([pull(1)], signal)).get(changeRequestKey(pull(1)))).toMatchObject({ unresolvedThreads: 2 }) + } + }) + it('reads past 100 historical runs from the pinned rollup and counts only the latest run', async () => { const gh = fakeGh(args => output(args.includes('id=fixed-rollup') ? { data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [ @@ -192,7 +251,7 @@ describe('GitHub provider fetch', () => { it('rejects references retained after their host was removed from configuration', async () => { const gh = fakeGh(() => output('')) const retained = provider(gh.run).changeRequestFromUrl('https://ghe.corp.example/team/svc/pull/2')! - const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608) + const replacement = new GitHubProvider(gh.run, ['github.com'], limits) const results = await replacement.fetch([retained], signal) await expect(replacement.findByHead(retained.repository, 'topic', signal)).rejects.toThrow('is not configured') expect(results.get(changeRequestKey(retained))).toMatchObject({ code: 'unavailable' }) @@ -354,12 +413,127 @@ describe('GitHub provider actions', () => { describe('GitHub provider reads', () => { const head = 'c'.repeat(40) + const pushed = 'd'.repeat(40) + const base = 'b'.repeat(40) - it('reads the pull request diff through gh pr diff on its host', async () => { - const gh = fakeGh(() => output('diff --git a/x b/x\n')) + /** Answer the pull request commit read with `commits`, and every other command, the compare read among them, with `other`. */ + function pinned( + commits: { readonly head: string; readonly base: string } | GhOutput = { head, base }, + other: (args: readonly string[]) => GhOutput = () => output('diff --git a/x b/x\n'), + ) { + return fakeGh((args) => { + if (!args.includes(`query=${PULL_REQUEST_COMMITS_QUERY}`)) return other(args) + return 'exitCode' in commits ? commits : output({ data: { repository: { pullRequest: { headRefOid: commits.head, baseRefOid: commits.base } } } }) + }) + } - await expect(provider(gh.run).diff(pull(7, enterprise), signal)).resolves.toBe('diff --git a/x b/x\n') - expect(gh.calls).toEqual([['pr', 'diff', '7', '--repo', 'ghe.corp.example/team/svc', '--color', 'never']]) + it('reads the diff between the recorded base and the requested head through the compare API after one commit read', async () => { + const gh = pinned() + + await expect(provider(gh.run).diff(pull(7, enterprise), head, signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls).toEqual([ + ['api', 'graphql', '--hostname', 'ghe.corp.example', + '-f', `query=${PULL_REQUEST_COMMITS_QUERY}`, '-f', 'owner=team', '-f', 'name=svc', '-F', 'number=7'], + ['api', '--hostname', 'ghe.corp.example', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', + `repos/team/svc/compare/${base}...${head}`], + ]) + }) + + it('compares the head commit without regard to case and addresses the requested spelling', async () => { + const gh = pinned() + + await expect(provider(gh.run).diff(pull(7), head.toUpperCase(), signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls[1]?.at(-1)).toBe(`repos/octo/demo/compare/${base}...${head.toUpperCase()}`) + }) + + it('starts the comparison from the base the status recorded while it confirms the head', async () => { + const confirmed = Promise.withResolvers() + const gh = fakeGh(args => args.includes(`query=${PULL_REQUEST_COMMITS_QUERY}`) + ? confirmed.promise : output('diff --git a/x b/x\n')) + + const read = provider(gh.run).diff(pull(7), head, signal, base) + await vi.waitFor(() => { expect(gh.calls).toHaveLength(2) }) + expect(gh.calls.map(call => call.at(-1))).toContain(`repos/octo/demo/compare/${base}...${head}`) + confirmed.resolve(output({ data: { repository: { pullRequest: { headRefOid: head, baseRefOid: base.toUpperCase() } } } })) + + await expect(read).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls).toHaveLength(2) + }) + + it('cancels the early comparison and waits for it when the head moved, the base differs, or the head read fails', async () => { + const moved = 'e'.repeat(40) + for (const [answer, expected, compares] of [ + [output({ data: { repository: { pullRequest: { headRefOid: pushed, baseRefOid: base } } } }), + { code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }, [base]], + [output({ data: { repository: { pullRequest: { headRefOid: head, baseRefOid: moved } } } }), 'diff --git a/y b/y\n', [base, moved]], + [output('', 1, 'gh: Something went wrong (HTTP 502)'), { code: 'unavailable', message: 'gh: Something went wrong (HTTP 502)' }, [base]], + ] as const) { + const calls: string[][] = [] + const cancelled: string[] = [] + const run: GhRunner = async (args, operation) => { + calls.push([...args]) + if (args.includes(`query=${PULL_REQUEST_COMMITS_QUERY}`)) return answer + const range = String(args.at(-1)) + if (range.includes(`${moved}...`)) return output('diff --git a/y b/y\n') + // The early comparison runs until the provider cancels it. + await new Promise((resolve) => { operation.addEventListener('abort', resolve, { once: true }) }) + cancelled.push(range) + throw operation.reason + } + + await expect(provider(run).diff(pull(7), head, signal, base)).resolves.toEqual(expected) + expect(calls.map(call => String(call.at(-1))).filter(target => target.includes('/compare/')) + .map(target => target.split('/compare/')[1]?.split('...')[0])).toEqual(compares) + expect(cancelled).toEqual([`repos/octo/demo/compare/${base}...${head}`]) + } + }) + + it('refuses a base that is not a full commit object name before starting gh', async () => { + const gh = pinned() + + await expect(provider(gh.run).diff(pull(7), head, signal, 'HEAD~1')).rejects.toThrow('forge-github: invalid base commit "HEAD~1"') + expect(gh.calls).toEqual([]) + }) + + it('reports a head that moved past the requested commit as stale without reading the diff', async () => { + const gh = pinned({ head: pushed, base }) + + await expect(provider(gh.run).diff(pull(7), head, signal)) + .resolves.toEqual({ code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + expect(gh.calls).toHaveLength(1) + }) + + it.each([ + ['a missing pull request', output({ data: { repository: { pullRequest: null } }, errors: [{ type: 'NOT_FOUND', message: 'Could not resolve' }] }, 1, + 'gh: Could not resolve to a PullRequest with the number of 7.'), + { code: 'not-found', message: 'gh: Could not resolve to a PullRequest with the number of 7.' }], + ['a refusal', output({ message: 'Server Error' }, 1, 'gh: Server Error (HTTP 502)'), { code: 'unavailable', message: 'Server Error' }], + ['an answer without commits', output({ data: { repository: {} } }), + { code: 'unavailable', message: 'unexpected GitHub response to the pull request commit read' }], + ['a base that is not a commit object name', output({ data: { repository: { pullRequest: { headRefOid: head, baseRefOid: 'main' } } } }), + { code: 'unavailable', message: 'unexpected GitHub response to the pull request commit read' }], + ] as const)('reports a commit read that fails with %s without reading the diff', async (_label, answer, failure) => { + const gh = pinned(answer) + + await expect(provider(gh.run).diff(pull(7), head, signal)).resolves.toEqual(failure) + expect(gh.calls).toHaveLength(1) + }) + + it('reads the diff with a gh older than 2.97, which rejects the escape option, by repeating the read without it', async () => { + // What gh 2.96.0 prints for an option it does not know. + const gh = pinned(undefined, args => args.includes('--allow-escape-sequences') + ? output('', 1, 'unknown flag: --allow-escape-sequences\n\nUsage: gh api [flags]\n') + : output('diff --git a/x b/x\n')) + + await expect(provider(gh.run).diff(pull(7), head, signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls.map(call => call.includes('--allow-escape-sequences'))).toEqual([false, true, false]) + }) + + it('refuses a head that is not a full commit object name before starting gh', async () => { + const gh = pinned() + + await expect(provider(gh.run).diff(pull(7), 'HEAD', signal)).rejects.toThrow('forge-github: invalid head commit "HEAD"') + expect(gh.calls).toEqual([]) }) it('reads a file at a commit through the raw contents API, encoding each path segment', async () => { @@ -380,16 +554,20 @@ describe('GitHub provider reads', () => { ['a missing pull request', '', 'GraphQL: Could not resolve to a PullRequest with the number of 7. (repository.pullRequest)', { code: 'not-found', message: 'GraphQL: Could not resolve to a PullRequest with the number of 7. (repository.pullRequest)' }], ['a missing file', { message: 'Not Found' }, 'gh: Not Found (HTTP 404)', { code: 'not-found', message: 'Not Found' }], - // What gh 2.100 prints for a pull request over 300 files. - ['a diff over GitHub\'s size limit', '', [ - '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/7)', - 'PullRequest.diff too_large', - ].join('\n'), { + // What gh 2.100 prints when GitHub refuses a diff over its size limit, as the pull request diff endpoint does past 300 files. + ['a diff over GitHub\'s size limit', { + message: 'Sorry, the diff exceeded the maximum number of files (300). Consider using \'List pull requests files\' API or locally ' + + 'cloning the repository instead.', + errors: [{ resource: 'PullRequest', field: 'diff', code: 'too_large' }], + status: '406', + }, 'gh: Sorry, the diff exceeded the maximum number of files (300). Consider using \'List pull requests files\' API or locally ' + + 'cloning the repository instead. (HTTP 406)', { code: 'too-large', - message: '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/7)', + message: 'Sorry, the diff exceeded the maximum number of files (300). Consider using \'List pull requests files\' API or locally ' + + 'cloning the repository instead.', }], + ['a diff GitHub refuses to render without an error code', { message: 'Not Acceptable' }, 'gh: Not Acceptable (HTTP 406)', + { code: 'too-large', message: 'Not Acceptable' }], ['a file over the contents API limit', { message: 'This API returns blobs up to 1 MB in size. The requested blob is too large to fetch via the API.', errors: [{ resource: 'Blob', field: 'data', code: 'too_large' }], @@ -401,24 +579,112 @@ describe('GitHub provider reads', () => { { code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }], ['no output', '', '', { code: 'unavailable', message: 'gh exited with 1' }], ])('reports a read refused for %s', async (_label, body, stderr, failure) => { - await expect(provider(fakeGh(() => output(body, 1, stderr)).run).diff(pull(7), signal)).resolves.toEqual(failure) + await expect(provider(pinned(undefined, () => output(body, 1, stderr)).run).diff(pull(7), head, signal)).resolves.toEqual(failure) }) it('reports a read as unavailable when gh cannot start, rethrows other failures, and refuses an invalid commit', async () => { - await expect(provider(() => Promise.reject(new GhUnavailableError('gh could not start: spawn gh ENOENT'))).diff(pull(7), signal)) + await expect(provider(() => Promise.reject(new GhUnavailableError('gh could not start: spawn gh ENOENT'))).diff(pull(7), head, signal)) .resolves.toEqual({ code: 'unavailable', message: 'gh could not start: spawn gh ENOENT' }) await expect(provider(() => Promise.reject(new Error('aborted'))).fileText(pull(7), head, 'a', signal)).rejects.toThrow('aborted') await expect(provider(fakeGh(() => output('')).run).fileText(pull(7), 'main', 'a', signal)).rejects.toThrow('forge-github: invalid commit "main"') }) it('reports output over maxOutputBytes as too large and a run past timeoutMs as unavailable', async () => { - await expect(provider(() => Promise.reject(new GhOutputLimitError('gh pr output exceeds maxOutputBytes'))).diff(pull(7), signal)) - .resolves.toEqual({ code: 'too-large', message: 'gh pr output exceeds maxOutputBytes' }) + const overLimit = pinned(undefined, () => { throw new GhOutputLimitError('gh api output exceeds maxOutputBytes') }) + await expect(provider(overLimit.run).diff(pull(7), head, signal)) + .resolves.toEqual({ code: 'too-large', message: 'gh api output exceeds maxOutputBytes' }) + expect(overLimit.calls).toHaveLength(2) await expect(provider(() => Promise.reject(new GhTimeoutError('gh api timed out after 30000ms'))).fileText(pull(7), head, 'a', signal)) .resolves.toEqual({ code: 'unavailable', message: 'gh api timed out after 30000ms' }) }) }) +describe('GitHub provider commits', () => { + const sha = (n: number): string => String(n).repeat(40).slice(0, 40) + const node = (n: number, author: unknown = { name: 'Octo Cat', user: { login: 'octo' } }) => ({ commit: { + oid: sha(n), messageHeadline: `commit ${n}`, authoredDate: `2026-10-0${n}T00:00:00Z`, author, + parents: { nodes: n === 1 ? [] : [{ oid: sha(n - 1) }] }, + } }) + const page = (nodes: unknown[], next: string | null, head = sha(3), total = 3) => output({ data: { repository: { pullRequest: { + headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage: next !== null, endCursor: next }, nodes }, + } } } }) + + it('lists the commits oldest first across pages pinned to one head, bounded by maxCommits', async () => { + const gh = fakeGh(args => args.includes('cursor=page-1') ? page([node(3, { name: 'Ann', user: null })], null) : page([node(1), node(2, null)], 'page-1')) + + await expect(provider(gh.run).commits(pull(7), signal)).resolves.toEqual({ + headSha: sha(3), + truncated: false, + commits: [ + { sha: sha(1), parent: null, title: 'commit 1', author: 'octo', authoredAt: '2026-10-01T00:00:00Z' }, + { sha: sha(2), parent: sha(1), title: 'commit 2', author: null, authoredAt: '2026-10-02T00:00:00Z' }, + { sha: sha(3), parent: sha(2), title: 'commit 3', author: 'Ann', authoredAt: '2026-10-03T00:00:00Z' }, + ], + }) + expect(gh.calls[0]).toEqual(expect.arrayContaining(['--hostname', 'github.com', 'owner=octo', 'name=demo', 'number=7', 'first=100'])) + expect(gh.calls[0]?.some(arg => arg.startsWith('cursor='))).toBe(false) + expect(gh.calls[1]).toEqual(expect.arrayContaining(['cursor=page-1'])) + + const bounded = fakeGh(() => page([node(1), node(2)], 'page-1')) + await expect(new GitHubProvider(bounded.run, ['github.com'], { ...limits, maxCommits: 2 }).commits(pull(7), signal)) + .resolves.toMatchObject({ truncated: true, commits: [{ sha: sha(1) }, { sha: sha(2) }] }) + expect(bounded.calls).toHaveLength(1) + expect(bounded.calls[0]).toEqual(expect.arrayContaining(['first=2'])) + }) + + it('refuses a listing whose head or count moves between pages, or whose pages do not advance', async () => { + const moved = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(4)) : page([node(1)], 'page-1')) + await expect(provider(moved.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + const recounted = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(3), 4) : page([node(1)], 'page-1')) + await expect(provider(recounted.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + // A page that repeats the cursor it was read after would be requested again forever. + const stuck = fakeGh(args => page(args.includes('cursor=page-1') ? [] : [node(1)], 'page-1')) + await expect(provider(stuck.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'GitHub commit pagination did not advance' }) + expect(stuck.calls).toHaveLength(2) + const endless = fakeGh(() => output({ data: { repository: { pullRequest: { + headRefOid: sha(3), commits: { totalCount: 3, pageInfo: { hasNextPage: true, endCursor: null }, nodes: [node(1)] }, + } } } })) + await expect(provider(endless.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'GitHub commit pagination did not advance' }) + }) + + it('refuses a missing pull request and an unexpected response', async () => { + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: null } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: null } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: { headRefOid: 1 } } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response to the commit listing' }) + }) + + it('reports GraphQL errors, a body that is not GraphQL, and a refused request as failures', async () => { + await expect(provider(fakeGh(() => output({ errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible' }] })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'Resource not accessible' }) + await expect(provider(fakeGh(() => output('not json')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response' }) + await expect(provider(fakeGh(() => output('', 1, 'To get started with GitHub CLI, please run: gh auth login')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }) + }) + + it('reads the changes between two commits through the compare API in its diff form', async () => { + const gh = fakeGh(() => output('diff --git a/x b/x\n')) + + await expect(provider(gh.run).compare(pull(7, enterprise), sha(1), sha(3), signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls).toEqual([[ + 'api', '--hostname', 'ghe.corp.example', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', + `repos/team/svc/compare/${sha(1)}...${sha(3)}`, + ]]) + const refused = 'gh: Sorry, this diff is taking too long to generate. (HTTP 406)' + await expect(provider(fakeGh(() => output({ message: 'Sorry, this diff is taking too long to generate.' }, 1, refused)).run) + .compare(pull(7), sha(1), sha(3), signal)).resolves.toEqual({ code: 'too-large', message: 'Sorry, this diff is taking too long to generate.' }) + await expect(provider(gh.run).compare(pull(7), 'main', sha(3), signal)).rejects.toThrow('forge-github: invalid commit "main"') + await expect(provider(gh.run).compare(pull(7), sha(1), 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"') + }) +}) + it('rejects readiness, actions, and content reads for an unconfigured host without starting gh', async () => { const gh = fakeGh(() => output('unexpected')) const subject = provider(gh.run) @@ -427,7 +693,16 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.readiness(target.repository.host, signal)).resolves.toEqual({ state: 'unavailable', message }) await expect(subject.markReady(target, signal)).resolves.toEqual({ code: 'failed', message }) await expect(subject.merge(target, { method: 'squash', headSha: 'a'.repeat(40) }, signal)).resolves.toEqual({ code: 'failed', message }) - await expect(subject.diff(target, signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.diff(target, 'a'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.commits(target, signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.compare(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) + // A repository that cannot name a request is refused before its host, as every read refuses it. + const unsafe = pull(7, { ...demo, host: 'unconfigured.example', owner: 'oc/to' }) + const invalid = 'forge-github: invalid repository "oc/to/demo"' + await expect(subject.diff(unsafe, 'a'.repeat(40), signal)).rejects.toThrow(invalid) + await expect(subject.fileText(unsafe, 'a'.repeat(40), 'file.txt', signal)).rejects.toThrow(invalid) + await expect(subject.commits(unsafe, signal)).rejects.toThrow(invalid) + await expect(subject.compare(unsafe, 'a'.repeat(40), 'b'.repeat(40), signal)).rejects.toThrow(invalid) expect(gh.calls).toEqual([]) }) diff --git a/packages/experimental/forge-github/tests/review.spec.ts b/packages/experimental/forge-github/tests/review.spec.ts index e128508994..8a71ba6494 100644 --- a/packages/experimental/forge-github/tests/review.spec.ts +++ b/packages/experimental/forge-github/tests/review.spec.ts @@ -11,7 +11,7 @@ const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment } const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' } function fixture() { const gh = vi.fn().mockResolvedValueOnce({ exitCode: 0, stdout: JSON.stringify({ head: { sha: head }, state: 'open' }), stderr: '' }).mockResolvedValue(success) - return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608), signal: new AbortController().signal } + return { gh, provider: new GitHubProvider(gh, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }), signal: new AbortController().signal } } describe('review submission', () => { @@ -91,7 +91,7 @@ describe('review submission', () => { }) it('rejects a host outside the provider configuration without invoking gh', async () => { const { gh, signal } = fixture() - expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) + expect(await new GitHubProvider(gh, ['enterprise.test'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) expect(gh).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/forge-session/tests/fixtures.ts b/packages/experimental/forge-session/tests/fixtures.ts index d176c97101..2c857ad28e 100644 --- a/packages/experimental/forge-session/tests/fixtures.ts +++ b/packages/experimental/forge-session/tests/fixtures.ts @@ -46,6 +46,7 @@ export function snapshot(ref: ChangeRequestRef, overrides: Partial ({ + id: 'pull-' + number, number, url: 'https://github.com/octo/demo/pull/' + number, title: 'Change ' + number, @@ -79,12 +80,13 @@ const node = (number) => ({ headRefName: number === 7 ? 'feat' : 'other', headRefOid: 'a'.repeat(40), baseRefName: 'main', + baseRefOid: 'e'.repeat(40), additions: 1, deletions: 0, mergeable: 'MERGEABLE', mergeStateStatus: number === 7 ? 'BLOCKED' : 'CLEAN', reviewDecision: null, - reviewThreads: { nodes: [] }, + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-' + number, state: number === 7 ? 'PENDING' : 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index a51d57819e..19fb0423c8 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 9ca86ee541048ff2 - zh: 7aef4feb76542dd6 + en: 4b29b898061bcc4e + zh: fd37c2a8b06e7aaf /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 5d2bb55ec6..b316d57a78 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -36,7 +36,9 @@ Mount the registry with at least one provider package, such as the GitHub provid `markReady(ref, signal)` marks a draft ready for review, and `merge(ref, { method, headSha }, signal)` merges a change request only while its head is still `headSha`. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to undefined once the host accepted the change or to a `ForgeActionFailure`: `unauthenticated`, `stale` when the head moved past `headSha`, or `failed` with the host's reason. After either settles, a watched change request is polled at once. Snapshots carry `mergeReady`, whether the host would merge the change request now for the signed-in user, and `mergeMethods`, the methods the repository accepts with that user's usual one first. -`diff(ref, signal)` reads the change request's unified patch as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. +`diff(ref, headSha, signal)` reads the change request's unified patch at head commit `headSha` as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. A provider returns a patch only when it describes `headSha`; once the head is another commit, `diff` resolves to `stale`. The first stale read at a head commit polls a watched change request at once so its next status names the current head; later stale reads at that commit wait for the regular poll, which bounds reads while the host's answers briefly disagree. When the latest status of a watched change request names `headSha` and carries `baseSha`, the base commit the host recorded with that head, `diff` passes it to the provider, which may start reading from it before it confirms the head. Snapshots carry `unresolvedThreads` with `threadsTruncated`, which marks the count as a lower bound when the provider counted only some review threads. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. + +Providers may implement `commits` and `compare` together. `commits(ref, signal)` lists a change request's commits oldest first, each with its full object name, first parent, title, author, and author time, at one head commit and with a `truncated` flag; `compare(ref, base, head, signal)` reads the unified patch from commit `base` to commit `head`. The registry returns undefined from `commits` and an `unavailable` failure from `compare` when the provider lacks either method, so a consumer can offer commit views only where both exist. `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 8961c8d31d..e931eec159 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -36,7 +36,9 @@ kind: "package-reference" `markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`,或带主机原因的 `failed`。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 -`diff(ref, signal)` 读取托管平台计算出的变更请求统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 +`diff(ref, headSha, signal)` 读取托管平台计算出的变更请求在 head 提交 `headSha` 处的统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。提供方只在补丁描述 `headSha` 时返回补丁;head 已是其他提交时,`diff` resolve 为 `stale`。同一 head 提交的第一次 stale 读取会让被 watch 的变更请求立即重新轮询,使下一次状态给出当前 head;之后在该提交上的 stale 读取等待常规轮询,从而在托管平台的应答短暂不一致时限制读取次数。被 watch 的变更请求的最新状态给出 `headSha` 并携带 `baseSha`(托管平台随该 head 记录的基准提交)时,`diff` 把它传给提供方,提供方可以在确认 head 之前就从它开始读取。快照携带 `unresolvedThreads` 与 `threadsTruncated`;提供方只统计了部分评审讨论时,后者表示该计数只是下限。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 + +提供方可以同时实现 `commits` 与 `compare`。`commits(ref, signal)` 在一个 head 提交上按从旧到新列出变更请求的提交,每个提交带完整对象名、第一个父提交、标题、作者与作者时间,并带 `truncated` 标志;`compare(ref, base, head, signal)` 读取从提交 `base` 到提交 `head` 的统一补丁。提供方缺少其中任一方法时,注册表的 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此使用方只在两者都存在时提供按提交查看。 `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index d5204d988a..4040c1f836 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -6,7 +6,7 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { changeRequestKey } from './keys.ts' import { nextPollDelay } from './schedule.ts' import type { - ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, + ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from './types.ts' @@ -44,6 +44,8 @@ interface Watch { /** Epoch milliseconds of the next poll; undefined while in flight or after a terminal state. */ dueAt: number | undefined failures: number + /** Head commit whose `stale` diff read last polled at once, so further stale reads at it wait for the regular poll. */ + staleHead: string | undefined } /** @@ -236,15 +238,59 @@ export class ForgeService extends Service { } /** - * 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. When the latest status of a watched change request names + * `headSha`, its `baseSha` goes to the provider, which may then read the patch while it confirms the head. * @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 { + async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const latest = this.watches.get(changeRequestKey(ref))?.latest + const base = latest !== undefined && 'snapshot' in latest && latest.snapshot.headSha === headSha ? latest.snapshot.baseSha : undefined + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.diff(ref, headSha, operation, base)) + const watch = this.watches.get(changeRequestKey(ref)) + if (typeof result !== 'string' && result.code === 'stale' && watch !== undefined && watch.staleHead !== headSha) { + watch.staleHead = headSha + this.refresh(ref) + } + return result + } + + /** + * 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 { return await this.invoke(this.registration(ref.repository.forge), signal, - (provider, operation) => provider.diff(ref, operation)) + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve(undefined) : provider.commits(ref, operation)) + } + + /** + * 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 { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve({ code: 'unavailable', message: 'This provider does not read commits' } as const) + : provider.compare(ref, base, head, operation)) } /** @@ -302,7 +348,7 @@ export class ForgeService extends Service { const dispose = this.ctx.effect(() => { let watch = this.watches.get(key) if (watch === undefined) { - watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0 } + watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0, staleHead: undefined } this.watches.set(key, watch) this.schedule() } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 35a977dcfe..b691744ec1 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -79,6 +79,11 @@ export interface ChangeRequestSnapshot { readonly headSha: string /** Branch the change request merges into. */ readonly baseBranch: string + /** + * Base commit the host recorded with `headSha`, whose merge base with the head starts the change request's diff; + * omitted when the provider does not report it. + */ + readonly baseSha?: string /** Lines the change request adds. */ readonly additions: number /** Lines the change request deletes. */ @@ -100,8 +105,10 @@ export 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. */ @@ -113,9 +120,10 @@ export 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 } @@ -176,6 +184,30 @@ export interface ForgeActionFailure { readonly message: string } +/** One commit of a change request. */ +export 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 +} + +/** The commits of a change request at one head commit. */ +export 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 +} + /** Whether a provider can reach one host with the current credentials. */ export interface ForgeReadiness { /** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */ @@ -214,12 +246,27 @@ export interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** 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 + /** + * 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. `base`, when given, is the `baseSha` the + * latest status recorded with `headSha`; a provider may start reading from it before it confirms the head. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** 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 + /** + * 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 } /** diff --git a/packages/experimental/forge/tests/fake-provider.ts b/packages/experimental/forge/tests/fake-provider.ts index 6f04abdc00..4c035071b7 100644 --- a/packages/experimental/forge/tests/fake-provider.ts +++ b/packages/experimental/forge/tests/fake-provider.ts @@ -39,6 +39,7 @@ export function snapshot(target: ChangeRequestRef, overrides: Partial { - this.actions.push(`diff ${target.number}`) + async diff(target: ChangeRequestRef, headSha: string, _signal: AbortSignal, _base?: string): Promise { + this.actions.push(`diff ${target.number} ${headSha}`) return this.readResult } diff --git a/packages/experimental/forge/tests/lifecycle.spec.ts b/packages/experimental/forge/tests/lifecycle.spec.ts index 26e779eb87..e7b23ae147 100644 --- a/packages/experimental/forge/tests/lifecycle.spec.ts +++ b/packages/experimental/forge/tests/lifecycle.spec.ts @@ -120,7 +120,7 @@ it('does not announce provider withdrawal after its registry has stopped', async expect(observer).toHaveBeenCalledTimes(1) }) -it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks'] as const)( +it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks', 'commits', 'compare'] as const)( 'cancels and drains %s when its provider stops', async (method) => { ctx = await forgeContext() const provider: ForgeProvider = new FakeProvider() @@ -137,10 +137,12 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', }) vi.spyOn(provider, 'markReady').mockImplementation(async (_ref, signal) => { await hold(signal); return undefined }) vi.spyOn(provider, 'merge').mockImplementation(async (_ref, _request, signal) => { await hold(signal); return undefined }) - vi.spyOn(provider, 'diff').mockImplementation(async (_ref, signal) => { await hold(signal); return 'diff' }) + vi.spyOn(provider, 'diff').mockImplementation(async (_ref, _headSha, signal) => { await hold(signal); return 'diff' }) vi.spyOn(provider, 'fileText').mockImplementation(async (_ref, _commit, _path, signal) => { await hold(signal); return 'file' }) provider.submitReview = async (_ref, _request, signal) => { await hold(signal); return { ok: true, url: 'https://fake.test/review' } } provider.fetchChecks = async (target, signal) => { await hold(signal); return snapshot(target) } + provider.commits = async (_ref, signal) => { await hold(signal); return { headSha: 'a'.repeat(40), commits: [], truncated: false } } + provider.compare = async (_ref, _base, _head, signal) => { await hold(signal); return 'diff' } const fiber = await provide(ctx, provider) const service = ctx.forge const signal = new AbortController().signal @@ -150,8 +152,10 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', readiness: () => service.readiness(demo, signal), markReady: () => service.markReady(ref(1), signal), merge: () => service.merge(ref(1), { method: 'squash', headSha: 'a'.repeat(40) }, signal), - diff: () => service.diff(ref(1), signal), + diff: () => service.diff(ref(1), 'a'.repeat(40), signal), fileText: () => service.fileText(ref(1), 'a'.repeat(40), 'file.txt', signal), + commits: () => service.commits(ref(1), signal), + compare: () => service.compare(ref(1), 'a'.repeat(40), 'b'.repeat(40), signal), } const rejected = expect(calls[method]()).rejects.toThrow('was unregistered') let disposed = false diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index c70a07057b..7a5d84ab7b 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -71,7 +71,7 @@ describe('forge registry', () => { await expect(ctx.forge.markReady(ref(1, elsewhere), signal)).rejects.toThrow('forge: no provider is registered for "missing"') await expect(ctx.forge.merge(ref(1, elsewhere), { method: 'squash', headSha: 'a'.repeat(40) }, signal)) .rejects.toThrow('forge: no provider is registered for "missing"') - await expect(ctx.forge.diff(ref(1, elsewhere), signal)).rejects.toThrow('forge: no provider is registered for "missing"') + await expect(ctx.forge.diff(ref(1, elsewhere), 'a'.repeat(40), signal)).rejects.toThrow('forge: no provider is registered for "missing"') await expect(ctx.forge.fileText(ref(1, elsewhere), 'a'.repeat(40), 'x', signal)).rejects.toThrow('forge: no provider is registered for "missing"') expect(() => ctx!.forge.fileUrl(ref(1, elsewhere), 'a'.repeat(40), 'x')).toThrow('forge: no provider is registered for "missing"') }) @@ -97,11 +97,32 @@ describe('forge registry', () => { await provide(ctx, provider) const signal = new AbortController().signal - await expect(ctx.forge.diff(ref(3), signal)).resolves.toBe('diff --git a/x b/x') + await expect(ctx.forge.diff(ref(3), 'a'.repeat(40), signal)).resolves.toBe('diff --git a/x b/x') provider.readResult = { code: 'not-found', message: 'gone' } await expect(ctx.forge.fileText(ref(3), 'b'.repeat(40), 'src/a.ts', signal)).resolves.toEqual({ code: 'not-found', message: 'gone' }) expect(ctx.forge.fileUrl(ref(3), 'b'.repeat(40), 'src/a.ts')).toBe(`https://fake.test/Octo/Demo/file/${'b'.repeat(40)}/src/a.ts`) - expect(provider.actions).toEqual(['diff 3', `text 3 ${'b'.repeat(40)} src/a.ts`]) + expect(provider.actions).toEqual([`diff 3 ${'a'.repeat(40)}`, `text 3 ${'b'.repeat(40)} src/a.ts`]) + }) + + it('reads commits and commit ranges only from a provider that implements both', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const list = { headSha: 'b'.repeat(40), truncated: false, commits: [] } + + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'This provider does not read commits' }) + const commits = vi.fn(async () => list) + Object.assign(provider, { commits }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + const compare = vi.fn(async () => 'diff --git a/x b/x') + Object.assign(provider, { compare }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBe(list) + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toBe('diff --git a/x b/x') + expect(commits).toHaveBeenCalledWith(ref(3), expect.any(AbortSignal)) + expect(compare).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), 'b'.repeat(40), expect.any(AbortSignal)) }) it('delegates change request actions to the provider of their forge and returns its outcome', async () => { diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 5760417c26..0988bb3ad1 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -223,6 +223,65 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(3) }) + it('passes the base commit of the latest status to a diff read at its head only', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1), { baseSha: 'e'.repeat(40) })) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const diff = vi.spyOn(provider, 'diff') + const signal = new AbortController().signal + + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await context.forge.diff(ref(1), 'f'.repeat(40), signal) + await context.forge.diff(ref(2), 'a'.repeat(40), signal) + + expect(diff.mock.calls.map(call => call[3])).toEqual(['e'.repeat(40), undefined, undefined]) + }) + + it('polls a watched change request at once after a diff read finds a newer head, and only then', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + + provider.readResult = 'diff --git a/x b/x' + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + provider.readResult = { code: 'not-found', message: 'gone' } + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(1) + + provider.readResult = { code: 'stale', message: 'the head moved' } + await expect(context.forge.diff(ref(1), 'a'.repeat(40), signal)).resolves.toEqual({ code: 'stale', message: 'the head moved' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + }) + + it('polls at once only for the first stale diff read at a head, leaving later ones to the regular cadence', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + provider.readResult = { code: 'stale', message: 'the head moved' } + + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + await vi.advanceTimersByTimeAsync(config.idleIntervalMs) + expect(provider.fetches).toHaveLength(3) + + await context.forge.diff(ref(1), 'b'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index 8419dfbb18..e817a48d82 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -82,12 +82,13 @@ export const VIEWER_ENDPOINT_CLASSES = { // No reader role names these, so the conservative class is owner-only. A share's method policy // decides whether one installed plugin's method reaches its viewers; this table only decides what // the core share roles grant. - 'account/ackBonusNotified': 'owner-only', // owner account and sign-in; the served page never reads it 'account/cancelSignIn': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getBalance': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getProfile': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getState': 'owner-only', // owner account and sign-in; the served page never reads it - 'account/getUnnotifiedBonuses': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/getNotificationContent': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/getNotifications': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/reportNotificationEvent': 'owner-only', // owner account and sign-in; the served page never reads it 'account/hasRunningAccountTasks': 'owner-only', // owner account and sign-in; the served page never reads it 'account/signOut': 'owner-only', // owner account and sign-in; the served page never reads it 'account/startSignIn': 'owner-only', // owner account and sign-in; the served page never reads it @@ -138,6 +139,7 @@ export const VIEWER_ENDPOINT_CLASSES = { 'workspaceFiles/list': 'owner-only', // owner Workspace file access' 'workspaceFiles/read': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it 'workspaceFiles/readBytes': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it + 'workspaceFiles/search': 'owner-only', // owner Workspace file access 'workspaceFiles/stat': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it 'pluginManager/cancelInstall': 'owner-only', // owner plugin management 'pluginManager/inspect': 'owner-only', // owner plugin management diff --git a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts index 4feed9d4e0..c8fb3ad8a9 100644 --- a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts @@ -408,7 +408,8 @@ describe('viewer page startup contract', () => { it('keeps the owner’s own surfaces refused and out of the reader’s snapshot', async () => { const { decide, grants } = await fixture() - const ownerOnly = ['account/watch', 'job/list', 'job/follow', 'settings/describe', + const ownerOnly = ['account/watch', 'account/getNotifications', 'account/getNotificationContent', 'account/reportNotificationEvent', + 'job/list', 'job/follow', 'settings/describe', 'credentials/describe', 'pluginManager/listPlugins', 'schedule/catalog', 'schedule/create', 'schedule/deliveryLimits', 'schedule/deleteInactive', 'schedule/edit', 'schedule/history', 'schedule/list', 'schedule/run', 'schedule/view', 'agentTeams/setEnabled'] as const diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index c964c25be1..5e9a6604cb 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-worktree/use-this-package: - en: c788af94d52dd001 - zh: 200580d1a97048eb + en: 7fb20cca0a3154e5 + zh: 41bf0aa2bf753c07 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: en: 6971a7ca9073bef1 zh: b977c28a75c7f963 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 756ea6803f..e164f86600 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -36,7 +36,7 @@ Mount the service alongside `workingDirectory`, `fs`, `subprocess`, `sandbox`, ` `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with `git worktree remove`; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at `baseCommit` when it does not, and reports which happened as `branchRecreated`. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. `onPhase` receives `prepare` before validation, target-registration cleanup, and branch creation, and `checkout` before the files are written; it must not throw. -Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, hidden index flags, submodules, locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout; ignored files do not, as Git itself discards them. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. +Every creation appends a `plugin:worktree/created` record to the Session log after the directory change, so the `worktree` projection lists the Session's checkouts with `owned` false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one `scheduled` cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While `retainOnArchive` is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the [Forge panel](../client-ui-forge/README.md) edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force `git worktree remove` under the creator's policy after a second use check inside the path lock, which also holds `ensure` and `set` into that path through `working-directory/access`; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative `modules` directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: `git status` reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as `failed`. Inspection stops reading `git status` at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by `maxOutputBytes`. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. `cleanupOf(session, revision)` reads the attempt, or waits for a named revision to settle, as `scheduled`, `retained`, `removed`, or `failed`; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept. The default checkout directory is `/.agents/worktrees/`. The returned `repositoryRoot` is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the `dsh-` prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as `dsh-6b1f02c4-9a3e`; a Session id without a UUID gets eight random hexadecimal digits after the prefix. `generatedWorktreeName` exports the same rule for callers that name a worktree before creating it. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Each Git and Node command runs under its own `timeoutMs` deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative `directory`, generated `namePrefix`, executable choices, process limits, and `retainOnArchive` are configurable in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-worktree). diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index fa3624a49c..5c497a2606 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -36,7 +36,7 @@ kind: "package-reference" `ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?)` 在记录的目录重新检出被删除的 worktree。它在修改前校验记录中的仓库根目录、完整提交对象名、分支和配置池内的规范目标路径。它只通过 `git worktree remove` 移除缺失目标的未锁定登记;其他 worktree 与锁定登记保持不变。随后在分支仍存在时检出该分支,否则在 `baseCommit` 重新创建同名分支,并通过 `branchRecreated` 报告是哪种情况。目录已存在时会报错。调用方 Session 的工作目录不变,从未提交的修改无法恢复。检出与创建时一样禁用过滤器。`onPhase` 在检查目录、清理登记与创建分支之前收到 `prepare`,在写入文件之前收到 `checkout`;它不能抛出异常。 -每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、隐藏的索引标记、子模块、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录;被忽略的文件不会,因为 Git 自身会丢弃它们。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 +每次创建都会在目录切换之后向 Session 日志追加一条 `plugin:worktree/created` 事件,因此 `worktree` 投影列出该 Session 的检出目录,位于 fork 继承前缀内的条目 `owned` 为 false。Workspace 归档某个 Session 时,服务为该 Session 自己创建的第一个检出目录登记一条 `scheduled` 清理并立即返回;检查在后台进行。`retainOnArchive` 开启时,归档不登记任何清理,所有检出目录都保留;该字段是 volatile 字段,每次归档时读取,[Forge 面板](../client-ui-forge/README.zh.md)在插件页该套件的 worktree 行上以开关编辑它。只要任一未归档 Session 仍引用该目录——通过记录的创建,或通过位于其中的工作目录(祖先子代理已归档的 Session 视为已归档;冷 Session 从投影缓存或其日志读取)——或创建者的沙箱策略为只读,目录就保留。符合条件的目录在路径锁内再做一次使用检查后,用创建者的策略执行不带 force 的 `git worktree remove`;路径锁同时通过 `working-directory/access` 阻塞进入该路径的 `ensure` 与 `set`;分支及其提交保留。跟踪文件改动、未跟踪文件、已初始化的子模块(仓库位于检出目录管理目录的 `modules` 中)、锁、分离 HEAD、分支不匹配以及位于配置池之外的目标都会保留目录。被忽略的文件以及对 skip-worktree 或 assume-unchanged 文件的改动不会:`git status` 不报告这两类内容,Git 删除目录时一并丢弃它们。检查不识别已提交的内嵌仓库;Git 会拒绝这类删除,本次尝试以 `failed` 结束。检查读到 `git status` 的第一条记录即停止,并以流式读取工作树列表,查找该检出目录期间在内存中保留其条目;两者的输出都不受 `maxOutputBytes` 限制。不检查进程:仍在写入的进程会让 Git 拒绝删除,空闲进程的下一条命令会失败。取消归档会取消尚未获准的删除,并等待已获准的删除结束。`cleanupOf(session, revision)` 读取本次尝试,或等待指定修订号结束,状态为 `scheduled`、`retained`、`removed` 或 `failed`;失败时 Session 仍保持归档并记录警告。此事件存在之前创建的检出目录,以及更早归档的 Session,不会被扫描。 默认检出目录是 `/.agents/worktrees/`。返回的 `repositoryRoot` 是调用方当前检出目录的顶层目录;如果它是链接检出目录,工作树父目录就嵌套在其中。省略名称时,名称由前缀 `dsh-`、Session id 中 UUID 的前 8 位十六进制数、一个连字符和 4 位随机十六进制数组成,例如 `dsh-6b1f02c4-9a3e`;Session id 不含 UUID 时,前缀后接 8 位随机十六进制数。`generatedWorktreeName` 导出同一规则,供在创建前确定名称的调用方使用。仅当服务的分配操作创建了父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`;已有文件与忽略规则保持不变。每条 Git 和 Node 命令各自受 `timeoutMs` 时限约束,默认 5 分钟,使大仓库在较慢的文件系统上也能完成检出;取消仍会终止正在运行的命令。相对路径 `directory`、生成名称使用的 `namePrefix`、可执行程序、进程限制与 `retainOnArchive` 可在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-worktree)中查阅。 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 3c74e3f73c..b445ec72b7 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -15,11 +15,12 @@ import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { WorktreeReclamation } from './archive.ts' import { PREPARE_DIRECTORY } from './directory.ts' import { generatedWorktreeName } from './name.ts' -import { runCommand } from './process.ts' +import { runCommand, scanCommand } from './process.ts' import type { ProcessConfig } from './process.ts' import { CREATED_RECORD, worktreeProjection } from './projection.ts' import type { WorktreeProjectionState } from './projection.ts' import { checkoutIdentity, registration, removeCheckout } from './removal.ts' +import type { GitScan } from './removal.ts' import type { CreatedWorktree, CreateWorktreePhase, CreateWorktreeRequest, RestoredWorktree, RestoreWorktreeRequest, WorktreeCleanup, } from './types.ts' @@ -47,7 +48,11 @@ export interface Config { timeoutMs?: number /** Subprocess termination grace in milliseconds. */ graceMs?: number - /** Maximum captured bytes per subprocess output stream. */ + /** + * Maximum captured bytes per subprocess output stream; archive inspection + * streams `git status`, and inspection and restoration stream the worktree + * listing, so it bounds only their stderr. + */ maxOutputBytes?: number } @@ -220,8 +225,9 @@ export class WorktreeService extends Service { ): Promise { const control = AbortSignal.any([this.lifetime.signal, signal]) control.throwIfAborted() - const run = this.gitRunner(this.ctx.sandboxPolicy.resolve({ session }), control) - const operation = removeCheckout(this.ctx, this.config.directory, request, run, control, admit) + const policy = this.ctx.sandboxPolicy.resolve({ session }) + const git = { read: this.gitRunner(policy, control), scan: this.gitScanner(policy, control) } + const operation = removeCheckout(this.ctx, this.config.directory, request, git, control, admit) this.pending.add(operation) try { return await operation } finally { this.pending.delete(operation) } } @@ -296,7 +302,8 @@ export class WorktreeService extends Service { if (identity === null) throw new Error('worktree restoration must use a canonical directory inside the configured pool of the source checkout root') await run(repositoryRoot, ['check-ref-format', `refs/heads/${branch}`]) await run(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseCommit}^{commit}`]) - const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, run, signal) + const scan = this.gitScanner(policy, signal) + const fields = await registration(this.ctx, { path, branch, baseCommit, repositoryRoot }, identity.target, scan, signal) if (fields !== undefined) { if (fields.some(field => field === 'locked' || field.startsWith('locked '))) throw new Error(`worktree is locked: ${path}`) if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) @@ -320,15 +327,23 @@ export class WorktreeService extends Service { } } - /** Confine Git commands to the caller's sandbox policy, with hooks and the filesystem monitor disabled. */ + /** Confine Git commands to the caller's sandbox policy, collecting bounded stdout. */ private gitRunner(policy: SandboxExecutionPolicy, signal: AbortSignal): GitRun { return (directory, args, allowedExitCodes, env) => runCommand( - this.ctx, this.config, policy, directory, - [this.config.gitCommand, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], - signal, allowedExitCodes, env, + this.ctx, this.config, policy, directory, this.gitArgv(args), signal, allowedExitCodes, env, ) } + /** Confine Git commands to the caller's sandbox policy, streaming stdout instead of collecting it. */ + private gitScanner(policy: SandboxExecutionPolicy, signal: AbortSignal): GitScan { + return (directory, args, onField) => scanCommand(this.ctx, this.config, policy, directory, this.gitArgv(args), signal, onField) + } + + /** The configured Git executable with hooks and the filesystem monitor disabled, followed by `args`. */ + private gitArgv(args: string[]): [string, ...string[]] { + return [this.config.gitCommand, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args] + } + /** Allocate the checkout directory exclusively inside the pool, creating a self-ignoring pool when it is new. */ private async prepareDirectory( policy: SandboxExecutionPolicy, diff --git a/packages/experimental/worktree/src/process.ts b/packages/experimental/worktree/src/process.ts index 74c8fa1c1b..f4bb56273a 100644 --- a/packages/experimental/worktree/src/process.ts +++ b/packages/experimental/worktree/src/process.ts @@ -1,8 +1,11 @@ -/** Bounded, cancellable commands under the calling Session's existing file policy. */ +/** Cancellable commands under the calling Session's existing file policy, whose stdout is collected within a bound or streamed. */ +import type { Readable } from 'node:stream' import type { Context } from '@deepseek-ai/cordis' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' -import type { SubprocessCollectedOutputs } from '@deepseek-ai/dsh-subprocess' +import type { + SubprocessCollect, SubprocessCollectedOutputs, SubprocessHandle, SubprocessOutcome, SubprocessOutputReader, +} from '@deepseek-ai/dsh-subprocess' import { deadline } from '@deepseek-ai/dsh-timeout' /** Resolved process resource limits owned by the worktree service. */ @@ -46,39 +49,116 @@ export async function runCommand( env: NodeJS.ProcessEnv = {}, ): Promise<{ stdout: string; exitCode: number }> { using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') - timeout.signal.throwIfAborted() - const program = await ctx.subprocess.resolveExecutable(argv[0], undefined, timeout.signal) - const command = [program, ...argv.slice(1)] - const wrapped = policy.mode === 'danger-full-access' - ? command - : (await ctx.sandbox.confine(command, { ...policy, mode: policy.mode }, timeout.signal)).argv - timeout.signal.throwIfAborted() - const child = ctx.subprocess.spawn({ - argv: wrapped, - cwd, - env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', GIT_NO_LAZY_FETCH: '1', ...env }, - signal: timeout.signal, - graceMs: config.graceMs, - stdio: { - stdin: 'ignore', - stdout: { maxBytes: config.maxOutputBytes }, - stderr: { maxBytes: config.maxOutputBytes }, - }, - }) + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, env, { maxBytes: config.maxOutputBytes }) try { const outcome = await child.done timeout.signal.throwIfAborted() // The spawn spec above collects both streams. const captured = child.collected as Required + const exitCode = allowedExitCode(outcome, captured.stderr, allowedExitCodes) const stdout = captured.stdout.readFrom(0) - const stderr = captured.stderr.readFrom(0) - if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) { - throw new Error(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.text.trim()}`) - } if (stdout.lossy) throw new Error('worktree command output exceeds maxOutputBytes') - return { stdout: stdout.text, exitCode: outcome.exitCode } + return { stdout: stdout.text, exitCode } } finally { child.terminate() await child.waitForExit() } } + +/** + * Run an argv as {@link runCommand} does, but pass each NUL-terminated stdout + * field to `onField` as it arrives instead of retaining the output, so the size + * of stdout is unbounded and `maxOutputBytes` limits only stderr. An + * unterminated remainder is ignored. A false return from `onField` terminates + * the command, whose outcome is then not checked, even when the provider + * rejects it for a launch cancelled before acknowledgement; otherwise only + * status 0 succeeds. + * @param ctx - subprocess and sandbox providers in the same execution world. + * @param config - complete process resource limits. + * @param policy - unchanged calling Session policy. + * @param cwd - canonical process working directory. + * @param argv - executable followed by literal arguments. + * @param signal - operation cancellation. + * @param onField - synchronous consumer of each field in order; false ends the command. + * @returns true when `onField` ended the command, false when it exited successfully first. + */ +export async function scanCommand( + ctx: Context, + config: ProcessConfig, + policy: SandboxExecutionPolicy, + cwd: string, + argv: readonly [string, ...string[]], + signal: AbortSignal, + onField: (field: string) => boolean, +): Promise { + using timeout = deadline(signal, config.timeoutMs, 'WORKTREE_TIMEOUT') + const child = await spawnCommand(ctx, config, policy, cwd, argv, timeout.signal, {}, 'pipe') + try { + // The spawn spec above pipes stdout and collects stderr. + const stdout = child.stdout as Readable + stdout.setEncoding('utf8') + let pending = '' + let stopped = false + for await (const chunk of stdout as AsyncIterable) { + const fields = (pending + chunk).split('\0') + pending = fields.splice(-1).join('') + if (!fields.every(field => onField(field))) { + stopped = true + break + } + } + if (stopped) { + child.terminate() + await Promise.allSettled([child.done]) + timeout.signal.throwIfAborted() + return true + } + const outcome = await child.done + timeout.signal.throwIfAborted() + allowedExitCode(outcome, child.collected.stderr as SubprocessOutputReader, [0]) + return false + } finally { + child.terminate() + await Promise.allSettled([child.done]) + await child.waitForExit() + } +} + +/** Resolve, confine, and start one command whose stderr is collected within `maxOutputBytes`. */ +async function spawnCommand( + ctx: Context, + config: ProcessConfig, + policy: SandboxExecutionPolicy, + cwd: string, + argv: readonly [string, ...string[]], + signal: AbortSignal, + env: NodeJS.ProcessEnv, + stdout: 'pipe' | SubprocessCollect, +): Promise { + signal.throwIfAborted() + const program = await ctx.subprocess.resolveExecutable(argv[0], undefined, signal) + const command = [program, ...argv.slice(1)] + const wrapped = policy.mode === 'danger-full-access' + ? command + : (await ctx.sandbox.confine(command, { ...policy, mode: policy.mode }, signal)).argv + signal.throwIfAborted() + return ctx.subprocess.spawn({ + argv: wrapped, + cwd, + env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', GIT_NO_LAZY_FETCH: '1', ...env }, + signal, + graceMs: config.graceMs, + stdio: { stdin: 'ignore', stdout, stderr: { maxBytes: config.maxOutputBytes } }, + }) +} + +/** + * The exit code of a command that exited with an allowed status. + * @throws when the command was signalled or exited with another status, quoting its stderr. + */ +function allowedExitCode(outcome: SubprocessOutcome, stderr: SubprocessOutputReader, allowedExitCodes: readonly number[]): number { + if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) { + throw new Error(`worktree command failed (${outcome.signal ?? outcome.exitCode}): ${stderr.readFrom(0).text.trim()}`) + } + return outcome.exitCode +} diff --git a/packages/experimental/worktree/src/removal.ts b/packages/experimental/worktree/src/removal.ts index f9e4082bf7..4681c0c708 100644 --- a/packages/experimental/worktree/src/removal.ts +++ b/packages/experimental/worktree/src/removal.ts @@ -3,9 +3,24 @@ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-fs' import type { RestoreWorktreeRequest } from './types.ts' -/** Runs one Git command in the owner's confinement and reports its output. */ +/** Runs one Git command in the owner's confinement and reports its complete bounded output. */ export type GitRead = (directory: string, args: string[]) => Promise<{ stdout: string; exitCode: number }> +/** + * Runs one Git command in the owner's confinement and passes each + * NUL-terminated stdout field to `onField` without retaining the output; + * false from `onField` ends the command. Resolves true when `onField` ended it. + */ +export type GitScan = (directory: string, args: string[], onField: (field: string) => boolean) => Promise + +/** The confined Git runners inspection and removal use. */ +export interface GitCommands { + /** Commands whose output stays small, read whole. */ + readonly read: GitRead + /** Commands whose output grows with the repository or its worktrees, read as it arrives. */ + readonly scan: GitScan +} + /** Resolved canonical locations of a recorded checkout that validation confirmed. */ export interface CheckoutIdentity { readonly root: Awaited> @@ -40,22 +55,31 @@ export async function checkoutIdentity( /** * Find the registration of `target` among the source repository's worktrees. + * The listing grows with the number of worktrees; it is streamed without an + * output limit, and its entries are kept in memory while `target` is resolved. * @param ctx - execution-world filesystem provider. * @param request - saved checkout identity. * @param target - resolved checkout directory. - * @param run - bounded Git runner with the owner's policy. + * @param scan - streaming Git runner with the owner's policy. * @param signal - cancellation of the lookups. * @returns the porcelain fields of the matching entry, or undefined when none is registered. */ export async function registration( - ctx: Context, request: RestoreWorktreeRequest, target: CheckoutIdentity['target'], run: GitRead, signal: AbortSignal, + ctx: Context, request: RestoreWorktreeRequest, target: CheckoutIdentity['target'], scan: GitScan, signal: AbortSignal, ): Promise { - const registered = await run(request.repositoryRoot, ['worktree', 'list', '--porcelain', '-z']) - for (const entry of registered.stdout.split('\0\0').map(entry => entry.split('\0'))) { - const registeredPath = entry.find(field => field.startsWith('worktree '))?.slice('worktree '.length) - if (registeredPath === undefined) continue - const recorded = await ctx.fs.resolve(registeredPath, { cwd: request.repositoryRoot, signal }) - if (recorded.targetKey === target.targetKey) return entry + const entries: { path: string; fields: string[] }[] = [] + // Each entry of the -z porcelain listing starts with its worktree line and ends with an empty field. + let fields: string[] = [] + await scan(request.repositoryRoot, ['worktree', 'list', '--porcelain', '-z'], (field) => { + if (field.startsWith('worktree ')) { + fields = [field] + entries.push({ path: field.slice('worktree '.length), fields }) + } else if (field.length > 0) fields.push(field) + return true + }) + for (const entry of entries) { + const recorded = await ctx.fs.resolve(entry.path, { cwd: request.repositoryRoot, signal }) + if (recorded.targetKey === target.targetKey) return entry.fields } return undefined } @@ -67,51 +91,52 @@ export async function registration( * @param ctx - execution-world filesystem provider. * @param directory - configured relative worktree pool. * @param request - saved checkout identity. - * @param run - bounded Git runner with the owner's policy. + * @param git - confined Git runners with the owner's policy. * @param signal - cancellation before or during removal. * @param admit - synchronous final admission after inspection; false retains the checkout. * @returns true when removed; false when inspection or admission retains it; Git failures reject. */ export async function removeCheckout( - ctx: Context, directory: string, request: RestoreWorktreeRequest, run: GitRead, signal: AbortSignal, admit: () => boolean, + ctx: Context, directory: string, request: RestoreWorktreeRequest, git: GitCommands, signal: AbortSignal, admit: () => boolean, ): Promise { - if (!await inspectRemoval(ctx, directory, request, run, signal)) return false + if (!await inspectRemoval(ctx, directory, request, git, signal)) return false signal.throwIfAborted() if (!admit()) return false - await run(request.repositoryRoot, ['worktree', 'remove', '--', request.path]) + await git.read(request.repositoryRoot, ['worktree', 'remove', '--', request.path]) return true } /** - * Verify checkout identity and account for every file that Git's non-force - * removal would refuse: tracked changes, untracked files, hidden index flags, - * and submodules. Ignored files are not counted; `git worktree remove` discards them. + * Verify checkout identity and that `git status` reports no tracked changes or + * untracked files; its output is read only up to the first entry. Ignored files + * are not counted, nor are edits to skip-worktree or assume-unchanged files, + * which `git status` hides; `git worktree remove` discards both. A checkout + * whose administrative directory holds submodule repositories is ineligible, + * as Git refuses to remove it; a committed embedded repository is not + * inspected, so Git's refusal of that removal rejects. * @param ctx - execution-world filesystem provider. * @param directory - configured relative worktree pool. * @param request - saved checkout identity. - * @param run - bounded Git runner with the owner's policy. + * @param git - confined Git runners with the owner's policy. * @param signal - cancellation of inspection. * @returns false for an ineligible checkout; inspection failures reject. */ export async function inspectRemoval( - ctx: Context, directory: string, request: RestoreWorktreeRequest, run: GitRead, signal: AbortSignal, + ctx: Context, directory: string, request: RestoreWorktreeRequest, git: GitCommands, signal: AbortSignal, ): Promise { const { path, branch } = request - const identity = await checkoutIdentity(ctx, directory, request, run, signal) + const identity = await checkoutIdentity(ctx, directory, request, git.read, signal) if (identity === null) return false if ((await ctx.fs.lstat(path, undefined, signal))?.type !== 'directory') return false - const fields = await registration(ctx, request, identity.target, run, signal) + const fields = await registration(ctx, request, identity.target, git.scan, signal) // The primary registration is excluded even when the configured pool contains it. if (fields === undefined || !fields.includes(`branch refs/heads/${branch}`) || fields.some(field => field === 'detached' || field.startsWith('locked') || field.startsWith('prunable'))) return false - const head = await run(path, ['symbolic-ref', 'HEAD']) + const head = await git.read(path, ['symbolic-ref', 'HEAD']) if (head.stdout.trim() !== `refs/heads/${branch}`) return false - const status = await run(path, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=none']) - if (status.stdout.length !== 0) return false - // Git status deliberately hides skip-worktree and assume-unchanged files. - const flags = await run(path, ['ls-files', '-v', '-z']) - if (flags.stdout.split('\0').some(entry => entry.length > 0 && (entry[0] === 'S' || /^[a-z]/.test(entry)))) return false - const index = await run(path, ['ls-files', '--stage', '-z']) - if (index.stdout.split('\0').some(entry => entry.startsWith('160000 '))) return false - return true + const changed = await git.scan(path, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=none'], () => false) + if (changed) return false + // Git refuses removal whenever this directory exists, populated or not. + const modules = await git.read(path, ['rev-parse', '--git-path', 'modules']) + return await ctx.fs.lstat(modules.stdout.replace(/\r?\n$/, ''), { cwd: path }, signal) === undefined } diff --git a/packages/experimental/worktree/tests/archive.spec.ts b/packages/experimental/worktree/tests/archive.spec.ts index e2b5c8d47a..d8d18c91ed 100644 --- a/packages/experimental/worktree/tests/archive.spec.ts +++ b/packages/experimental/worktree/tests/archive.spec.ts @@ -63,7 +63,7 @@ function agentFor(ctx: Context, session: Session): Agent { return agent } -async function fixture(options: { cache?: boolean; retainOnArchive?: boolean } = {}) { +async function fixture(options: { cache?: boolean; retainOnArchive?: boolean; maxOutputBytes?: number } = {}) { const temporary = await realpath(await mkdtemp(join(tmpdir(), 'dsh-worktree-archive-'))) cleanups.push(() => rm(temporary, { recursive: true, force: true })) const root = await repository(temporary) @@ -87,7 +87,8 @@ async function fixture(options: { cache?: boolean; retainOnArchive?: boolean } = ctx.provide('storageDomain', domain) if (options.cache === true) await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 1_000, writeIntervalMs: 60_000 }) await ctx.plugin(WorkspaceRegistry) - const worktrees = ctx.plugin(WorktreeService, options.retainOnArchive === undefined ? {} : { retainOnArchive: options.retainOnArchive }) + const { cache: _cache, ...config } = options + const worktrees = ctx.plugin(WorktreeService, config) await worktrees const session = ctx.sessions.create(SessionId('archive-owner'), { meta: { cwd: root } }) const agent = agentFor(ctx, session) @@ -137,6 +138,39 @@ describe('archive-triggered worktree cleanup', () => { expect(f.ctx.workspaceRegistry.archivedSessionIds).toContain(f.session.id) }) + it('removes a clean checkout whose file listing exceeds maxOutputBytes', async () => { + const f = await fixture({ maxOutputBytes: 1_024 }) + for (let index = 0; index < 64; index++) { + await writeFile(join(f.worktree.path, `file-${String(index).padStart(3, '0')}-${'x'.repeat(24)}.txt`), `${index}\n`) + } + await git(f.worktree.path, 'add', '.') + await git(f.worktree.path, 'commit', '-m', 'many files') + expect((await git(f.worktree.path, 'ls-files', '-z')).length).toBeGreaterThan(1_024) + await f.ctx.workspaceRegistry.archiveSession(f.session.id) + expect(await settled(f)).toMatchObject({ status: 'removed' }) + await expect(access(f.worktree.path)).rejects.toMatchObject({ code: 'ENOENT' }) + }) + + it('retains a checkout whose status output exceeds maxOutputBytes instead of failing', async () => { + const f = await fixture({ maxOutputBytes: 1_024 }) + for (let index = 0; index < 64; index++) { + await writeFile(join(f.worktree.path, `untracked-${String(index).padStart(3, '0')}-${'x'.repeat(24)}.txt`), `${index}\n`) + } + expect((await git(f.worktree.path, 'status', '--porcelain', '-z', '--untracked-files=all')).length).toBeGreaterThan(1_024) + await f.ctx.workspaceRegistry.archiveSession(f.session.id) + expect(await settled(f)).toMatchObject({ status: 'retained' }) + await access(join(f.worktree.path, 'untracked-000-xxxxxxxxxxxxxxxxxxxxxxxx.txt')) + }) + + it('removes a clean checkout when the worktree listing exceeds maxOutputBytes', async () => { + const f = await fixture({ maxOutputBytes: 1_024 }) + for (let index = 0; index < 8; index++) await git(f.root, 'worktree', 'add', '--detach', join(f.temporary, `extra-${index}`)) + expect((await git(f.root, 'worktree', 'list', '--porcelain', '-z')).length).toBeGreaterThan(1_024) + await f.ctx.workspaceRegistry.archiveSession(f.session.id) + expect(await settled(f)).toMatchObject({ status: 'removed' }) + await expect(access(f.worktree.path)).rejects.toMatchObject({ code: 'ENOENT' }) + }) + it('returns from admission before the inspection runs', async () => { const f = await fixture() const release = Promise.withResolvers() diff --git a/packages/experimental/worktree/tests/process.spec.ts b/packages/experimental/worktree/tests/process.spec.ts new file mode 100644 index 0000000000..1ccc614dc7 --- /dev/null +++ b/packages/experimental/worktree/tests/process.spec.ts @@ -0,0 +1,60 @@ +import { rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import { scanCommand } from '../src/process.ts' +import { harness, repository } from './harness.ts' + +const disposers: (() => Promise)[] = [] +afterEach(async () => { + for (const dispose of disposers.splice(0).reverse()) await dispose() +}) + +/** + * Make `done` reject once `terminate()` is called, as the SSH provider does + * when it cancels a launch whose start it has not yet acknowledged. + */ +function rejectDoneOnTerminate(ctx: Context): void { + const spawn = ctx.subprocess.spawn.bind(ctx.subprocess) + vi.spyOn(ctx.subprocess, 'spawn').mockImplementation((spec) => { + const handle = spawn(spec) + let cancelled: Promise | undefined + return { + get stdin() { return handle.stdin }, + get stdout() { return handle.stdout }, + get stderr() { return handle.stderr }, + get control() { return handle.control }, + get collected() { return handle.collected }, + get done() { return cancelled === undefined ? handle.done : Promise.race([handle.done, cancelled]) }, + terminate() { + cancelled ??= Promise.reject(new Error('SSH process terminated before launch acknowledgement')) + handle.terminate() + }, + waitForExit: signal => handle.waitForExit(signal), + } + }) +} + +describe('streamed commands', () => { + it('returns the early answer when stopping rejects the outcome of an unacknowledged launch', async () => { + const root = await repository() + disposers.push(() => rm(root, { recursive: true, force: true })) + const ctx = await harness(root) + disposers.push(() => ctx.fiber.dispose()) + await writeFile(join(root, 'untracked.txt'), 'dirty\n') + rejectDoneOnTerminate(ctx) + const fields: string[] = [] + + const stopped = await scanCommand( + ctx, { timeoutMs: 30_000, graceMs: 1_000, maxOutputBytes: 1_024 }, ctx.sandboxPolicy.resolve(), root, + ['git', 'status', '--porcelain=v1', '-z', '--untracked-files=all'], new AbortController().signal, + (field) => { + fields.push(field) + return false + }, + ) + + expect(stopped).toBe(true) + expect(fields).toEqual(['?? untracked.txt']) + }) +}) diff --git a/packages/experimental/worktree/tests/removal.spec.ts b/packages/experimental/worktree/tests/removal.spec.ts index d4afb66f85..383b7f4c1d 100644 --- a/packages/experimental/worktree/tests/removal.spec.ts +++ b/packages/experimental/worktree/tests/removal.spec.ts @@ -4,16 +4,26 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { inspectRemoval, removeCheckout } from '../src/removal.ts' -import type { GitRead } from '../src/removal.ts' +import type { GitCommands, GitRead, GitScan } from '../src/removal.ts' import type { RestoreWorktreeRequest } from '../src/types.ts' import { git, harness, repository, testAgent } from './harness.ts' /** A Git runner over the fixture's unconfined git, as the service's danger-full-access runner behaves. */ const run: GitRead = async (directory, args) => ({ stdout: await git(directory, ...args), exitCode: 0 }) +/** Pass each NUL-terminated field of `text` to `onField` as the streaming runner does; true when it stopped early. */ +function scanText(text: string, onField: (field: string) => boolean): boolean { + return !text.split('\0').slice(0, -1).every(field => onField(field)) +} + +/** A streaming runner over the same git; it reads the output whole, then passes its fields in order. */ +const scan: GitScan = async (directory, args, onField) => scanText(await git(directory, ...args), onField) + +const commands: GitCommands = { read: run, scan } + /** The inspection-and-removal step archive cleanup runs, with the pool the harness configures. */ function remove(ctx: Context, _agent: Agent, request: RestoreWorktreeRequest, admit: () => boolean = () => true): Promise { - return removeCheckout(ctx, '.agents/worktrees', request, run, new AbortController().signal, admit) + return removeCheckout(ctx, '.agents/worktrees', request, commands, new AbortController().signal, admit) } const disposers: (() => Promise)[] = [] @@ -48,21 +58,70 @@ describe('safe worktree removal', () => { expect(await git(worktree.path, 'rev-parse', 'HEAD')).toBe(head) }) - it.each(['modified', 'staged', 'untracked', 'assume-unchanged', 'skip-worktree'] as const)( + it.each(['modified', 'staged', 'untracked'] as const)( 'retains %s files', async (kind) => { const { ctx, agent, worktree } = await fixture() - const tracked = join(worktree.path, 'tracked.txt') if (kind === 'untracked') await writeFile(join(worktree.path, 'new.txt'), 'keep') else { - await writeFile(tracked, 'keep\n') + await writeFile(join(worktree.path, 'tracked.txt'), 'keep\n') if (kind === 'staged') await git(worktree.path, 'add', 'tracked.txt') - if (kind === 'assume-unchanged' || kind === 'skip-worktree') await git(worktree.path, 'update-index', `--${kind}`, 'tracked.txt') } expect(await remove(ctx, agent, worktree)).toBe(false) await access(worktree.path) }, ) + it.each(['assume-unchanged', 'skip-worktree'] as const)( + 'removes a checkout whose only edits are to %s files, which git status hides', async (flag) => { + const { ctx, agent, worktree } = await fixture() + await writeFile(join(worktree.path, 'tracked.txt'), 'hidden edit\n') + await git(worktree.path, 'update-index', `--${flag}`, 'tracked.txt') + expect(await git(worktree.path, 'status', '--porcelain')).toBe('') + expect(await remove(ctx, agent, worktree)).toBe(true) + await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' }) + }, + ) + + it('retains a checkout holding a submodule repository, which Git refuses to remove', async () => { + const { ctx, agent, worktree, root } = await fixture() + const source = await repository() + disposers.push(() => rm(source, { recursive: true, force: true })) + await git(worktree.path, '-c', 'protocol.file.allow=always', 'submodule', 'add', source, 'nested') + await git(worktree.path, 'commit', '-m', 'submodule') + expect(await git(worktree.path, 'status', '--porcelain')).toBe('') + expect(await remove(ctx, agent, worktree)).toBe(false) + await access(join(worktree.path, 'nested', 'tracked.txt')) + await expect(git(root, 'worktree', 'remove', worktree.path)).rejects.toThrow('working trees containing submodules cannot be moved or removed') + }) + + it('removes a checkout whose submodule was never initialized there, as Git does', async () => { + const root = await repository() + disposers.push(() => rm(root, { recursive: true, force: true })) + const source = await repository() + disposers.push(() => rm(source, { recursive: true, force: true })) + await git(root, '-c', 'protocol.file.allow=always', 'submodule', 'add', source, 'nested') + await git(root, 'commit', '-m', 'submodule') + const ctx = await harness(root) + disposers.push(() => ctx.fiber.dispose()) + const agent = testAgent(ctx, root) + const worktree = await ctx.worktrees.create(agent, { name: 'archive-me' }) + expect(await git(worktree.path, 'ls-files', '--stage', 'nested')).toMatch(/^160000 /) + expect(await remove(ctx, agent, worktree)).toBe(true) + await expect(access(worktree.path)).rejects.toMatchObject({ code: 'ENOENT' }) + }) + + it('leaves a committed embedded repository to Git, which refuses the removal', async () => { + const { ctx, agent, worktree } = await fixture() + const source = await repository() + disposers.push(() => rm(source, { recursive: true, force: true })) + await git(worktree.path, 'clone', source, 'nested') + await git(worktree.path, 'add', '-A') + await git(worktree.path, 'commit', '-m', 'embedded repository') + expect(await git(worktree.path, 'status', '--porcelain')).toBe('') + await expect(remove(ctx, agent, worktree)).rejects.toThrow('working trees containing submodules cannot be moved or removed') + await access(join(worktree.path, 'nested', 'tracked.txt')) + }) + it('removes a checkout that holds only ignored files, as Git does without force', async () => { const { ctx, agent, worktree } = await fixture() await git(worktree.path, 'config', 'core.excludesFile', join(worktree.repositoryRoot, 'exclude')) @@ -94,17 +153,18 @@ describe('safe worktree removal', () => { }, ) - it.each(['repository identity', 'registration', 'checked-out branch', 'submodule'] as const)( + it.each(['repository identity', 'registration', 'checked-out branch'] as const)( 'retains a checkout when the %s changes during inspection', async (changed) => { const { ctx, worktree, root } = await fixture() - const run = vi.fn(async (directory: string, args: string[]) => { + const read = vi.fn(async (directory: string, args: string[]) => { if (changed === 'repository identity' && args[0] === 'rev-parse') return { stdout: worktree.path, exitCode: 0 } - if (changed === 'registration' && args[0] === 'worktree') return { stdout: `worktree ${root}\0branch refs/heads/main\0\0\0`, exitCode: 0 } if (changed === 'checked-out branch' && args[0] === 'symbolic-ref') return { stdout: 'refs/heads/other', exitCode: 0 } - if (changed === 'submodule' && args.includes('--stage')) return { stdout: `160000 ${worktree.baseCommit} 0\tsubmodule\0`, exitCode: 0 } return { stdout: await git(directory, ...args), exitCode: 0 } }) - expect(await inspectRemoval(ctx, '.agents/worktrees', worktree, run, new AbortController().signal)).toBe(false) + const listed: GitScan = async (directory, args, onField) => changed === 'registration' && args[0] === 'worktree' + ? scanText(`worktree ${root}\0branch refs/heads/main\0\0`, onField) + : await scan(directory, args, onField) + expect(await inspectRemoval(ctx, '.agents/worktrees', worktree, { read, scan: listed }, new AbortController().signal)).toBe(false) await access(worktree.path) }, ) diff --git a/packages/experimental/worktree/tests/worktree.spec.ts b/packages/experimental/worktree/tests/worktree.spec.ts index c1beb17c4a..33c9b84f21 100644 --- a/packages/experimental/worktree/tests/worktree.spec.ts +++ b/packages/experimental/worktree/tests/worktree.spec.ts @@ -414,6 +414,22 @@ describe('restoring removed worktrees', () => { expect(ctx.workingDirectory.get(agent.session)).toBe(root) }) + it('finds the stale registration when the worktree listing exceeds maxOutputBytes', async () => { + const root = await repo() + ctx = await harness(root, { maxOutputBytes: 1_024 }) + const agent = testAgent(ctx, root) + const created = await ctx.worktrees.create(agent, { name: 'topic' }) + await ctx.workingDirectory.set(agent, root) + for (let index = 0; index < 8; index++) await git(root, 'worktree', 'add', '--detach', join(root, '.agents/worktrees', `extra-${index}`)) + expect((await git(root, 'worktree', 'list', '--porcelain', '-z')).length).toBeGreaterThan(1_024) + await rm(created.path, { recursive: true, force: true }) + + expect(await ctx.worktrees.restore(agent, created)).toEqual({ path: created.path, branchRecreated: false }) + + expect(await git(created.path, 'symbolic-ref', '--short', 'HEAD')).toBe('topic') + expect(await registered(root)).toContain(gitPath(created.path)) + }) + it('creates a deleted branch again at its base commit, without the commits it had gained', async () => { const root = await repo() ctx = await harness(root) diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 1d444f3c2f..913f55dcbb 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -677,7 +677,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ISession', - declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(): Promise;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', + declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(options?: {\n deferConsumption?: boolean;\n }): Promise;\n consumeOlder(): boolean;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', }, { name: 'ISessions', @@ -969,7 +969,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionSnapshot', - declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly loadingOlder: boolean;\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', + declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly historyWasPartial: boolean;\n readonly loadingOlder: boolean;\n readonly historyLoadStatus: \'idle\' | \'loading\' | \'pendingConsumption\' | \'error\';\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', }, { name: 'SessionStandardProps', @@ -985,7 +985,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SlotCore', - declaration: 'export class SlotCore {\n constructor();\n readonly registerFactory: RegisterFactory;\n factory(name: string): StoredFactory | undefined;\n factoryVersion(name: string): number;\n subscribeFactory(name: string, listener: () => void): () => void;\n isFactoryLive(definition: StoredFactory): boolean;\n register = EntryKeyOf, const D extends ChildrenDecl = Record, H extends StoreDecl | undefined = undefined, M = never, N extends (keyof LocaleNamespaceMap & string) | undefined = undefined, C extends SlotComponent = SlotComponent>(options: BaseOptions & {\n inject?: undefined;\n }, component: C & SlotComponent, keyof NoInfer & keyof SlotMap & string, HandleOf>, object, NoInfer, NoInfer>> & RendersCheck): () => void;\n register = EntryKeyOf, const D extends ChildrenDecl = Record, H extends StoreDecl | undefined = undefined, M = never, N extends (keyof LocaleNamespaceMap & string) | undefined = undefined, C extends SlotComponent = SlotComponent>(options: BaseOptions & {\n inject: (...args: InjectParams) => I;\n }, component: C & SlotComponent, keyof NoInfer & keyof SlotMap & string, HandleOf>, I, NoInfer, NoInfer>> & RendersCheck): () => void;\n register(options: ErasedOptions, component: unknown): () => void;\n isLive(entry: StoredEntry): boolean;\n entries(key: string): readonly StoredEntry[];\n entriesOfSlot(key: string): readonly StoredEntry[];\n spec(key: K): SlotSpec | undefined;\n specDynamic(key: string): SlotSpec | undefined;\n snapshot(root?: string): LiveCompositionNode[];\n declarationEpoch(key: string): number;\n subscribe(key: string, fn: () => void): () => void;\n subscribeDeclaration(key: string, fn: () => void): () => void;\n getVersion(key: string): number;\n onMutate(fn: (key: string) => void): () => void;\n reportEntryError(key: string, entry: StoredEntry, error: unknown, info: {\n abdicate: boolean;\n }): void;\n reportFactoryError(name: string, registration: StoredEntry | StoredFactory, error: unknown): void;\n onEntryError(fn: (key: string, registration: StoredEntry | StoredFactory, error: unknown, info: {\n abdicated: boolean;\n }) => void): () => void;\n}', + declaration: 'export class SlotCore {\n constructor();\n readonly registerFactory: RegisterFactory;\n factory(name: string): StoredFactory | undefined;\n factoryVersion(name: string): number;\n subscribeFactory(name: string, listener: () => void): () => void;\n isFactoryLive(definition: StoredFactory): boolean;\n register = EntryKeyOf, const D extends ChildrenDecl = Record, H extends StoreDecl | undefined = undefined, M = never, N extends (keyof LocaleNamespaceMap & string) | undefined = undefined, C extends SlotComponent = SlotComponent>(options: BaseOptions & {\n inject?: undefined;\n }, component: C & SlotComponent, keyof NoInfer & keyof SlotMap & string, HandleOf>, object, NoInfer, NoInfer>> & RendersCheck): () => void;\n register = EntryKeyOf, const D extends ChildrenDecl = Record, H extends StoreDecl | undefined = undefined, M = never, N extends (keyof LocaleNamespaceMap & string) | undefined = undefined, C extends SlotComponent = SlotComponent>(options: BaseOptions & {\n inject: (...args: InjectParams) => I;\n }, component: C & SlotComponent, keyof NoInfer & keyof SlotMap & string, HandleOf>, I, NoInfer, NoInfer>> & RendersCheck): () => void;\n isLive(entry: StoredEntry): boolean;\n entries(key: string): readonly StoredEntry[];\n entriesOfSlot(key: string): readonly StoredEntry[];\n spec(key: K): SlotSpec | undefined;\n specDynamic(key: string): SlotSpec | undefined;\n snapshot(root?: string): LiveCompositionNode[];\n declarationEpoch(key: string): number;\n subscribe(key: string, fn: () => void): () => void;\n subscribeDeclaration(key: string, fn: () => void): () => void;\n getVersion(key: string): number;\n onMutate(fn: (key: string) => void): () => void;\n reportEntryError(key: string, entry: StoredEntry, error: unknown, info: {\n abdicate: boolean;\n }): void;\n reportFactoryError(name: string, registration: StoredEntry | StoredFactory, error: unknown): void;\n onEntryError(fn: (key: string, registration: StoredEntry | StoredFactory, error: unknown, info: {\n abdicated: boolean;\n }) => void): () => void;\n}', }, { name: 'SlotEntryDef', diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 27267a9b1b..36cbd48ee7 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -278,7 +278,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:495', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:498', }, { key: 'conversation.chat.commandview', @@ -332,7 +332,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:477', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:480', }, { key: 'conversation.chat.flow', @@ -379,7 +379,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:436', }, { key: 'conversation.chat.markdown.fence', @@ -445,7 +445,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'wraps-owner-content', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.markdown.fence\', () => ctx.slots.register(\n { name: \'conversation.chat.markdown.fence\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:430', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', }, { key: 'conversation.chat.message.images', @@ -492,7 +492,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:469', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:472', }, { key: 'conversation.chat.node', @@ -564,7 +564,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:445', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:448', }, { key: 'conversation.chat.reasoning.body', @@ -608,7 +608,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:483', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:486', }, { key: 'conversation.chat.text-interaction', @@ -660,7 +660,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.text-interaction\', () => ctx.slots.register(\n { name: \'conversation.chat.text-interaction\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:428', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:431', }, { key: 'conversation.chat.turnTail', @@ -727,7 +727,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:489', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:492', }, { key: 'conversation.chat.user.before', @@ -777,7 +777,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.before\', () => ctx.slots.register(\n { name: \'conversation.chat.user.before\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:459', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:462', }, { key: 'conversation.chat.user.images', @@ -824,7 +824,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:471', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:474', }, { key: 'conversation.composer', @@ -891,9 +891,10 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Resident composer body, including the no-Session inert state; fixed overlays must portal to\nthe document body because the docked composer contains them.', registerOptions: [], ownerProps: [ - '/** Owner share of the resident composer bar. */\nexport interface ComposerBarOwnerProps {\n /** Hero uses centered placement; composer uses the active bottom placement. */\n variant: \'hero\' | \'composer\'\n /** A feature-owned reason that makes message input inert while leaving model selection live. */\n blocked?: { readonly reason: string }\n /** Lock all message actions while preserving the resident composer surface. */\n disabled?: boolean\n /** Whether the shared Workspace picker is expanded. */\n workspacePickerOpen?: boolean\n /** Open the Workspace picker from the inert composer surface. */\n onRequestWorkspace?: () => void\n placeholder?: string\n /** Optional content rendered above the composer surface. */\n accessory?: ReactNode\n}', + '/** Owner share of the resident composer bar. */\nexport interface ComposerBarOwnerProps {\n /** Hero uses centered placement; composer uses the active bottom placement. */\n variant: \'hero\' | \'composer\'\n /** Conversation content occurrence rendering this composer; an unaddressed document paste reaches the main one. */\n occurrence: ConversationContentInputProps[\'variant\']\n /** A feature-owned reason that makes message input inert while leaving model selection live. */\n blocked?: { readonly reason: string }\n /** Lock all message actions while preserving the resident composer surface. */\n disabled?: boolean\n /** Whether the shared Workspace picker is expanded. */\n workspacePickerOpen?: boolean\n /** Open the Workspace picker from the inert composer surface. */\n onRequestWorkspace?: () => void\n placeholder?: string\n /** Optional content rendered above the composer surface. */\n accessory?: ReactNode\n}', ], ownerPropsReferences: [ + 'ConversationContentInputProps', 'Workspace', ], standardProps: [ @@ -3507,7 +3508,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Optional sidebar account launcher; opens the shell-owned settings panel.', registerOptions: [], ownerProps: [ - '/** Sidebar launcher geometry and settings navigation. */\nexport interface SettingsLauncherOwnerProps {\n /** Whether the sidebar shows labels. */\n wide: boolean\n /** Whether the settings dialog covers the sidebar; a launcher may treat a false-to-true edge as one Settings entry. */\n settingsOpen: boolean\n /** Effective Settings key labels and accessible combination; omitted when unbound. */\n settingsShortcut?: { readonly keys: readonly string[]; readonly aria?: string | undefined }\n /** Open the settings panel. */\n openSettings: () => void\n /** @param id - registered onboarding editor to open explicitly. */\n openOnboarding: (id: string) => void\n}', + '/** Sidebar launcher geometry and settings navigation. */\nexport interface SettingsLauncherOwnerProps {\n /** Whether the sidebar shows labels. */\n wide: boolean\n /** Whether the settings dialog covers the sidebar; a launcher may treat a false-to-true edge as one Settings entry. */\n settingsOpen: boolean\n /** Effective Settings key labels and accessible combination; omitted when unbound. */\n settingsShortcut?: { readonly keys: readonly string[]; readonly aria?: string | undefined }\n /** @param sectionId - section to open; absent uses the shell\'s default section. */\n openSettings: (sectionId?: string) => void\n /** @param id - registered onboarding editor to open explicitly. */\n openOnboarding: (id: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -3533,6 +3534,40 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.launcher\', () => ctx.slots.register(\n { name: \'settings.launcher\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-settings/src/client/contract/slots.ts:17', }, + { + key: 'settings.launcher.notifications', + kind: 'single', + scope: 'root', + summary: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', + doc: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', + registerOptions: [], + ownerProps: [ + '/** Account-menu presentation facts supplied to its notification extension. */\nexport interface AccountNotificationsOwnerProps {\n /** Whether the account menu can display notifications outside onboarding. */\n active: boolean\n /** Open the account section in the existing settings shell. */\n openAccount: () => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'settings.launcher\' (client-ui-settings-account), so it exists while that entry is mounted', + occupants: [ + 'client-ui-account-notifications AccountNotifications', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.launcher.notifications\', () => ctx.slots.register(\n { name: \'settings.launcher.notifications\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-settings-account/src/client/account-ui.ts:47', + }, { key: 'settings.models.footer', kind: 'list', @@ -4081,7 +4116,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:503', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:506', }, { key: 'sidebar', @@ -4847,7 +4882,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.files.actions\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.files.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-sidebar-files/src/client/index.ts:39', + source: 'packages/client/ui-sidebar-files/src/client/index.ts:46', }, { key: 'sidebar.right.tab.guide', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index e182793ce2..03d088a96a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -844,9 +844,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'abstract describe(ref: CredentialRef): Promise', - description: 'Describe one reference for configuration surfaces without exposing the value.', + description: 'Describe one reference for configuration surfaces without exposing the full value.', parameters: [{ name: 'ref', description: 'the reference to describe.' }], - returns: 'configured state, supplying source, and writability.', + returns: 'configured state, supplying source, writability, and optional masked preview.', }, { signature: 'abstract set(ref: CredentialRef, value: string): Promise', @@ -892,7 +892,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'credentialsController', summary: 'Host service backing the generated `ctx.remote.credentials` namespace.', - description: '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.', + description: '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.', methods: [ { signature: '@Remote async describe(refs: string[]): Promise>', @@ -978,86 +978,110 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'deepseekAccount', - summary: 'Account operations; only Host consumers can obtain a request credential.', - description: 'Account operations; only Host consumers can obtain a request credential.', + summary: 'Account login, credentials, and client-safe Remote operations.', + description: 'Account login, credentials, and client-safe Remote operations.', methods: [ { - signature: 'abstract getState(): Promise', + signature: '@Remote async getState(): Promise', description: 'Read stored-account presence and the latest login attempt.', parameters: [], returns: 'a snapshot without credentials or PKCE secrets.', }, { - signature: 'abstract getProfile(client: AccountClientMetadata): Promise', + signature: '@Remote async getProfile(client: AccountClientMetadata): Promise', description: 'Query Platform profile independently of wallet balances. A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch consumers, so they re-read getPlatformSession; repeated IDs stay silent.', parameters: [{ name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'profile outcome, or null if signed out or the grant changed during the query.', }, { - signature: 'abstract getBalance(client: AccountClientMetadata): Promise', + signature: '@Remote getBalance(client: AccountClientMetadata): Promise', description: 'Query Platform recharge and bonus wallet balances independently of profile data.', parameters: [{ name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'balance outcome, or null if signed out or the grant changed during the query.', }, { - signature: 'abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise', - description: 'Query the granted bonuses Platform has not yet recorded as displayed.', + signature: '@Remote async getNotifications(client: AccountClientMetadata): Promise', + description: 'Query unconsumed account notifications in server order without reading profile data.', parameters: [{ name: 'client', description: '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.', }, { - signature: 'abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise', - description: 'Record one displayed bonus as notified for the account it belongs to.', - parameters: [{ name: 'accountId', description: 'account the notification was read for; a different current account is never acknowledged.' }, { name: 'orderId', description: 'granted bonus order the user saw.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }], - returns: 'true once Platform records the acknowledgement; false if signed out or the account changed.', + signature: '@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise', + description: 'Query localized content of a notification, including one already consumed.', + parameters: [{ name: 'id', description: 'notification whose content is requested.' }, { name: 'client', description: '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.', }, { - signature: 'abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', - description: 'Join an active attempt or start browser authorization.', - parameters: [{ name: 'client', description: 'identity of the requesting UI; a new attempt captures it, and joining retains the original attempt\'s identity.' }, { name: 'callbackOrigin', description: 'browser-accessible loopback HTTP origin, including any SSH local port.' }, { name: 'loginSource', description: 'initiating UI, used to return from a failed exchange.' }], - returns: 'the initial snapshot without waiting for browser approval.', + signature: '@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise', + description: 'Report a notification interaction; the backend decides consumption.', + parameters: [{ name: 'id', description: 'notification the user interacted with.' }, { name: 'event', description: 'displayed frame, non-dismiss action click, or explicit dismissal.' }, { name: 'client', description: '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.', }, { - signature: 'abstract cancelSignIn(id: SignInAttemptId): Promise', - description: 'Cancel only the named attempt; committing attempts settle before returning.', - parameters: [{ name: 'id', description: 'attempt identity from this Host.' }], - returns: 'state after cancellation or an already-started commit.', - }, - { - signature: 'abstract signOut(client: AccountClientMetadata): Promise', - description: 'Remove the local grant while retaining API keys; the provider revokes it in the background.', - parameters: [{ name: 'client', description: '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.', - }, - { - signature: 'abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable', - description: 'Subscribe to snapshots including a complete initial state.', - parameters: [{ name: 'signal', description: 'subscription lifetime; ending it never cancels login.' }, { name: 'includeIdentityChanges', description: 'also notify when cached Platform identity changes; defaults to false.' }], - returns: 'complete snapshots as account state changes.', - }, - { - signature: 'abstract resolveToken(url: string): Promise', - description: 'Resolve a credential only for the inference origin allowed by the provider.', - parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], - returns: 'stored token, or undefined for other origins or a signed-out account.', - }, - { - signature: 'abstract rejectToken(token: string): Promise', + signature: 'async rejectToken(token: string): Promise', description: 'Remove an inference-rejected token only while it still matches the stored login.', parameters: [{ name: 'token', description: 'token captured by the rejected inference request.' }], returns: 'after matching credentials are removed and the expiry notification is emitted.', }, { - signature: 'abstract getPlatformSession(): Promise', - description: '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.', + signature: 'async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', + description: 'Read existing login identity without creating a device or returning credentials.', + parameters: [], + returns: 'optional device/account identifiers and the provider\'s OS version string.', + }, + { + signature: 'async getPlatformSession(): Promise', + description: '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.', parameters: [], returns: 'a Host-only snapshot, or null while signed out or when the credential changed during the read.', }, { - signature: 'abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', - description: 'Read existing login identity without creating a device or returning credentials.', + signature: 'async resolveToken(url: string): Promise', + description: 'Resolve a credential only for the inference origin allowed by the provider.', + parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], + returns: 'stored token, or undefined for other origins or a signed-out account.', + }, + { + signature: '@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', + description: 'Join an active attempt or start browser authorization.', + parameters: [{ name: 'client', description: 'identity of the requesting UI; a new attempt captures it, and joining retains the original attempt\'s identity.' }, { name: 'callbackOrigin', description: 'browser-accessible loopback HTTP origin, including any SSH local port.' }, { name: 'loginSource', description: 'initiating UI, used to return from a failed exchange.' }], + returns: 'the initial snapshot without waiting for browser approval.', + }, + { + signature: '@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise', + description: 'Cancel only the named attempt; committing attempts settle before returning.', + parameters: [{ name: 'attemptId', description: 'attempt identity from this Host.' }], + returns: 'state after cancellation or an already-started commit.', + }, + { + signature: '@Remote signOut(client: AccountClientMetadata): Promise', + description: 'Remove the local grant while retaining API keys; the provider revokes it in the background.', + parameters: [{ name: 'client', description: '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.', + }, + { + signature: '@Remote hasRunningAccountTasks(): boolean', + description: 'Inspect running work before sign-out.', parameters: [], - returns: 'optional device/account identifiers and the provider\'s OS version string.', + returns: 'whether a running task\'s latest request uses the account route; false when the optional agents service is absent.', + }, + { + signature: '@Remote({ mode: \'stream\' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<\'session-expired\'>', + description: 'Subscribe to live credential expiry without replay.', + parameters: [{ name: 'signal', description: 'subscription lifetime; provider disposal also ends it.' }], + returns: 'expiry notifications emitted during the subscription.', + }, + { + signature: 'watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable', + description: 'Subscribe to ordered updates including a complete initial snapshot.', + parameters: [{ name: 'signal', description: 'subscription lifetime; ending it never cancels login.' }, { name: 'includeIdentityChanges', description: 'also notify when cached Platform identity changes; defaults to false.' }], + returns: 'complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce.', + }, + { + signature: '@Remote({ name: \'watch\', mode: \'stream\' }) watchState(signal: AbortSignal): AsyncIterable', + description: 'Stream account state without the Host-only identity subscription option.', + parameters: [{ name: 'signal', description: 'subscription lifetime.' }], + returns: 'initial state, login progress, and credential-change updates.', }, ], }, @@ -1246,10 +1270,24 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['on cancellation, provider disposal, or expiry of this read\'s own `fetchTimeoutMs` deadline.'], }, { - signature: 'async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise', - description: 'Read the changes of a change request as its host computes them.', + signature: 'async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise', + description: '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. When the latest status of a watched change request names `headSha`, its `baseSha` goes to the provider, which may then read the patch while it confirms the head.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'headSha', description: 'head commit the patch must describe, usually the head of the latest status.' }, { name: 'signal', description: 'cancellation of the read.' }], + 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.'], + }, + { + signature: 'async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise', + description: 'List the commits of a change request at its current head.', parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'signal', description: 'cancellation of the read.' }], - returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it.', + 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.'], + }, + { + signature: 'async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise', + description: 'Read the changes between two commits of a change request\'s repository.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'base', description: 'full object name of the commit compared from.' }, { name: 'head', description: 'full object name of a commit that descends from `base`.' }, { name: 'signal', description: '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.'], }, { @@ -1351,14 +1389,21 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, with Git using the Session\'s sandbox policy.', parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'which changes to read.' }, { name: 'signal', description: 'request cancellation.' }], 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 any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'], + 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/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.'], + }, + { + signature: '@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'base', description: 'the base ref of the `branch` scope, or null for its automatic fork point.' }, { name: 'signal', description: '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`.'], }, { signature: '@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise', - description: '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.', + description: 'Read the new side of one changed file in a scope, which supplies the unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of the `branch` scope, else the working tree.', parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'the scope the diff was read in.' }, { name: 'path', description: 'path relative to the checkout\'s top-level directory, as the diff names it.' }, { name: 'signal', description: '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.'], + throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; `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.'], }, { signature: '@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise', @@ -1368,11 +1413,18 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['`forgePanel/not-bound` for an invisible binding, `forgePanel/stale-head` for a moved head, or `forgePanel/checks-failed` when the provider cannot complete the read.'], }, { - signature: '@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise', - description: '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.', + signature: '@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise', + description: '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.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'signal', description: 'request cancellation.' }], - returns: 'the files, the head commit, 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/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.'], + 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-failed` when the host does not list them.'], + }, + { + signature: '@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise', + description: '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.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'commits', description: 'consecutive commits of the change request, or null for all of it.' }, { name: 'signal', description: '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.'], }, { signature: '@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise', @@ -4683,6 +4735,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'workspaceFileScope', description: 'header-derived workspace root for the Session identity on the wire.' }, { name: 'path', description: 'workspace path, absolute or relative to the workspace root.' }, { name: 'signal', description: 'caller cancellation.' }], returns: 'the directory\'s children in the backend\'s stable name order, bounded by the entry cap.', }, + { + signature: '@Remote async search( workspaceFileScope: WorkspaceFileScope, request: WorkspaceFileSearchRequest, signal: AbortSignal, ): Promise', + description: 'Search files and their inferred ancestor directories with packaged ripgrep. Native ignore rules apply unless disabled; VCS metadata, symlinks and empty directories are absent. Within the bounded set of listed files, matches sort by depth, then workspace-relative path.', + parameters: [{ name: 'workspaceFileScope', description: 'header-derived workspace root for the Session identity on the wire.' }, { name: 'request', description: 'the query, literal exclusions, and hidden/ignore switches.' }, { name: 'signal', description: 'caller cancellation, forwarded to the subprocess; rejection preserves its reason.' }], + returns: 'matches capped by search.maxResults; incomplete marks excess rg files or exit 2.', + throws: ['RemoteError `gateway/bad-request`: the query is blank.', 'RemoteError `workspace-file/not-found`: the workspace root does not exist.', 'RemoteError `workspace-file/not-directory`: the workspace root is not a directory.', 'RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out.'], + }, { signature: '@Remote({ mode: \'stream\' }) changes(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): AsyncIterable', description: 'Watch one file or a directory\'s direct entries in the Session\'s filesystem. Files use the backend\'s read authority; directories remain workspace-scoped.', @@ -5303,7 +5362,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ mode: 'emit', signature: '\'session/event\'(this: Scoped, session: Session, event: SessionEvent): void', summary: 'Post-commit, fire-and-forget append feed.', - description: 'Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent\'s context.', + description: 'Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent\'s context.', parameters: [{ name: 'session', description: 'the session whose log grew.' }, { name: 'event', description: 'the appended event, exactly as recorded.' }], }, { @@ -5550,18 +5609,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ /** Shapes of every exported type the Service and Event signatures reference (transitively), sorted by name. */ export const TYPE_API: readonly TypeApiEntry[] = [ - { - name: 'AccountBonusBatch', - declaration: 'export interface AccountBonusBatch {\n readonly accountId: AccountUserId;\n readonly bonuses: readonly AccountBonusNotification[];\n}', - }, - { - name: 'AccountBonusNotification', - declaration: 'export interface AccountBonusNotification {\n readonly title?: string;\n readonly orderId: AccountBonusOrderId;\n readonly campaign?: JsonValue;\n readonly amount?: JsonValue;\n readonly currency?: JsonValue;\n readonly grantedAt?: JsonValue;\n readonly expiresAt: string;\n readonly message: string;\n}', - }, - { - name: 'AccountBonusOrderId', - declaration: 'export type AccountBonusOrderId = Branded<\'AccountBonusOrderId\'>;', - }, { name: 'AccountClientMetadata', declaration: 'export interface AccountClientMetadata {\n readonly version: string;\n readonly locale: string;\n readonly timezoneOffsetSeconds: number;\n}', @@ -5574,10 +5621,34 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AccountLinks', declaration: 'export interface AccountLinks {\n readonly usageUrl: string;\n readonly topUpUrl: string;\n}', }, + { + name: 'AccountNotification', + declaration: 'export interface AccountNotification {\n readonly id: AccountNotificationId;\n readonly createdAt: string;\n readonly displayUntil: string | null;\n readonly title: string;\n readonly body: string;\n readonly actions: readonly AccountNotificationAction[];\n readonly data?: JsonValue;\n}', + }, + { + name: 'AccountNotificationAction', + declaration: 'export interface AccountNotificationAction {\n readonly label: string;\n readonly style: \'primary\' | \'secondary\';\n readonly target: {\n readonly type: \'app_route\';\n readonly name: \'account\';\n } | {\n readonly type: \'dismiss\';\n };\n}', + }, + { + name: 'AccountNotificationBatch', + declaration: 'export interface AccountNotificationBatch {\n readonly nextPollAfterSeconds: number;\n readonly notifications: readonly AccountNotification[];\n}', + }, + { + name: 'AccountNotificationEvent', + declaration: 'export type AccountNotificationEvent = \'displayed\' | \'cta_clicked\' | \'dismissed\';', + }, + { + name: 'AccountNotificationId', + declaration: 'export type AccountNotificationId = Branded<\'AccountNotificationId\'>;', + }, { name: 'AccountProfile', declaration: 'export interface AccountProfile {\n readonly id: AccountUserId | null;\n readonly name: string | null;\n readonly contact: string | null;\n readonly avatarUrl?: string | null;\n}', }, + { + name: 'AccountUpdate', + declaration: 'export interface AccountUpdate {\n readonly type: \'snapshot\' | \'credentials-changed\';\n readonly state: AccountView;\n}', + }, { name: 'AccountUserId', declaration: 'export type AccountUserId = Branded<\'AccountUserId\'>;', @@ -5956,7 +6027,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ChangeRequestSnapshot', - declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly unresolvedThreads: number;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', + declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly baseSha?: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly unresolvedThreads: number;\n readonly threadsTruncated: boolean;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', }, { name: 'ChangeRequestState', @@ -6280,7 +6351,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CredentialInfo', - declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}', + declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n masked?: string;\n}', }, { name: 'CredentialKey', @@ -6590,9 +6661,21 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeCheckoutState', declaration: 'export type ForgeCheckoutState = {\n readonly state: \'pending\';\n} | {\n readonly state: \'none\';\n} | {\n readonly state: \'failed\';\n readonly message: string;\n} | {\n readonly state: \'ready\';\n readonly checkout: ForgeCheckout;\n};', }, + { + name: 'ForgeCommit', + declaration: 'export interface ForgeCommit {\n readonly sha: string;\n readonly parent: string | null;\n readonly title: string;\n readonly author: string | null;\n readonly authoredAt: string;\n}', + }, + { + name: 'ForgeCommitList', + declaration: 'export interface ForgeCommitList {\n readonly headSha: string;\n readonly commits: readonly ForgeCommit[];\n readonly truncated: boolean;\n}', + }, + { + name: 'ForgeCommitRange', + declaration: 'export interface ForgeCommitRange {\n readonly from: string;\n readonly to: string;\n}', + }, { name: 'ForgeDiffFile', - declaration: 'export interface ForgeDiffFile {\n readonly path: string;\n readonly previousPath: string | null;\n readonly status: ForgeDiffStatus;\n readonly binary: boolean;\n readonly oversized: boolean;\n readonly untracked: boolean;\n readonly additions: number;\n readonly deletions: number;\n readonly hunks: readonly ForgeDiffHunk[];\n}', + declaration: 'export interface ForgeDiffFile {\n readonly path: string;\n readonly previousPath: string | null;\n readonly status: ForgeDiffStatus;\n readonly binary: boolean;\n readonly oversized: boolean;\n readonly untracked: boolean;\n readonly additions: number;\n readonly deletions: number;\n readonly hunks: readonly ForgeDiffHunk[];\n readonly layer: ForgeFileLayer;\n readonly digest: string;\n}', }, { name: 'ForgeDiffHunk', @@ -6604,7 +6687,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeFailure', - declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'unavailable\';\n readonly message: string;\n}', + declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unavailable\';\n readonly message: string;\n}', + }, + { + name: 'ForgeFileLayer', + declaration: 'export type ForgeFileLayer = \'interface\' | \'implementation\' | \'test\';', }, { name: 'ForgeLineComment', @@ -6614,13 +6701,17 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeLocalChanges', declaration: 'export interface ForgeLocalChanges {\n readonly base: string;\n readonly files: readonly ForgeChangedFile[];\n}', }, + { + name: 'ForgeLocalCommits', + declaration: 'export interface ForgeLocalCommits {\n readonly headSha: string;\n readonly commits: readonly ForgeCommit[];\n readonly truncated: boolean;\n}', + }, { name: 'ForgeLocalDiff', declaration: 'export interface ForgeLocalDiff {\n readonly base: string | null;\n readonly files: readonly ForgeDiffFile[];\n readonly omitted: number;\n}', }, { name: 'ForgeLocalScope', - declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n readonly base: string | null;\n} | {\n readonly kind: \'uncommitted\';\n} | {\n readonly kind: \'unstaged\';\n} | {\n readonly kind: \'staged\';\n};', + declaration: 'export type ForgeLocalScope = {\n readonly kind: \'branch\';\n readonly base: string | null;\n readonly commits: ForgeCommitRange | null;\n} | {\n readonly kind: \'uncommitted\';\n} | {\n readonly kind: \'unstaged\';\n} | {\n readonly kind: \'staged\';\n};', }, { name: 'ForgeMissingWorktree', @@ -6640,7 +6731,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeProvider', - declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n}', + declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal, base?: string): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n compare?(ref: ChangeRequestRef, base: string, /* …truncated — full shape in source */', }, { name: 'ForgeReadiness', @@ -8448,7 +8539,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Session', - declaration: 'export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n readonly inheritedEventCount: SessionLogOffset;\n get id(): SessionId;\n readonly firstLiveSeq: SessionLogOffset;\n readonly firstLifecycleSeq: SessionLogOffset;\n static create(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader, inheritedEventCount?: SessionLogOffset, projections?: readonly SessionMessageProjection[]): Session;\n static fromRestore(id: SessionId, seed: readonly SessionEvent[], header: SessionHeader, inheritedEventCount: SessionLogOffset, eventState: SessionSeedEventState, projections?: readonly SessionMessageProjection[]): Session;\n eventAt(seq: SessionSeq): SessionEvent | undefined;\n snapshotEvents(fromSeq: SessionLogOffset = SessionLogOffset(0), toSeqExclusive: SessionLogOffset = this.seq): readonly SessionEvent[];\n ownEvents(): readonly SessionEvent[];\n isOwnSeq(seq: SessionSeq): boolean;\n get seq(): SessionLogOffset;\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n requestContext(): RequestContext | undefined;\n toolHistory(): ToolHistory;\n deriveMessages(): Message[];\n deriveEventMessage(event: SessionEvent): Message | null;\n}', + declaration: 'export class Session {\n get surface(): SessionSurface;\n readonly header: SessionHeader;\n readonly inheritedEventCount: SessionLogOffset;\n get id(): SessionId;\n readonly firstLiveSeq: SessionLogOffset;\n readonly firstLifecycleSeq: SessionLogOffset;\n static create(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader, inheritedEventCount?: SessionLogOffset, projections?: readonly SessionMessageProjection[]): Session;\n static fromRestore(id: SessionId, seed: readonly SessionEvent[], header: SessionHeader, inheritedEventCount: SessionLogOffset, eventState: SessionSeedEventState, projections?: readonly SessionMessageProjection[]): Session;\n eventAt(seq: SessionSeq): SessionEvent | undefined;\n snapshotEvents(fromSeq: SessionLogOffset = SessionLogOffset(0), toSeqExclusive: SessionLogOffset = this.seq): readonly SessionEvent[];\n ownEvents(): readonly SessionEvent[];\n isOwnSeq(seq: SessionSeq): boolean;\n get seq(): SessionLogOffset;\n get currentBatchPublication(): SessionEvent | undefined;\n append(inputs: readonly SessionEventInput[]): readonly SessionEvent[];\n append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]): SessionEvent;\n requestHeader(): EpochHeader | undefined;\n requestContext(): RequestContext | undefined;\n toolHistory(): ToolHistory;\n deriveMessages(): Message[];\n deriveEventMessage(event: /* …truncated — full shape in source */', }, { name: 'SessionAccess', @@ -8554,6 +8645,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionEventFrame', declaration: 'export type SessionEventFrame = {\n readonly type: \'ready\';\n} | SessionEventEntry;', }, + { + name: 'SessionEventInput', + declaration: 'export type SessionEventInput = {\n [K in SessionEventType]: readonly [\n type: K,\n data: SessionEventMap[K],\n ...opts: K extends SurfaceEventType ? [\n opts: SurfaceIntent\n ] : [\n ]\n ];\n}[SessionEventType];', + }, { name: 'SessionEventMap', declaration: 'export interface SessionEventMap {\n \'turn/start\': {\n turn: number;\n };\n \'turn/end\': {\n turn: number;\n reason: TurnEndReason;\n };\n \'step/start\': {\n turn: number;\n step: number;\n };\n \'step/end\': {\n turn: number;\n step: number;\n };\n \'user/message\': UserMessage;\n \'developer/message\': {\n turn: number;\n step: number;\n message: DeveloperMessage;\n headerSeq?: SessionSeq;\n };\n \'system/message\': {\n turn: number;\n step: number;\n message: SystemMessage;\n };\n \'assistant/message\': {\n turn: number;\n step: number;\n message: AssistantMessage;\n stream: AssistantStreamRecord[];\n usage?: TokenUsage;\n interrupted?: true;\n };\n \'assistant/attempt\': {\n turn: number;\n step: number;\n stream: AssistantStreamRecord[];\n };\n \'tool/call\': {\n turn: number;\n step: number;\n callId: ToolCallId;\n name: string;\n arguments: string;\n };\n \'tool/result\': {\n turn: number;\n step: number;\n message: ToolResultMessage;\n error?: {\n name: string;\n code: string;\n reason?: string;\n };\n meta?: JsonValue;\n };\n \'request/header\': {\n header: EpochHeader;\n reason: RequestHeaderReason;\n startsSeries?: true;\n };\n \'request/context\': RequestContext;\n \'session/end-seed\': {\n /* …truncated — full shape in source */', @@ -9480,7 +9575,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SubagentRuntime', - declaration: 'export class SubagentRuntime extends TypertRemoteService {\n static Config;\n static inject;\n constructor(ctx: Context, private config: Config);\n resolveMaxDepth(configured?: number | \'provider-managed\'): number | undefined;\n startActivation(spec: SubagentActivationSpec & {\n readonly childId: SessionId;\n }): Promise;\n startActivation(spec: SubagentActivationSpec): Promise;\n async startActivation(spec: SubagentActivationSpec): Promise;\n rootOf(caller: Agent): Agent;\n namesOf(agent: Agent): SubagentMemberNames;\n async resolveName(caller: Agent, name: string, signal: AbortSignal): Promise;\n async waitForTreeWork(root: Agent): Promise;\n async sendMessage(sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async drainDescendants(parents: readonly Agent[]): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n @Remote({ name: \'prompt\', resources: { session: request => request.childSessionId } })\n async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise;\n @Remote({ name: \'interruptByUser\', resources: { session: childSessionId => childSess /* …truncated — full shape in source */', + declaration: 'export class SubagentRuntime extends TypertRemoteService {\n static Config;\n static inject;\n constructor(ctx: Context, private config: Config);\n resolveMaxDepth(configured?: number | \'provider-managed\'): number | undefined;\n startActivation(spec: SubagentActivationSpec & {\n readonly childId: SessionId;\n }): Promise;\n startActivation(spec: SubagentActivationSpec): Promise;\n rootOf(caller: Agent): Agent;\n namesOf(agent: Agent): SubagentMemberNames;\n async resolveName(caller: Agent, name: string, signal: AbortSignal): Promise;\n async waitForTreeWork(root: Agent): Promise;\n async sendMessage(sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions): Promise;\n interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;\n async drainDescendants(parents: readonly Agent[]): Promise;\n listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise;\n @Remote({ name: \'prompt\', resources: { session: request => request.childSessionId } })\n async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise;\n @Remote({ name: \'interruptByUser\', resources: { session: childSessionId => childSessionId } })\n interruptByUser(childSessionId: SessionId): SubagentInterruptReceipt;\n /* …truncated — full shape in source */', }, { name: 'SubagentSendMessageOptions', @@ -10450,6 +10545,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WorkspaceFileScope', declaration: 'export interface WorkspaceFileScope {\n readonly sessionId: SessionId;\n readonly workspaceRoot: string;\n}', }, + { + name: 'WorkspaceFileSearchMatch', + declaration: 'export interface WorkspaceFileSearchMatch {\n readonly path: string;\n readonly type: WorkspaceDirectoryEntry[\'type\'];\n}', + }, + { + name: 'WorkspaceFileSearchRequest', + declaration: 'export interface WorkspaceFileSearchRequest {\n readonly query: string;\n readonly excludedPaths: readonly string[];\n readonly includeHidden: boolean;\n readonly respectGitignore: boolean;\n}', + }, + { + name: 'WorkspaceFileSearchResult', + declaration: 'export interface WorkspaceFileSearchResult {\n readonly matches: readonly WorkspaceFileSearchMatch[];\n readonly truncated: boolean;\n readonly incomplete: boolean;\n}', + }, { name: 'WorkspaceFileStat', declaration: 'export interface WorkspaceFileStat {\n readonly absolutePath: string;\n readonly version: string;\n readonly bytes?: number;\n}', diff --git a/packages/extensions/tool-cordis/src/index.ts b/packages/extensions/tool-cordis/src/index.ts index eddc643cb9..9e7cd9bd77 100644 --- a/packages/extensions/tool-cordis/src/index.ts +++ b/packages/extensions/tool-cordis/src/index.ts @@ -32,6 +32,8 @@ export function apply(ctx: Context): void { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }], }, + // Listing reads the Provider registry without mutating it. + isConcurrencySafe: () => true, execute(_args, _exec): Promise { return Promise.resolve({ providers: ctx.cordisInspect.list() } as unknown as JsonValue) }, @@ -57,6 +59,8 @@ export function apply(ctx: Context): void { schema: { type: 'json' }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }], }, + // Provider methods are read-only, and each Client query settles by its own request id. + isConcurrencySafe: () => true, async execute(args, exec) { const data = await ctx.cordisInspect.query( args.platform, diff --git a/packages/extensions/tool-cordis/tests/host.spec.ts b/packages/extensions/tool-cordis/tests/host.spec.ts index d9aa417110..87830a4036 100644 --- a/packages/extensions/tool-cordis/tests/host.spec.ts +++ b/packages/extensions/tool-cordis/tests/host.spec.ts @@ -5,6 +5,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' import { describe, expect, it } from 'vitest' import * as CordisInspectProviders from '../src/host.ts' +import * as CordisInspectTools from '../src/index.ts' /** * The Host inspect providers are one process-global set: the host entry @@ -35,3 +36,14 @@ describe('the cordis-inspect-providers host entry', () => { expect(ctx.cordisInspect.list()).toEqual([]) }) }) + +describe('the cordis inspect tools', () => { + it('declares both read-only tools parallel-safe', async () => { + const ctx = await host() + const fiber = ctx.plugin(CordisInspectTools) + await fiber + expect(ctx.tools.get('cordis_inspect_list')?.isConcurrencySafe?.({})).toBe(true) + expect(ctx.tools.get('cordis_inspect_query')?.isConcurrencySafe?.({ platform: 'host', provider: 'Service', method: 'get' })).toBe(true) + await fiber.dispose() + }) +}) diff --git a/packages/fs/tool-fs-search/README.i18n.yaml b/packages/fs/tool-fs-search/README.i18n.yaml index b1c75185bb..dfbcdb5fc2 100644 --- a/packages/fs/tool-fs-search/README.i18n.yaml +++ b/packages/fs/tool-fs-search/README.i18n.yaml @@ -21,8 +21,8 @@ en: a5a01d14e0bec814 zh: 409298cfafd91b05 /deepseek-ai-dsh-tool-fs-search/use-this-package/the-tools: - en: 1932fbef1abcac77 - zh: 6d8060990b5f2f08 + en: d4a0419665d3c3b3 + zh: 7fe718b32401b4cd /deepseek-ai-dsh-tool-fs-search/use-this-package/configuration: en: 3e84e19a22aeb6c8 zh: 8ac44b21eb697f2f @@ -42,8 +42,8 @@ en: 5a30f023dd86c345 zh: 558b6e80c62648ba /deepseek-ai-dsh-tool-fs-search/understand-the-implementation/how-a-search-runs: - en: 7904c9f013272819 - zh: 656763e9a7e97c1e + en: f3fc47e0bec9091f + zh: af6723f131c40f10 /deepseek-ai-dsh-tool-fs-search/understand-the-implementation/native-mode-benchmark: en: 031654f59e63d07e zh: a3b488fb1880d2f5 diff --git a/packages/fs/tool-fs-search/README.md b/packages/fs/tool-fs-search/README.md index 4c26ffa018..79689f866a 100644 --- a/packages/fs/tool-fs-search/README.md +++ b/packages/fs/tool-fs-search/README.md @@ -52,6 +52,8 @@ A subprocess backend, then the tools; the spill backend is optional and makes ca Routine budgets stay out of the model-facing schema: a model that needs surrounding context reads the matched file with `read`, and one that needs later results follows the returned spill locator's retrieval hint. +Both tools opt into concurrent scheduling with sibling parallel-safe calls. A search records no file observation, over-cap spilling runs in the model-ordered post-execute phase, and working-directory recovery is serialized per Session by the working-directory service. + ### Configuration `sampleOverCapGlobResults` is required; the remaining keys are optional search caps with the defaults below. @@ -107,7 +109,7 @@ Local workspace discovery is naturally a process-backed `rg` workflow, and putti Without an explicit `path`, `glob` prunes unrelated subtrees for patterns such as `packages/core/src/*.ts` when every directory component is a plain relative name outside VCS metadata. Ordered ripgrep globs exclude the tree, admit directories with the prefix's distinct names, then apply the original file pattern. Same-named directories elsewhere may also be traversed, but only the original pattern admits files. The added arguments are capped at 8 KiB; larger sets use the original traversal. The search root, path separators, symlink handling, matching, and modification-time ordering stay unchanged; other patterns retain the original traversal. -Each call resolves the packaged binary (`@vscode/ripgrep`, or the executable's `-rg` sidecar in a pkg single-file runtime), prepends `--no-config` so a host `RIPGREP_CONFIG_PATH` cannot inject a `--pre` preprocessor into the unconfined spawn, and passes every model-controlled value as a plain argv element — no shell layer exists, so no quoting applies. Collect-mode budgets bound complete stdout and a stderr tail; a lossy stdout read fails as `SEARCH_RAW_OUTPUT_OVERFLOW` rather than parsing a silently-partial stream. The tools never read a raw spill path. +Each call resolves and starts the packaged binary through the shared [ripgrep library](../../util/ripgrep/README.md), which prepends `--no-config` to prevent configuration-driven preprocessors. Model-controlled values remain plain argv elements without shell quoting. Collect-mode budgets bound complete stdout and a stderr tail; a lossy stdout read fails as `SEARCH_RAW_OUTPUT_OVERFLOW` rather than parsing a silently-partial stream. The tools never read a raw spill path. ### Native-mode benchmark diff --git a/packages/fs/tool-fs-search/README.zh.md b/packages/fs/tool-fs-search/README.zh.md index 10cae42308..31059be780 100644 --- a/packages/fs/tool-fs-search/README.zh.md +++ b/packages/fs/tool-fs-search/README.zh.md @@ -52,6 +52,8 @@ kind: "package-reference" 常规预算不进入面向模型的 schema:需要周边上下文的模型用 `read` 读取匹配文件,需要后续结果的模型遵循返回的 spill locator 检索提示。 +两个工具都选择与同批并行安全调用并发调度。搜索不记录文件观察,超出上限的 spill 在按模型顺序执行的 post-execute 阶段运行,工作目录恢复由工作目录服务按会话串行化。 + ### 配置 `sampleOverCapGlobResults` 为必填;其余键是可选的搜索上限,默认值如下。 @@ -107,7 +109,7 @@ Node 部署在受支持的 macOS、Linux 与 Windows 目标上获得 `@vscode/ri 未显式提供 `path` 时,如果目录部分的每一项都是普通相对名称且不属于 VCS 元数据目录,`glob` 会为 `packages/core/src/*.ts` 这样的模式跳过无关子树。按顺序添加的 ripgrep glob 先排除目录树,再按前缀中去重后的名称放行目录,最后应用原始文件模式。其他位置的同名目录也可能被遍历,但文件仍只按原模式匹配。新增参数上限为 8 KiB,超过时沿用原遍历方式。搜索根目录、路径分隔符、符号链接处理、匹配规则和修改时间排序保持不变;其他模式仍按原方式遍历。 -每次调用解析打包二进制(`@vscode/ripgrep`,或 pkg 单文件运行时中可执行程序的 `-rg` 伴随文件),前置 `--no-config`,使宿主的 `RIPGREP_CONFIG_PATH` 无法向不受约束的 spawn 注入 `--pre` 预处理器,并把每个模型控制的值作为普通 argv 元素传入——不存在 shell 层,因此不涉及 shell 引号处理。collect 模式预算限制完整 stdout 与 stderr 尾部;lossy stdout 读取以 `SEARCH_RAW_OUTPUT_OVERFLOW` 失败,而不是解析静默不完整的流。工具从不读取原始 spill 路径。 +每次调用通过共享的 [ripgrep 库](../../util/ripgrep/README.zh.md) 解析并启动打包二进制,由它前置 `--no-config` 防止配置启用预处理程序。模型控制的值作为普通 argv 元素传入,不经过 shell 引号处理。collect 模式预算限制完整 stdout 与 stderr 尾部;lossy stdout 读取以 `SEARCH_RAW_OUTPUT_OVERFLOW` 失败,而不是解析静默不完整的流。工具从不读取原始 spill 路径。 ### Native 模式 benchmark diff --git a/packages/fs/tool-fs-search/package.json b/packages/fs/tool-fs-search/package.json index 29e776f7a3..1649d99a4c 100644 --- a/packages/fs/tool-fs-search/package.json +++ b/packages/fs/tool-fs-search/package.json @@ -32,8 +32,8 @@ ], "license": "MIT", "dependencies": { - "@vscode/ripgrep": "^1.18.0", - "@deepseek-ai/schemastery": "workspace:~" + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-util-ripgrep": "workspace:*" }, "peerDependencies": { "@deepseek-ai/dsh-llm": "workspace:*", @@ -63,6 +63,7 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*" + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@vscode/ripgrep": "^1.18.0" } } diff --git a/packages/fs/tool-fs-search/src/glob.ts b/packages/fs/tool-fs-search/src/glob.ts index 31df85aa53..2df74e0d0f 100644 --- a/packages/fs/tool-fs-search/src/glob.ts +++ b/packages/fs/tool-fs-search/src/glob.ts @@ -333,6 +333,8 @@ export function applyGlobTool(ctx: Context, caps: GlobToolCaps): void { path: { type: 'string', description: 'Directory to search in. Defaults to the session workspace; a relative path resolves against it.' }, }, timeoutMs: caps.timeoutMs, + // Path listing records no file observation; over-cap spilling runs in model-ordered post-execute. + isConcurrencySafe: () => true, output: { schema: { type: 'object', diff --git a/packages/fs/tool-fs-search/src/grep.ts b/packages/fs/tool-fs-search/src/grep.ts index e0246d6b76..03ca1bce44 100644 --- a/packages/fs/tool-fs-search/src/grep.ts +++ b/packages/fs/tool-fs-search/src/grep.ts @@ -293,6 +293,8 @@ export function applyGrepTool(ctx: Context, caps: GrepToolCaps): void { include: { type: 'string', description: 'One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported.' }, }, timeoutMs: caps.timeoutMs, + // Matches record no file observation; over-cap spilling runs in model-ordered post-execute. + isConcurrencySafe: () => true, output: { schema: { type: 'object', diff --git a/packages/fs/tool-fs-search/src/search-core.ts b/packages/fs/tool-fs-search/src/search-core.ts index 794a5d43fe..970846b99a 100644 --- a/packages/fs/tool-fs-search/src/search-core.ts +++ b/packages/fs/tool-fs-search/src/search-core.ts @@ -19,9 +19,10 @@ * @module @deepseek-ai/dsh-tool-fs-search/search-core */ -import { existsSync } from 'node:fs' -import { isAbsolute, join, parse, relative, sep } from 'node:path' +import { isAbsolute, relative, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' +import { spawnRipgrep } from '@deepseek-ai/dsh-util-ripgrep' +export { resolveRgPath } from '@deepseek-ai/dsh-util-ripgrep' import { HarnessError } from '@deepseek-ai/dsh-llm' import { ItemRetainer, TextRetainer } from '@deepseek-ai/dsh-output-retention' import type { RetainedItems } from '@deepseek-ai/dsh-output-retention' @@ -154,35 +155,6 @@ function completeStdout(toolName: string, stdout: SubprocessOutputRead, rawOutpu ) } -let rgPathPromise: Promise | undefined - -/** - * The packaged ripgrep binary path, resolved lazily once per process. - * - * A single-file runtime uses the executable's `-rg` sidecar because a native - * helper cannot be spawned from pkg's virtual filesystem. Node-mode builds - * fall back to the platform package selected by `@vscode/ripgrep`. Resolving - * at the call boundary keeps a missing or corrupt binary at the first search - * call as `SEARCH_FAILED`, rather than failing the Loader composition. - * - * @returns the packaged binary's absolute path; the memoized promise rejects - * when the platform package cannot be resolved. - */ -export function resolveRgPath(): Promise { - rgPathPromise ??= Promise.resolve().then(async () => { - const executable = parse(process.execPath) - const executableSidecar = process.platform === 'win32' - ? join(executable.dir, `${executable.name}-rg.exe`) - : `${process.execPath}-rg` - if ('pkg' in process && existsSync(executableSidecar)) return executableSidecar - const dependency = (await import('@vscode/ripgrep')).rgPath - return process.versions.electron === undefined - ? dependency - : dependency.replace(/\.asar(?=[\\/])/u, '.asar.unpacked') - }) - return rgPathPromise -} - /** * Run the packaged ripgrep binary with a plain argv vector and return its * complete raw stdout. The working directory is the calling agent's session @@ -236,8 +208,8 @@ export async function runRipgrep( : await ctx.workingDirectory.ensure(exec.agent, exec.signal) let handle: SubprocessHandle try { - handle = ctx.subprocess.spawn({ - argv: [await resolveRgPath(), '--no-config', ...argv], + handle = await spawnRipgrep(ctx.subprocess, { + argv, cwd: workdir, stdio: { stdin: 'ignore', diff --git a/packages/fs/tool-fs-search/tests/tools.spec.ts b/packages/fs/tool-fs-search/tests/tools.spec.ts index 5763aacc15..463fddd4cd 100644 --- a/packages/fs/tool-fs-search/tests/tools.spec.ts +++ b/packages/fs/tool-fs-search/tests/tools.spec.ts @@ -259,6 +259,12 @@ describe('registration', () => { expect(glob?.description).toContain('sampled across top-level entries') }) + it('declares glob and grep parallel-safe', async () => { + const { ctx } = await setup() + expect(ctx.tools.get('glob')?.isConcurrencySafe?.({ pattern: '*.ts' })).toBe(true) + expect(ctx.tools.get('grep')?.isConcurrencySafe?.({ pattern: 'x' })).toBe(true) + }) + it('stays pending until ctx.subprocess exists (inject)', async () => { const ctx = new Context() provideWorkingDirectoryFixture(ctx) diff --git a/packages/fs/tool-fs-search/tsconfig.json b/packages/fs/tool-fs-search/tsconfig.json index 4e6b7268ce..5971d17453 100644 --- a/packages/fs/tool-fs-search/tsconfig.json +++ b/packages/fs/tool-fs-search/tsconfig.json @@ -43,6 +43,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../util/ripgrep" } ] } diff --git a/packages/jobs/tool-jobs/README.i18n.yaml b/packages/jobs/tool-jobs/README.i18n.yaml index b4ec668330..7d8836390e 100644 --- a/packages/jobs/tool-jobs/README.i18n.yaml +++ b/packages/jobs/tool-jobs/README.i18n.yaml @@ -18,8 +18,8 @@ en: 823e94910a15e2e1 zh: c23e0b605f32f0bd /deepseek-ai-dsh-tool-jobs/use-this-package/the-three-tools: - en: 6f20f54e60bcf637 - zh: 6279c685d9d0bb16 + en: 618467d160f47332 + zh: f064a74fe4b08d3e /deepseek-ai-dsh-tool-jobs/use-this-package/completion-notices: en: 99577924f3d65112 zh: 521dac5540f9c1b7 diff --git a/packages/jobs/tool-jobs/README.md b/packages/jobs/tool-jobs/README.md index f97394300e..870d49be0f 100644 --- a/packages/jobs/tool-jobs/README.md +++ b/packages/jobs/tool-jobs/README.md @@ -35,6 +35,8 @@ Load this plugin in any composition where the agent should start, observe, and s The three tools return `{ text, job }`, `PublicJobSnapshot[]`, and `{ outcome: 'cancellation-requested' | 'already-finished', job }` respectively. A public snapshot carries id, kind, label, status with the live progress line or the terminal detail, and start/finish times, and omits ownership and ring offsets. All three render through generic UI cards: `read` for output and list, `execute` for kill. +`job_list` opts into concurrent scheduling with sibling parallel-safe calls because it reads a status snapshot. `job_output` stays exclusive because each read consumes the stream cursor and the one-time result delivery, and `job_kill` stays exclusive because it requests cancellation. + ### Completion notices When a job finishes, the owning agent receives `background job (: