Merge remote-tracking branch 'origin/master' into claude/tool-errors-experimental-c89252

# Conflicts:
#	packages/experimental/cua/README.i18n.yaml
#	snapshots/session/cua-native/session.v4.jsonl
This commit is contained in:
sjw1231 committed 2026-11-09 20:38:55 +08:00
commit bd27d339fb
167 files changed
+10020 -745

No files matched your search

@@ -9,8 +9,8 @@
en: f72db0b79aa02fb5
zh: b91c1f177dc93ab4
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision:
en: ec115e11f96ffe60
zh: c1fe9eb2866196d0
en: 41fd533d5be7642b
zh: c6fcbabec22bdbb7
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered:
en: 32c970ae153e0f6c
zh: 8431be0a10ffed15
@@ -16,7 +16,7 @@ Provider startup capabilities are static. Platform, supported methods, applicati
Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names.
Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime.
Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; native window operations reject closed or foreign windows. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime.
## Alternatives considered
@@ -16,7 +16,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。
在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。
在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;原生窗口操作会拒绝已关闭或属于其他应用的窗口。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。
## 考虑过的替代方案
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-09-cua-ax-traversal-defaults.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md
/agent-note-ax-traversal-defaults-and-per-read-limits:
en: 71a088b589135b94
zh: 40a0accb1f6d100b
/agent-note-ax-traversal-defaults-and-per-read-limits/problem:
en: 18405553f792f64c
zh: 1b6891403539c2f8
/agent-note-ax-traversal-defaults-and-per-read-limits/decision:
en: 89cb2b1f33b0551c
zh: b57839093a735c2a
/agent-note-ax-traversal-defaults-and-per-read-limits/alternatives-considered:
en: c15d84e0bbb18b39
zh: 4799291d7a66fa04
/agent-note-ax-traversal-defaults-and-per-read-limits/consequences:
en: 687f4ba2af13e847
zh: ae5777022619b71d
@@ -0,0 +1,21 @@
# Agent Note: AX traversal defaults and per-read limits
Status: implemented
English | [中文](2026-11-09-cua-ax-traversal-defaults.zh.md)
## Problem
A shallow read can omit a control in a deeply nested window. Increasing the profile settings to reach it also increases the work and possible output of subsequent reads.
## Decision
For an accessibility tree read, the Host takes each of `maxElements` and `maxDepth` from the request when present and from the provider configuration otherwise. A caller can raise or lower either value for one read. The native provider enforces its traversal ceilings. On macOS, Paste menu discovery always uses the configured values because the paste operation has no traversal options.
## Alternatives considered
**Cap each read at the configured values.** With a profile tuned for small reads, recovering a truncated branch would require changing the profile even when the provider can handle a larger request. Per-read overrides let the caller inspect that window and return to the usual limits on the next read.
## Consequences
Lowering a profile default reduces the budget for ordinary reads. An explicit larger request can take longer and produce more text. The native operation deadline and response size limit still apply. The [macOS configuration table](../../../../packages/experimental/cua-macos/README.md#use-this-package) lists the defaults.
@@ -0,0 +1,21 @@
# Agent Note: AX 树遍历的默认值和单次读取上限
Status: implemented
[English](2026-11-09-cua-ax-traversal-defaults.md) | 中文
## 问题
读取深度较小时,控件可能位于窗口中被截断的分支里。为了找到这个控件而调高配置值,会让以后的读取也可能访问更多节点、返回更多文本。
## 决策
读取辅助功能树时,Host 分别处理 `maxElements` 和 `maxDepth`。调用方显式传入的值只对本次读取生效,可以高于或低于配置值。省略的参数使用平台配置。原生实现在遍历时执行自身的硬上限。macOS 的粘贴操作没有遍历参数,查找粘贴菜单时始终使用配置值。
## 考虑过的替代方案
**把配置值作为每次读取的硬上限。** 如果日常读取使用较小的配置值,即使平台支持读取更大的树,调用方也必须先修改配置才能看到被截断的分支。允许单次覆盖后,调用方可以单独扩大这次读取的范围,下次读取继续使用原有配置。
## 影响
调低配置值可以缩小常规读取的范围。显式请求更大的树可能耗时更长,也可能返回更多文本。原生调用仍受超时和响应大小限制。默认值见 [macOS 配置表](../../../../packages/experimental/cua-macos/README.zh.md#use-this-package)。
@@ -9,8 +9,8 @@
en: 344bcc7e9825bbc8
zh: c1d0f4b54f5b3786
/agent-note-change-request-panel-and-worktree-sessions/decision:
en: 66bde24e7c601eb6
zh: 5091591f3dc1ac85
en: 4695a1e4f8aa7a25
zh: e17be0e36ea3eaa3
/agent-note-change-request-panel-and-worktree-sessions/deferred:
en: 32ef8af85f4d2f66
zh: b82b67f94346399e
@@ -28,7 +28,7 @@ The panel does not move a Session between existing worktrees. Removing a change
The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from `git diff` using the Session's permissions and execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other.
Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Review drafts and inline records belong to a browser tab occurrence, not to the Session log or a GitHub pending review. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records.
Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Inline records of Agent references and published comments, and the review summary, belong to a browser tab occurrence, not to the Session log; a pull request comment kept for a later review goes to the code host's pending review, as [the pending review decision](2026-11-05-forge-pending-review-drafts.md) records. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records.
## Deferred
@@ -28,7 +28,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自使用 Session 权限与执行环境的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。
评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。评审草稿与行内记录归浏览器页签实例所有,不进入 Session 日志,也不创建 GitHub 待提交评审。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。
评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。Agent 引用与已发布评论的行内记录以及评审总结归浏览器页签实例所有,不进入 Session 日志;留待之后一起提交的 PR 评论写入代码托管平台的待提交评审,见[待提交评审决策](2026-11-05-forge-pending-review-drafts.zh.md)。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。
## Deferred
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-05-forge-pending-review-drafts.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/feature/2026-11-05-forge-pending-review-drafts.md
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review:
en: 25b4da2d12f15b82
zh: 6d9fec68e8bb0baa
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/problem:
en: 2674866671bd0d4b
zh: e60d41a24d20d7bf
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/decision:
en: 3df55965423b6d33
zh: 2e8f0fbb4f7a311f
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/alternatives-considered:
en: ef67e05cb9442f05
zh: d4433ddd090a9cec
/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/consequences:
en: 198f6cf5a2bc2230
zh: 92eb0a349356f100
@@ -0,0 +1,31 @@
# Agent Note: Pull request comment drafts in the code host's pending review
Status: implemented
English | [中文](2026-11-05-forge-pending-review-drafts.zh.md)
## Problem
The [forge panel](2026-10-09-forge-panel.md) kept a pull request's comment drafts in a browser tab occurrence, published them as one review, and recorded what it published. Once the changes view shows the code host's review threads and lets the user reply to them, browser drafts leave four gaps. A reply cannot join a later review, because the drafts and the threads live in different places. A review the user started on the GitHub page, or in another browser, does not appear, and GitHub refuses a review submitted while the user has one. Drafts are lost with the tab and invisible on another device. And GitHub keeps one pending review per user and pull request, so two stores of one review would disagree.
## Decision
A pull request comment that the user keeps for a later review goes to the user's pending review on the code host through the provider's optional `writeReview`. The first such comment or reply starts the pending review at the head the user saw; later ones join it. The changes view reads the pending review with the threads, shows its comments as threads tagged Pending, and Submit review submits or discards that review with the summary and decision. Replies, resolving and unresolving, and editing and deleting the user's own comments use the same write, which re-checks the head and is never retried.
The browser keeps what the code host does not hold: the review summary and decision until submission, the records of Agent references and published comments, and the outgoing direct write whose outcome needs confirmation. Comments on local changes never had a host destination; they go to the main input as before. Comment drafts an earlier panel kept in the browser stay readable: they show beside their code as browser drafts, can move into the pending review, and keep Submit review disabled while a pending review exists; without one, Submit review publishes them as one review as before.
GitHub measurements on a private test repository decided three rules. While the user has a pending review, GitHub refuses a directly created review and a single comment (HTTP 422, "can only have one pending review per pull request"), so the view offers neither; a reply sent without the review's id still joins the review, so the view offers no reply at once and the provider refuses one. GitHub refuses Approve and Request changes on the user's own pull request, so the dialog offers only Comment there.
## Alternatives considered
**Keeping drafts in the browser tab.** It needs no host write until submission, but replies cannot join the same review, a review started elsewhere blocks submission without explanation, and the drafts do not follow the user to another device.
**Keeping both stores.** Mirroring browser drafts into the pending review or the reverse gives one review two owners whose contents can diverge, and every edit would need reconciliation of two writes.
**Recording drafts in the Session log.** The log records what reaches the model; review drafts are host state the model never sees, and other Sessions on the same pull request would not see them.
**Retrying a write after an unknown outcome.** A lost response does not show whether GitHub applied the mutation. A submission of the pending review is kept as the write to reconcile, as a direct submission is, and blocks another submission until the user checks GitHub; a reply, resolution, or comment change reads the threads again and asks the user to check them before trying again.
## Consequences
A comment kept for later is visible on the GitHub page to its author before submission, and is lost only when the user discards the review. Each comment, reply, or thread change costs one GraphQL query for the head check and one mutation. Resolving a thread does not change the pull request's update time, so every write from the panel drops the panel's kept threads; another view of the same pull request shows the change at its next status or after `reviewRefreshMs`. A provider without `writeReview` reports no write permissions, so its threads stay read-only and its pull request comments are published at once or added to the input. Comment drafts from an earlier panel remain until the user moves, publishes, or deletes them, or closes their tab.
@@ -0,0 +1,31 @@
# Agent Note: PR 评论草稿保存在代码托管平台的待提交评审中
Status: implemented
[English](2026-11-05-forge-pending-review-drafts.md) | 中文
## Problem
[forge 面板](2026-10-09-forge-panel.zh.md)原先把 PR 的评论草稿保存在浏览器页签实例中,作为一次评审发布,并记录已发布的内容。变更视图显示代码托管平台的评审讨论并允许用户回复之后,浏览器草稿留下四个缺口。回复无法加入之后的评审,因为草稿与讨论保存在不同的地方。用户在 GitHub 页面或另一个浏览器中开始的评审不会显示,而用户已有待提交评审时,GitHub 会拒绝直接提交的评审。草稿随页签丢失,在其他设备上也看不到。GitHub 每个用户在每个 PR 上只保留一个待提交评审,两处保存同一个评审会出现不一致。
## Decision
用户留待之后一起提交的 PR 评论,通过提供方的可选能力 `writeReview` 写入代码托管平台上该用户的待提交评审。第一条这样的评论或回复在用户看到的 head 上开始待提交评审,之后的评论或回复加入其中。变更视图随讨论一起读取待提交评审,把其中的评论显示为带“待提交”标签的讨论;“提交评审”带着总结和评审决定提交或丢弃这个评审。回复、解决与取消解决、编辑与删除用户自己的评论也使用同一写操作;写操作会重新检查 head,且从不重试。
浏览器只保存代码托管平台不保存的内容:提交前的评审总结与评审决定、Agent 引用与已发布评论的记录,以及结果有待确认的直接写入。本地变更上的评论本来就没有托管平台上的去处,仍像以前一样进入主输入框。早期面板保存在浏览器中的评论草稿仍可读取:它们作为浏览器草稿显示在对应代码旁,可以加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”像以前一样把它们作为一次评审发布。
在一个私有测试仓库上对 GitHub 的实测确定了三条规则。用户已有待提交评审时,GitHub 拒绝直接创建的评审和单条评论(HTTP 422,“每个 PR 只能有一个待提交评审”),因此视图两者都不提供;不带评审 id 发送的回复仍会加入该评审,因此视图不提供立即回复,提供方也拒绝这种回复。GitHub 拒绝用户批准或请求更改自己的 PR,因此在这种 PR 上,弹窗只提供“评论”。
## Alternatives considered
**把草稿保存在浏览器页签中。** 提交之前不需要写入托管平台,但回复无法加入同一个评审,在别处开始的评审会无说明地阻止提交,草稿也无法随用户换到另一台设备。
**两处同时保存。** 把浏览器草稿同步到待提交评审,或反过来同步,会让一个评审有两个所有者,内容可能分歧,每次编辑都要核对两次写入。
**把草稿记录在 Session 日志中。** 日志记录的是到达模型的内容;评审草稿是模型永远看不到的托管平台状态,同一 PR 上的其他 Session 也看不到它们。
**结果不明时自动重试写操作。** 响应丢失并不能说明 GitHub 是否执行了 mutation。提交待提交评审时,与直接提交一样,这次提交会作为待核对的写入保留下来,在用户到 GitHub 核对之前阻止再次提交;回复、解决讨论或修改评论时,视图重新读取讨论,并请用户核对后再重试。
## Consequences
留待之后提交的评论,在提交前其作者就能在 GitHub 页面上看到,只有用户丢弃评审时才会丢失。每条评论、回复或讨论状态的修改,都消耗一次用于检查 head 的 GraphQL 查询和一个 mutation。解决讨论不会改变 PR 的更新时间,因此面板发出的每个写操作都会丢弃面板保留的讨论;同一 PR 的其他视图在收到下一次状态时,或在 `reviewRefreshMs` 之后显示这一变化。未实现 `writeReview` 的提供方不报告任何写入权限,因此它的讨论保持只读,它的 PR 评论只能立即发布或添加到输入框。早期面板留下的评论草稿会一直保留,直到用户把它们加入评审、发布、删除,或关闭所在页签。
@@ -0,0 +1,19 @@
- dialog "提交评审":
- heading "提交评审" [level=2]
- button "关闭"
- text: 待提交评论(1)
- group "丢弃评审":
- text: 丢弃待提交的评审及其中的 1 条评论?此操作无法撤销
- button "取消"
- button "丢弃评审"
- textbox "评审总结…"
- status
- radio "评论" [checked]
- text: 评论
- radio "批准"
- text: 批准
- radio "请求更改"
- text: 请求更改
- button "丢弃评审" [disabled]
- button "取消"
- button "提交评审" [disabled]
@@ -1,4 +1,8 @@
- region "评论 R2–4":
- text: 你的评论 R2–4 已发布到 GitHub 请核对边界条件
- region "R2–4":
- text: R2–4 · 在 aaaaaaa 上 lin 1 个月前
- button "lin 的评论操作"
- paragraph: 请核对边界条件
- button "回复…"
- button "添加到输入框"
- button "在 GitHub 查看"
- button "在 GitHub 中查看"
- button "解决讨论"
@@ -10,5 +10,6 @@
- text: 批准
- radio "请求更改" [checked]
- text: 请求更改
- button "丢弃评审"
- button "取消"
- button "提交评审" [disabled]
@@ -0,0 +1,15 @@
- complementary "讨论列表,共 5 个":
- text: 讨论 5
- button "关闭讨论列表"
- radiogroup "筛选讨论":
- radio "未解决 4"
- radio "已解决 1"
- radio "全部 5" [checked]
- heading "docs/panel.md" [level=3]
- button "文件级讨论 Add a screenshot."
- heading "src/panel.ts" [level=3]
- button "R2 · 1 条回复 Why two?"
- button "L15 The old fifteen was a number."
- button "R15 Settled. 已解决"
- button "原在 R9 · 在 fffffff 上 This line moved. 已过期"
- button "在 GitHub 中查看"
@@ -0,0 +1,19 @@
> ## Review Thread 1
> File: src/panel.ts
> Side: R
> Lines: 2
> Commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
> State: unresolved
> Source: https://github.com/octo/demo/pull/7#discussion_on-line_0
> Diff hunk:
> ```diff
> @@ -1,5 +1,5 @@
> export const n1 = 1
> -export const n2 = 2
> +export const n2 = 'two'
> ```
> Comments:
> @lin (2026-10-09T00:00:00Z):
> > Why **two**?
> @octo (2026-10-09T00:00:00Z):
> > It reads better.
@@ -0,0 +1,16 @@
- region "R2":
- text: R2 · 在 aaaaaaa 上 lin 2 小时前
- button "lin 的评论操作"
- paragraph:
- text: Why
- strong: two
- text: "?"
- text: octo 2 小时前 作者
- paragraph: It reads better.
- textbox "回复…": 已改为字符串
- button "取消"
- button "回复"
- button "回复选项"
- button "添加到输入框"
- button "在 GitHub 中查看"
- button "解决讨论"
@@ -0,0 +1,91 @@
- button "收起 panel.ts" [expanded]
- text: src/panel.ts
- button "panel.ts 有 3 条未解决的讨论,跳到下一条": 3 条未解决
- text: +2 −2
- checkbox "将 panel.ts 标记为已审阅"
- button "panel.ts 的更多操作"
- button "选择第 L1 行": "1"
- text: export const n1 = 1
- button "选择第 R1 行": "1"
- text: export const n1 = 1
- button "选择第 L2 行": "2"
- text: export const n2 = 2
- button "选择第 R2 行": "2"
- text: export const n2 = 'two'
- region "R2":
- text: R2 · 在 aaaaaaa 上 lin 2 小时前
- button "lin 的评论操作"
- paragraph:
- text: Why
- strong: two
- text: "?"
- text: octo 2 小时前 作者
- paragraph: It reads better.
- button "回复…"
- button "添加到输入框"
- button "在 GitHub 中查看"
- button "解决讨论"
- button "选择第 L3 行": "3"
- text: export const n3 = 3
- button "选择第 R3 行": "3"
- text: export const n3 = 3
- button "选择第 L4 行": "4"
- text: export const n4 = 4
- button "选择第 R4 行": "4"
- text: export const n4 = 4
- button "选择第 L5 行": "5"
- text: export const n5 = 5
- button "选择第 R5 行": "5"
- text: export const n5 = 5
- button "6 行未变更"
- button "选择第 L12 行": "12"
- text: export const n12 = 12
- button "选择第 R12 行": "12"
- text: export const n12 = 12
- button "选择第 L13 行": "13"
- text: export const n13 = 13
- button "选择第 R13 行": "13"
- text: export const n13 = 13
- button "选择第 L14 行": "14"
- text: export const n14 = 14
- button "选择第 R14 行": "14"
- text: export const n14 = 14
- button "选择第 L15 行": "15"
- text: export const n15 = 15
- button "选择第 R15 行": "15"
- text: export const n15 = 'fifteen'
- region "L15":
- text: L15 · 在 aaaaaaa 上 lin 2 小时前
- button "lin 的评论操作"
- paragraph: The old fifteen was a number.
- button "回复…"
- button "添加到输入框"
- button "在 GitHub 中查看"
- button "解决讨论"
- text: 已解决的讨论 · lin
- button "展开"
- button "选择第 L16 行": "16"
- text: export const n16 = 16
- button "选择第 R16 行": "16"
- text: export const n16 = 16
- button "选择第 L17 行": "17"
- text: export const n17 = 17
- button "选择第 R17 行": "17"
- text: export const n17 = 17
- button "选择第 L18 行": "18"
- text: export const n18 = 18
- button "选择第 R18 行": "18"
- text: export const n18 = 18
- button "其余未变更的行"
- text: 1 条讨论已过期:所在代码已被后续提交修改
- button "收起" [expanded]
- region "原在 R9":
- text: 原在 R9 · 在 fffffff 上 已过期
- button "查看当时的文件"
- text: "@@ -1,5 +1,5 @@ export const n1 = 1 -export const n2 = 2 +export const n2 = 'two' lin 2 小时前"
- button "lin 的评论操作"
- paragraph: This line moved.
- button "回复…"
- button "添加到输入框"
- button "在 GitHub 中查看"
- button "解决讨论"
@@ -10,5 +10,6 @@
- text: 批准
- radio "请求更改" [checked]
- text: 请求更改
- button "丢弃评审"
- button "取消"
- button "提交评审"
+391 -12
View File
@@ -1,5 +1,6 @@
/** Worktree Sessions and the change request panel through the real optional bundle, a Git checkout, and a scripted GitHub CLI. */
import { execFile } from 'node:child_process'
import { existsSync } from 'node:fs'
import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { homedir, tmpdir } from 'node:os'
import { basename, join } from 'node:path'
@@ -10,7 +11,7 @@ import { pluginRecordOf, type SessionEvent } from '@deepseek-ai/dsh-session'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { initialShortcutConfig, type DesktopShortcutInput, type ShortcutRevision } from '@deepseek-ai/dsh-client-shortcuts/protocol'
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
import { chromium, type Browser, type Page } from 'playwright'
import { chromium, type Browser, type Locator, type Page } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import {
captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents, watchConsole,
@@ -49,8 +50,14 @@ const run = promisify(execFile)
* `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`.
* request 7 serves `commits.json`, oldest first. The review thread read serves
* `threads.json` as its one page of threads, with the viewer `lin`, who may write
* to the repository and did not open either pull request, or no threads without it. Review mutations, which arrive as
* JSON on stdin, change what later reads report through `state.json`: replies,
* which join the pending review whenever one exists, resolution, comment edits and
* deletions, and the pending review of `lin` with its new threads, which a
* submission publishes. Each mutation is appended to
* `mutations.jsonl`, and every invocation to `calls.jsonl`.
*/
const GH = `#!/usr/bin/env node
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
@@ -131,6 +138,56 @@ if (args[0] === 'auth' && args[1] === 'status') {
process.stdout.write('github.com\\n Logged in to github.com account octo\\n')
process.exit(0)
}
const review = () => ({ pending: null, published: [], replies: {}, resolved: {}, bodies: {}, deleted: [], ...state.review })
/** The signed-in reviewer, who did not open the pull requests. */
const VIEWER = 'lin'
/** One review comment node by \`login\`, which the viewer may change when it is the viewer's own. */
const commentNode = (id, body, login, pending) => ({ id, state: pending ? 'PENDING' : 'SUBMITTED', createdAt: '2026-10-09T01:00:00Z',
url: pending ? null : 'https://github.com/octo/demo/pull/7#discussion_' + id, body,
viewerCanUpdate: login === VIEWER, viewerCanDelete: login === VIEWER, author: { __typename: 'User', login, avatarUrl: null } })
if (args[0] === 'api' && args[1] === 'graphql' && args.includes('--input')) {
const { query, variables } = JSON.parse(readFileSync(0, 'utf8'))
const field = query.match(/\\{\\s*(\\w+)\\(input:/)[1]
appendFileSync(join(here, 'mutations.jsonl'), JSON.stringify({ field, variables }) + '\\n')
const current = review()
const draft = thread => ({ id: 'new-' + (current.published.length + (current.pending?.threads.length ?? 0) + 1),
path: thread.path, side: thread.side, line: thread.line, startLine: thread.startLine ?? null, body: thread.body })
let payload
if (field === 'addPullRequestReview') {
current.pending = { id: 'review-1', commit: variables.commit, threads: [] }
for (const thread of variables.threads ?? []) current.pending.threads.push(draft(thread))
payload = { pullRequestReview: { id: 'review-1' } }
} else if (field === 'addPullRequestReviewThread') {
current.pending.threads.push(draft(variables))
payload = { thread: { id: current.pending.threads.at(-1).id } }
} else if (field === 'addPullRequestReviewThreadReply') {
const replies = current.replies[variables.thread] ??= []
// As on GitHub, a reply joins the pending review whenever one exists.
replies.push({ id: variables.thread + '-reply-' + replies.length, body: variables.body, pending: variables.review !== null || current.pending !== null })
payload = { comment: { id: replies.at(-1).id } }
} else if (field === 'resolveReviewThread' || field === 'unresolveReviewThread') {
current.resolved[variables.thread] = field === 'resolveReviewThread'
payload = { thread: { id: variables.thread } }
} else if (field === 'updatePullRequestReviewComment') {
current.bodies[variables.comment] = variables.body
payload = { pullRequestReviewComment: { id: variables.comment } }
} else if (field === 'deletePullRequestReviewComment') {
current.deleted.push(variables.comment)
payload = { clientMutationId: null }
} else if (field === 'submitPullRequestReview' || field === 'deletePullRequestReview') {
if (field === 'submitPullRequestReview') current.published.push(...current.pending.threads)
for (const replies of Object.values(current.replies)) {
for (const reply of replies) if (reply.pending && field === 'deletePullRequestReview') current.deleted.push(reply.id)
for (const reply of replies) reply.pending = false
}
current.pending = null
payload = { pullRequestReview: { id: variables.review } }
}
state.review = current
save()
process.stdout.write(JSON.stringify({ data: { [field]: payload } }))
process.exit(0)
}
if (args[0] === 'api' && args[1] === 'graphql') {
const query = args.find(arg => arg.startsWith('query=')).slice('query='.length)
const check = (name, conclusion, completedAt, databaseId = 101) => ({
@@ -171,6 +228,41 @@ if (args[0] === 'api' && args[1] === 'graphql') {
} } } } }))
process.exit(0)
}
if (query.includes('viewer { login }')) {
const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length))
const current = review()
const page = nodes => ({ pageInfo: { hasNextPage: false, endCursor: null }, nodes })
const written = (thread, pending) => ({
id: thread.id, isOutdated: false, isResolved: false, path: thread.path, diffSide: thread.side, startDiffSide: thread.startLine === null ? null : thread.side,
line: thread.line, startLine: thread.startLine, originalLine: thread.line, originalStartLine: thread.startLine, subjectType: 'LINE',
viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: false,
root: { nodes: [{ diffHunk: '@@ -1,5 +1,5 @@', commit: { oid: pulls[number].headRefOid }, originalCommit: { oid: pulls[number].headRefOid } }] },
comments: page([commentNode(thread.id + '-0', thread.body, VIEWER, pending)]),
})
const stored = existsSync(join(here, 'threads.json')) ? JSON.parse(readFileSync(join(here, 'threads.json'), 'utf8')) : []
const threads = [...stored, ...current.published.map(thread => written(thread, false)),
...(current.pending?.threads ?? []).map(thread => written(thread, true))].map((thread) => {
const replies = (current.replies[thread.id] ?? []).map(reply => commentNode(reply.id, reply.body, VIEWER, reply.pending))
const comments = [...thread.comments.nodes, ...replies].filter(comment => !current.deleted.includes(comment.id))
.map(comment => ({ ...comment, body: current.bodies[comment.id] ?? comment.body }))
return { ...thread, isResolved: current.resolved[thread.id] ?? thread.isResolved, comments: page(comments) }
}).filter(thread => thread.comments.nodes.length > 0)
const pendingComments = threads.flatMap(thread => thread.comments.nodes).filter(comment => comment.state === 'PENDING').length
process.stdout.write(JSON.stringify({ data: { viewer: { login: VIEWER }, repository: { isArchived: false, viewerPermission: 'WRITE',
pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid, locked: false,
reviews: { nodes: current.pending === null ? [] : [{ id: current.pending.id, viewerDidAuthor: true, comments: { totalCount: pendingComments } }] },
reviewThreads: page(threads) } } } }))
process.exit(0)
}
if (query.includes('reviews(states: PENDING')) {
const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length))
const pending = review().pending
// Every thread and comment the double serves belongs to the pull request it was read from.
const target = args.some(arg => arg.startsWith('target=')) ? { target: { pullRequest: { id: 'pull-' + number } } } : {}
process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid,
reviews: { nodes: pending === null ? [] : [{ id: pending.id, viewerDidAuthor: true }] } } }, ...target } }))
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 } } } }))
@@ -1021,7 +1113,10 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
expect(narrowComment.x + narrowComment.width).toBeLessThanOrEqual(390)
await page.setViewportSize({ width: 1680, height: 1000 })
await panelFile.getByRole('button', { name: '开始评审', exact: true }).click()
await panelFile.locator('[data-forge-review-thread="pending"]').getByText('请核对边界条件', { exact: true }).waitFor()
// The comment starts the pending review on GitHub, and the threads read again show it there.
const pendingThread = panelFile.locator('[data-forge-thread="new-1"]')
await pendingThread.getByText('请核对边界条件', { exact: true }).waitFor({ timeout: 20_000 })
await pendingThread.getByText('待提交', { exact: true }).waitFor()
await page.setViewportSize({ width: 1680, height: 500 })
const changesScroll = view.locator('[data-forge-changes-scroll]')
await changesScroll.evaluate((element) => { element.scrollTop = element.scrollHeight })
@@ -1052,11 +1147,16 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE)
await reviewDialog.getByRole('button', { name: '提交评审', exact: true }).click()
await page.getByRole('alert').filter({ hasText: '已提交评审' }).waitFor()
await panelFile.locator('[data-forge-review-thread="published"]').getByText('请核对边界条件', { exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'review-record.expected.md'), await captureStableAria(page, '[data-forge-review-thread="published"]', scaffold.workspaceCwd), MODE)
const published: unknown = JSON.parse((await readFile(join(root, 'reviews.jsonl'), 'utf8')).trim())
expect(published).toEqual({ endpoint: 'repos/octo/demo/pulls/7/reviews', body: { commit_id: HEAD7, event: 'REQUEST_CHANGES', body: '需要补充边界检查',
comments: [{ path: 'src/panel.ts', side: 'RIGHT', line: 4, start_line: 2, start_side: 'RIGHT', body: '请核对边界条件' }] } })
await expect.poll(() => pendingThread.getByText('待提交', { exact: true }).count(), { timeout: 20_000 }).toBe(0)
await compareOrRefreshGolden(join(EXPECTED, 'review-record.expected.md'),
await captureStableAria(page, '[data-forge-thread="new-1"]', scaffold.workspaceCwd), MODE)
const mutations = (await readFile(join(root, 'mutations.jsonl'), 'utf8')).trim().split('\n').map((line): unknown => JSON.parse(line))
expect(mutations).toEqual([
{ field: 'addPullRequestReview', variables: { pull: 'pull-7', commit: HEAD7,
threads: [{ path: 'src/panel.ts', body: '请核对边界条件', line: 4, side: 'RIGHT', startLine: 2, startSide: 'RIGHT' }] } },
{ field: 'submitPullRequestReview', variables: { review: 'review-1', event: 'REQUEST_CHANGES', body: '需要补充边界检查' } },
])
expect(existsSync(join(root, 'reviews.jsonl'))).toBe(false)
await page.getByRole('button', { name: '退出全屏', exact: true }).click()
await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).click()
await panelFile.getByText('export const n6 = 6', { exact: true }).first().waitFor({ timeout: 20_000 })
@@ -1080,7 +1180,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
expect(await panelFile.evaluate((element, original) => element === original, originalFile)).toBe(true)
await expect.poll(() => docsFile.getAttribute('data-expanded')).toBe(null)
await expect.poll(() => scrollport.evaluate(element => element.scrollTop)).toBe(position)
expect(await panelFile.locator('[data-forge-review-thread="published"]').count()).toBe(1)
expect(await panelFile.locator('[data-forge-thread="new-1"]').count()).toBe(1)
await page.setViewportSize({ width: 1680, height: 1000 })
await page.locator('[data-dockkit-tab]').filter({ hasText: '#7 的变更' }).locator('[data-dockkit-tab-close]').click()
await expect.poll(() => view.count()).toBe(0)
@@ -1353,7 +1453,9 @@ it.skipIf(MODE === 'record')('opens a comment from the hover plus in one press w
expect(await file.getByRole('textbox').count()).toBe(0)
await page.mouse.up()
await file.getByRole('region', { name: '评论 R6–8', exact: true }).waitFor()
expect(await plus('R6').count()).toBe(0)
// The open editor leaves the hover plus for the next comment.
await code(3).hover()
expect(await plus('R3').isVisible()).toBe(true)
await file.getByRole('button', { name: '取消', exact: true }).click()
await file.getByRole('textbox').waitFor({ state: 'detached' })
@@ -1719,7 +1821,7 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i
expect(await file.getByRole('button', { name: '开始评审', exact: true }).isDisabled()).toBe(true)
await input.fill('检查边界条件')
await file.getByRole('button', { name: '开始评审', exact: true }).click()
await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor()
await file.locator('[data-forge-thread]').getByText('检查边界条件', { exact: true }).waitFor({ timeout: 20_000 })
expect(tripwire.pageErrors).toEqual([])
})
@@ -1856,6 +1958,174 @@ it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a
expect(tripwire.pageErrors).toEqual([])
})
/**
* One review thread node of pull request 7 as the GraphQL thread read returns it, its comments by `lin`, the viewer, then
* `octo`, the pull request's author; the viewer may reply, resolve, and change their own comments.
*/
function threadNode(
id: string, fields: Record<string, unknown>, bodies: readonly string[], commit: string = HEAD7,
): Record<string, unknown> {
return {
id, isOutdated: false, isResolved: false, path: 'src/panel.ts', diffSide: 'RIGHT', startDiffSide: null, line: null, startLine: null,
originalLine: null, originalStartLine: null, subjectType: 'LINE', viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: true, ...fields,
root: { nodes: [{ diffHunk: '@@ -1,5 +1,5 @@\n export const n1 = 1\n-export const n2 = 2\n+export const n2 = \'two\'',
commit: { oid: commit }, originalCommit: { oid: commit } }] },
comments: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: bodies.map((body, index) => ({
id: `${id}-${index}`, state: 'SUBMITTED', createdAt: '2026-10-09T00:00:00Z', url: `${PULL}#discussion_${id}_${index}`, body,
viewerCanUpdate: index === 0, viewerCanDelete: index === 0, author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null },
})) },
}
}
/** Threads of pull request 7: on new line 2, on old line 15, resolved on new line 15, outdated, and on the whole of `docs/panel.md`. */
const THREADS = [
threadNode('on-line', { line: 2, originalLine: 2 }, ['Why **two**?', 'It reads better.']),
threadNode('old-side', { diffSide: 'LEFT', line: 15, originalLine: 15 }, ['The old fifteen was a number.']),
threadNode('resolved', { isResolved: true, line: 15, originalLine: 15 }, ['Settled.']),
threadNode('outdated', { isOutdated: true, originalLine: 9 }, ['This line moved.'], 'f'.repeat(40)),
threadNode('whole-file', { path: 'docs/panel.md', subjectType: 'FILE' }, ['Add a screenshot.']),
]
it.skipIf(MODE === 'record')('overlays the review threads of a change request and opens them from the thread list', async () => {
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-threads', 'follow-up')
await writeFile(join(root, 'threads.json'), JSON.stringify(THREADS))
// Comments were written two hours before the browser's clock, so their relative times stay fixed.
await page.clock.setFixedTime(Date.parse('2026-10-09T02:00:00Z'))
const { view, sessionId } = await openReview(page, scaffold)
const panel = view.locator('[data-forge-diff-file="src/panel.ts"]')
const onLine = panel.locator('[data-forge-thread="on-line"]')
await onLine.getByText('two', { exact: true }).waitFor({ timeout: 20_000 })
// The thread follows the row of its last line, in the column of its side: under the new side and the old side.
const placement = (card: Element, number: string) => {
const row = card.closest('[data-forge-notes]')
const column = Array.from(row?.children ?? []).findIndex(cell => cell.contains(card))
return { line: row?.previousElementSibling?.querySelector(number)?.textContent, column }
}
expect(await onLine.evaluate(placement, '[data-new-line]')).toEqual({ line: 'export const n2 = \'two\'', column: 1 })
expect(await panel.locator('[data-forge-thread="old-side"]').evaluate(placement, '[data-old-line]')).toEqual({ line: 'export const n15 = 15', column: 0 })
await panel.locator('[data-forge-thread="resolved"]').getByText('已解决的讨论 · lin', { exact: true }).waitFor()
await panel.locator('[data-forge-outdated-threads]').getByText('1 条讨论已过期:所在代码已被后续提交修改', { exact: true }).waitFor()
await view.locator('[data-forge-diff-file="docs/panel.md"] [data-forge-thread="whole-file"]').getByText('文件级讨论', { exact: true }).waitFor()
const count = panel.getByRole('button', { name: 'panel.ts 有 3 条未解决的讨论,跳到下一条', exact: true })
await count.waitFor()
await view.getByRole('navigation').getByTitle('3 条未解决的讨论', { exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'review-threads.expected.md'),
await captureStableAria(page, '[data-forge-diff-file="src/panel.ts"]', scaffold.workspaceCwd), MODE)
// The count steps through the file's unresolved threads in display order: R2, L15, then the outdated one.
const centered = async (id: string): Promise<boolean> => await panel.locator(`[data-forge-thread="${id}"]`).evaluate((card) => {
const viewport = card.closest('[data-forge-changes-scroll]')!.getBoundingClientRect()
const box = card.getBoundingClientRect()
return box.top + box.height / 2 > viewport.top && box.top + box.height / 2 < viewport.bottom
})
for (const id of ['on-line', 'old-side', 'outdated']) {
await count.click()
await expect.poll(() => centered(id)).toBe(true)
}
expect(await view.locator('[data-forge-thread-list]').count()).toBe(0)
await view.getByRole('button', { name: '讨论列表,共 5 个', exact: true }).click()
const list = view.getByRole('complementary', { name: '讨论列表,共 5 个' })
await expect.poll(() => list.getByRole('radio', { checked: true }).allTextContents()).toEqual(['未解决4'])
await expect.poll(() => list.locator('[data-forge-thread-item]').evaluateAll(items => items.map(item => item.getAttribute('data-forge-thread-item'))))
.toEqual(['whole-file', 'on-line', 'old-side', 'outdated'])
await list.getByRole('radio', { name: /^已解决/ }).click()
await list.locator('[data-forge-thread-item="resolved"]').click()
// Opening a resolved thread unfolds it inside its file, and the docked list stays.
await panel.locator('[data-forge-thread="resolved"]').getByText('Settled.', { exact: true }).waitFor()
await list.getByRole('radio', { name: /^全部/ }).click()
await expect.poll(() => list.locator('[data-forge-thread-item]').count()).toBe(5)
await compareOrRefreshGolden(join(EXPECTED, 'review-thread-list.expected.md'),
await captureStableAria(page, '[data-forge-thread-list]', scaffold.workspaceCwd), MODE)
// A view narrower than 480px gives the list the files' whole width and closes it before opening a thread.
await view.evaluate((element) => { element.style.width = '420px'; element.style.flex = 'none' })
await expect.poll(() => list.evaluate(element => [getComputedStyle(element).position, element.getBoundingClientRect().width]))
.toEqual(['absolute', 420])
await list.locator('[data-forge-thread-item="on-line"]').click()
await list.waitFor({ state: 'detached' })
await view.evaluate((element) => { element.style.width = ''; element.style.flex = '' })
await onLine.getByRole('button', { name: '添加到输入框', exact: true }).click()
await page.locator('[data-composer-input]').first().getByText('panel.ts R2', { exact: true }).first().waitFor()
const sent = scaffold.whenTurnSettled()
await page.locator('[data-composer-input]').first().press('Enter')
await sent
await page.getByText(FOLLOW_UP_REPLY, { exact: true }).waitFor()
// The quoted thread reaches the model only inside the ordinary logged user message.
const quotes = (await readPersistedEvents(scaffold, sessionId)).flatMap(event => event.type === 'user/message'
? event.data.content.flatMap(block => block.type === 'text' && block.text.includes('## Review Thread') ? [block.text] : []) : [])
expect(quotes).toHaveLength(1)
await compareOrRefreshGolden(join(EXPECTED, 'review-thread-message.expected.md'), quotes.join('').trimEnd(), MODE)
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[])
const reads = calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('viewer { login }')))
expect(reads.length).toBeGreaterThan(0)
expect(reads[0]).toEqual(expect.arrayContaining(['owner=octo', 'name=demo', 'number=7', 'first=100']))
expect(tripwire.pageErrors).toEqual([])
})
it.skipIf(MODE === 'record')('replies to, edits, deletes, and resolves review threads, and discards a pending review started from a reply', async () => {
const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-writes')
await writeFile(join(root, 'threads.json'), JSON.stringify(THREADS))
await page.clock.setFixedTime(Date.parse('2026-10-09T02:00:00Z'))
const { view } = await openReview(page, scaffold)
const panel = view.locator('[data-forge-diff-file="src/panel.ts"]')
const onLine = panel.locator('[data-forge-thread="on-line"]')
await onLine.getByText('two', { exact: true }).waitFor({ timeout: 20_000 })
await onLine.getByRole('button', { name: '回复…', exact: true }).click()
await onLine.getByRole('textbox', { name: '回复…', exact: true }).fill('已改为字符串')
await compareOrRefreshGolden(join(EXPECTED, 'review-thread-reply.expected.md'),
await captureStableAria(page, '[data-forge-thread="on-line"]', scaffold.workspaceCwd), MODE)
await onLine.getByRole('button', { name: '回复', exact: true }).click()
await onLine.getByText('已改为字符串', { exact: true }).waitFor({ timeout: 20_000 })
await onLine.getByRole('button', { name: 'lin 的评论操作', exact: true }).first().click()
await page.getByRole('menuitem', { name: '编辑', exact: true }).click()
await onLine.getByRole('textbox', { name: '编辑评论', exact: true }).fill('Why a **word**?')
await onLine.getByRole('button', { name: '保存', exact: true }).click()
await onLine.getByText('word', { exact: true }).waitFor({ timeout: 20_000 })
await onLine.getByRole('button', { name: 'lin 的评论操作', exact: true }).last().click()
await page.getByRole('menuitem', { name: '删除', exact: true }).click()
await onLine.getByRole('group', { name: '删除这条评论?', exact: true }).getByRole('button', { name: '删除', exact: true }).click()
await expect.poll(() => onLine.getByText('已改为字符串', { exact: true }).count(), { timeout: 20_000 }).toBe(0)
await onLine.getByRole('button', { name: '解决讨论', exact: true }).click()
await onLine.getByText('已解决的讨论 · lin', { exact: true }).waitFor({ timeout: 20_000 })
const oldSide = panel.locator('[data-forge-thread="old-side"]')
await oldSide.getByRole('button', { name: '回复…', exact: true }).click()
await oldSide.getByRole('textbox', { name: '回复…', exact: true }).fill('稍后一起提交')
await oldSide.getByRole('button', { name: '回复选项', exact: true }).click()
await page.getByRole('menuitem', { name: '开始评审', exact: true }).click()
await oldSide.getByText('待提交', { exact: true }).waitFor({ timeout: 20_000 })
await view.getByRole('button', { name: '提交评审 (1)', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '提交评审', exact: true })
await dialog.getByRole('button', { name: '丢弃评审', exact: true }).click()
await compareOrRefreshGolden(join(EXPECTED, 'discard-review.expected.md'),
await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE)
await dialog.getByRole('group', { name: '丢弃评审', exact: true }).getByRole('button', { name: '丢弃评审', exact: true }).click()
await page.getByRole('alert').filter({ hasText: '已丢弃评审' }).waitFor()
await expect.poll(() => oldSide.getByText('稍后一起提交', { exact: true }).count(), { timeout: 20_000 }).toBe(0)
await view.getByRole('button', { name: '提交评审', exact: true }).waitFor()
const mutations = (await readFile(join(root, 'mutations.jsonl'), 'utf8')).trim().split('\n').map((line): unknown => JSON.parse(line))
expect(mutations).toEqual([
{ field: 'addPullRequestReviewThreadReply', variables: { thread: 'on-line', body: '已改为字符串', review: null } },
{ field: 'updatePullRequestReviewComment', variables: { comment: 'on-line-0', body: 'Why a **word**?' } },
{ field: 'deletePullRequestReviewComment', variables: { comment: 'on-line-reply-0' } },
{ field: 'resolveReviewThread', variables: { thread: 'on-line' } },
{ field: 'addPullRequestReview', variables: { pull: 'pull-7', commit: HEAD7, threads: null } },
{ field: 'addPullRequestReviewThreadReply', variables: { thread: 'old-side', body: '稍后一起提交', review: 'review-1' } },
{ field: 'deletePullRequestReview', variables: { review: 'review-1' } },
])
// Every write checked the head of pull request 7 first.
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[])
expect(calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('reviews(states: PENDING') && !arg.includes('viewer { login }'))))
.toHaveLength(mutations.length - 1)
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'
@@ -1903,3 +2173,112 @@ it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu
await expect.poll(() => file.getAttribute('data-viewed')).toBe('viewed')
expect(tripwire.pageErrors).toEqual([])
})
/**
* Launch the panel on a branch whose README.md replaces its first line and adds eight more, so a side-by-side view
* pairs a deletion with an addition, then open the Session's local changes full screen.
* @param failureShot - screenshot name for a failure.
* @returns the launch and the local changes view.
*/
async function openLocalChanges(failureShot: string): Promise<PanelLaunch & { readonly view: Locator }> {
const launch = await launchPanel(failureShot)
const { scaffold, page, project } = launch
await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
await writeFile(join(project, 'README.md'), `changed\n${Array.from({ length: 8 }, (_, line) => `line ${line + 2}\n`).join('')}`)
await writeFile(join(project, 'notes.md'), 'note\n')
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.locator('[data-forge-header]').click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更/ }).click()
const view = page.locator('[data-forge-changes="local"]')
await view.locator('[data-forge-diff-file="README.md"]').waitFor()
await page.getByRole('button', { name: '全屏', exact: true }).click()
return { ...launch, view }
}
it.skipIf(MODE === 'record')('keeps the changes toolbar and header on one line, folding view controls into the More menu as they narrow', async () => {
const { page, view, tripwire } = await openLocalChanges('web-e2e-forge-toolbar-fold')
const toolbar = view.locator('[data-fold]')
const more = toolbar.getByRole('button', { name: '更多视图选项', exact: true })
const create = view.getByRole('button', { name: '创建变更请求', exact: true })
const layout = () => toolbar.evaluate((row) => {
const header = row.closest('[data-forge-changes]')!.firstElementChild!
return { fold: row.getAttribute('data-fold'), overflow: row.scrollWidth - row.clientWidth, height: row.getBoundingClientRect().height,
header: header.getBoundingClientRect().height }
})
// The button keeps a fixed height when its label wraps, so the label's own height tells one line from two.
const labelHeight = () => create.evaluate((button) => {
const range = document.createRange()
range.selectNodeContents(button)
return Math.round(range.getBoundingClientRect().height)
})
const lineHeight = await labelHeight()
const seen: string[] = []
for (const width of [1680, 700, 560, 390, 340]) {
await page.setViewportSize({ width, height: 800 })
await expect.poll(async () => (await layout()).overflow).toBeLessThanOrEqual(0)
const { fold, height, header } = await layout()
// One 28px control row inside the toolbar's padding, and the header keeps its single-line height.
expect([width, height]).toEqual([width, 38])
expect([width, header]).toEqual([width, 44])
expect([width, await labelHeight()]).toEqual([width, lineHeight])
seen.push(`${width}:${fold}`)
}
expect(seen[0]).toBe('1680:0')
expect(seen.at(-1)).toBe('340:3')
expect(await more.isVisible()).toBe(true)
await page.setViewportSize({ width: 390, height: 800 })
await expect.poll(() => toolbar.getAttribute('data-fold')).toBe('2')
// Folded controls leave the row; the progress turns into the ring and the bare count.
expect(await toolbar.getByRole('button', { name: '左右对比', exact: true }).isVisible()).toBe(false)
expect(await toolbar.getByRole('switch', { name: '隐藏测试文件', exact: true }).isVisible()).toBe(false)
expect(await toolbar.locator('[data-forge-progress="compact"]').innerText()).toBe('0/2')
await more.click()
const menu = page.getByRole('menu')
expect(await menu.getByRole('menuitem').allTextContents()).toEqual(['全部折叠', '左右对比', '自动换行', '隐藏测试文件'])
const code = view.locator('[data-forge-diff-file="README.md"] [data-review]')
expect(await code.getAttribute('data-split')).toBe('')
await menu.getByRole('menuitem', { name: '左右对比', exact: true }).click()
await expect.poll(() => code.getAttribute('data-split')).toBe(null)
expect(await page.getByRole('menu').count()).toBe(0)
await page.setViewportSize({ width: 1680, height: 800 })
await expect.poll(() => toolbar.getAttribute('data-fold')).toBe('0')
expect(await more.isVisible()).toBe(false)
expect(await toolbar.getByRole('button', { name: '左右对比', exact: true }).getAttribute('aria-pressed')).toBe('false')
expect(tripwire.pageErrors).toEqual([])
})
it.skipIf(MODE === 'record')('writes a left and a right comment at once, each inside its own column of the side-by-side row', async () => {
const { page, view, tripwire } = await openLocalChanges('web-e2e-forge-side-comments')
const readme = view.locator('[data-forge-diff-file="README.md"]')
const open = async (name: string) => {
await readme.getByRole('button', { name: `选择第 ${name} 行`, exact: true }).click()
await readme.getByRole('button', { name: '添加评论', exact: true }).click()
return readme.getByRole('region', { name: `评论 ${name}`, exact: true })
}
const left = await open('L1')
const right = await open('R1')
await right.getByRole('textbox').fill('右侧的评论')
for (const width of [1680, 1000, 780]) {
await page.setViewportSize({ width, height: 900 })
const boxes = await readme.evaluate((section) => {
const pair = section.querySelector('[data-diff-pair]')!
const [l, r] = Array.from(pair.children, cell => cell.getBoundingClientRect())
const [a, b] = Array.from(section.querySelectorAll('[data-forge-comment]'), form => form.getBoundingClientRect())
return { l: [l!.left, l!.right], r: [r!.left, r!.right], a: [a!.left, a!.right, a!.top], b: [b!.left, b!.right, b!.top] }
})
// Each comment stays inside its side's column, and both share one row.
expect(boxes.a[0]!).toBeGreaterThan(boxes.l[0]!)
expect(boxes.a[1]!).toBeLessThan(boxes.l[1]!)
expect(boxes.b[0]!).toBeGreaterThan(boxes.r[0]!)
expect(boxes.b[1]!).toBeLessThan(boxes.r[1]!)
expect(boxes.a[2]).toBe(boxes.b[2])
}
await left.getByRole('button', { name: '取消', exact: true }).click()
expect(await left.count()).toBe(0)
expect(await right.getByRole('textbox').inputValue()).toBe('右侧的评论')
expect(tripwire.pageErrors).toEqual([])
})
+14 -4
View File
@@ -1121,6 +1121,13 @@ export interface Config {
* `testPaths` and before the built-in rules.
*/
interfacePaths?: string[]
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
maxCachedReviewBytes?: number
/**
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
* request's update time does not change when a thread is resolved.
*/
reviewRefreshMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1156,7 +1163,7 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../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. */
@@ -1186,7 +1193,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:279`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:432`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1220,9 +1227,12 @@ export interface Config {
hosts?: string[]
/** Deadline in milliseconds for one `gh` invocation. */
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
/**
* Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in
* one review read, which reports itself truncated past it.
*/
maxReviewThreads?: number
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
maxCommits?: number
+14 -4
View File
@@ -1123,6 +1123,13 @@ export interface Config {
* `testPaths` and before the built-in rules.
*/
interfacePaths?: string[]
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
maxCachedReviewBytes?: number
/**
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
* request's update time does not change when a thread is resolved.
*/
reviewRefreshMs?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1158,7 +1165,7 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../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. */
@@ -1188,7 +1195,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:279`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:432`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1222,9 +1229,12 @@ export interface Config {
hosts?: string[]
/** Deadline in milliseconds for one `gh` invocation. */
timeoutMs?: number
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */
/** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read or review read. */
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
/**
* Most review threads counted per pull request in one status read, which reports a lower bound past it, and read in
* one review read, which reports itself truncated past it.
*/
maxReviewThreads?: number
/** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
maxCommits?: number
+1 -1
View File
@@ -47,7 +47,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `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` |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
+1 -1
View File
@@ -49,7 +49,7 @@
| `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` |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
+2 -1
View File
@@ -585,6 +585,7 @@ flowchart TD
pkg_skill_badge --> pkg_skill
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -1762,7 +1763,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
+2 -1
View File
@@ -587,6 +587,7 @@ flowchart TD
pkg_skill_badge --> pkg_skill
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -1764,7 +1765,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
+7 -4
View File
@@ -12,11 +12,14 @@
en: 26ccfa2e342e3e67
zh: fe6cc2a622757c48
/forges/change-request-actions:
en: 87d2c81d9514267f
zh: 1daf31c5b0127a1c
en: ae735fbdbdf2d870
zh: 9903fcc571104ad8
/forges/review-threads:
en: af729af6e59e915f
zh: 62ddae4cfcd4431f
/forges/session-bindings:
en: 13dfd36f2166bba0
zh: a369434f52f04d57
/forges/panel:
en: e52a5c57abc4d30e
zh: 509a40f421cc3d33
en: 4020149c26661a2d
zh: 56842b057d4f662e
+253 -6
View File
@@ -47,6 +47,18 @@ interface ForgeProvider {
readonly forge: string
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
* Read the review threads of a change request at head commit `headSha`. The threads are returned only when the
* read names `headSha` as the head; once the head is another commit, the read resolves to a `stale` failure.
* Omission declares that this provider cannot read reviews.
*/
readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>
/**
* Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the
* head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares
* that this provider cannot write reviews, and its `readReview` then reports no viewer permission.
*/
writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>
/** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */
repositoryFromRemote(url: string): ForgeRepository | undefined
/** Map a change request web URL to its reference, or undefined when this provider does not serve it. */
@@ -244,9 +256,9 @@ 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; `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.
* a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure.
*/
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable'
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable'
/** Human-readable cause. */
readonly message: string
}
@@ -303,7 +315,7 @@ interface ForgeActionFailure {
}
```
`ctx.forge.submitReview` delegates an explicit comment or completed review to the provider. A provider that omits this capability returns unsupported. Consumers retain pending drafts and reconcile unknown write outcomes before resubmitting.
`ctx.forge.submitReview` delegates an explicit comment or completed review to the provider. A provider that omits this capability returns unsupported. Consumers reconcile unknown write outcomes before resubmitting; comments kept for a later review go to the code host's pending review through `ctx.forge.writeReview`.
```ts type-equiv
/** One inline comment addressed to the old or new side of a pull request diff. */
@@ -323,17 +335,188 @@ type ForgeReviewRequest = {
readonly headSha: string
} & (
| { readonly kind: 'comment'; readonly comment: ForgeLineComment }
| { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] }
| { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] }
)
```
```ts type-equiv
/** Result of a review write; unknown outcomes must be checked on the host before another submission. */
/** Result of a review submission; unknown outcomes must be checked on the host before another submission. */
type ForgeReviewResult =
| { readonly ok: true; readonly url: string }
| { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string }
```
## Review threads
`ctx.forge.readReview(ref, headSha, signal)` reads the review threads of a change request at one head commit. The provider returns `ForgeReviewData` only when the read names `headSha` as the head; otherwise it returns `stale`, which polls a watched change request again at once, as a stale diff read does. For a provider without `readReview` the service returns `unsupported`, so consumers show no threads instead of a failure. A line thread has two positions: `original` on the commit it was written on, and `current` on the head of the read, which is null once the host no longer places the thread on that commit. A consumer that shows the head's diff places a thread at `current` and shows the others with their `diffHunk`; reading the file at `original.commit` through `fileText` shows the whole file the thread was written on. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub's fields map onto these positions.
```ts type-equiv
/** Opaque host identity of one review thread. */
type ForgeThreadId = Branded<'ForgeThreadId'>
```
```ts type-equiv
/** Opaque host identity of one review comment. */
type ForgeCommentId = Branded<'ForgeCommentId'>
```
```ts type-equiv
/** Consecutive lines on one side of a diff whose new side is one commit. */
interface ForgeAnchor {
/**
* Full object name of the commit the diff's new side shows: new-side (`R`) lines number this commit's file, and
* old-side (`L`) lines number the file at the diff's base.
*/
readonly commit: string
/** First line, inclusive. */
readonly startLine: number
/** Last line, inclusive. */
readonly endLine: number
}
```
```ts type-equiv
/** Account that wrote a review comment. */
interface ForgeCommentAuthor {
/** Login as the host spells it. */
readonly login: string
/** Avatar image URL, or null when the host reports none. */
readonly avatarUrl: string | null
/** Whether the account is an app or bot rather than a person. */
readonly bot: boolean
}
```
```ts type-equiv
/** One comment of a review thread. */
interface ForgeReviewComment {
/** Host identity of the comment. */
readonly id: ForgeCommentId
/** Author, or null when the account no longer exists. */
readonly author: ForgeCommentAuthor | null
/** Markdown source as the author wrote it; it may contain raw HTML, which readers must not render as HTML. */
readonly body: string
/** ISO 8601 time the comment was created. */
readonly createdAt: string
/** Whether the comment belongs to the signed-in user's review that is not submitted yet, which only that user sees. */
readonly pending: boolean
/** Web page of the comment, or null when the host reports none. */
readonly url: string | null
/** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */
readonly viewerCanEdit: boolean
/** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */
readonly viewerCanDelete: boolean
}
```
```ts type-equiv
/**
* One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was
* written on, and `current` on the head commit of the read. `current` is null once the host no longer places the
* thread on the head commit, as after later commits changed its lines.
*/
interface ForgeReviewThread {
/** Host identity of the thread. */
readonly id: ForgeThreadId
/** Repository-relative path the thread is on. */
readonly path: string
/** Old (`L`) or new (`R`) side of the diff the lines number. */
readonly side: 'L' | 'R'
/** Whether the thread is on lines or on the whole file. */
readonly subject: 'line' | 'file'
/** Lines in the diff that ends at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */
readonly current: ForgeAnchor | null
/** Lines in the diff that ended at the commit the thread was written on; null for a file thread. */
readonly original: ForgeAnchor | null
/** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */
readonly diffHunk: string | null
/** Whether the thread is marked resolved. */
readonly resolved: boolean
/** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */
readonly viewerCanReply: boolean
/**
* Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false
* for a provider without it.
*/
readonly viewerCanResolve: boolean
/** Comments oldest first; the first starts the thread. */
readonly comments: readonly ForgeReviewComment[]
}
```
```ts type-equiv
/** Review threads of a change request read at one head commit. */
interface ForgeReviewData {
/** Head commit the threads were read at; `current` positions number its files. */
readonly headSha: string
/** Login of the signed-in user the provider read as, or null when the host does not name one. */
readonly viewer: string | null
/** Threads in host order, at most the provider's limit. */
readonly threads: readonly ForgeReviewThread[]
/** Whether the change request has more threads than `threads` holds. */
readonly truncated: boolean
/** The signed-in user's pending review, or null without one. */
readonly pendingReview: ForgePendingReview | null
/**
* Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`;
* false for a provider without it.
*/
readonly viewerCanReview: boolean
}
```
`ctx.forge.writeReview(ref, write, signal)` writes to the review threads and the signed-in user's pending review: a reply, at once or with `pending` inside the pending review; resolving or unresolving a thread; editing or deleting a comment; a line comment at the head added to the pending review; and submitting or discarding the pending review. A pending reply or comment starts a pending review when the user has none. Every write carries the head commit the user saw; the provider checks it first and returns `stale` without writing once the head moved, which polls a watched change request as a stale read does, and the service polls a watched change request at once after any other result. Writes are never retried, and an `unknown` result must be checked on the host before the write is tried again. For a provider without `writeReview` the service returns `unsupported`. `ForgeReviewData` carries the pending review and the user's permissions for each thread, comment, and the pending review, which a provider without `writeReview` reports as absent, so consumers offer only the writes that can succeed. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns the GraphQL mutations and how their outcomes map onto these results.
```ts type-equiv
/** Opaque host identity of one review. */
type ForgeReviewId = Branded<'ForgeReviewId'>
```
```ts type-equiv
/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */
interface ForgePendingReview {
/** Host identity of the review. */
readonly id: ForgeReviewId
/** Comments the review holds. */
readonly comments: number
}
```
```ts type-equiv
/** Decision a submitted review records. */
type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes'
```
```ts type-equiv
/**
* One write to the review threads and the pending review of a change request. `pending` replies and `add-pending`
* comments join the signed-in user's pending review, which is started when the user has none. A host that adds every
* reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists.
*/
type ForgeReviewWrite = {
/** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */
readonly headSha: string
} & (
| { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean }
| { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean }
| { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string }
/** Deleting the only comment of a thread deletes the thread. */
| { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId }
/** A comment on lines of `headSha`. */
| { readonly kind: 'add-pending'; readonly comment: ForgeLineComment }
| { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string }
/** Delete the pending review with every comment it holds. */
| { readonly kind: 'discard-pending'; readonly review: ForgeReviewId }
)
```
```ts type-equiv
/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */
type ForgeReviewWriteResult =
| { readonly ok: true }
| { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string }
```
## Session bindings
`ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules.
@@ -623,6 +806,10 @@ type ForgeChangeRequestStatesFrame =
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.
`changeRequestReview(session, url, headSha, fresh)` reads the threads of a bound change request at the head of the diff the view shows and refuses another head with `forgePanel/stale-head`, `forgePanel/review-unsupported` for a provider without review reads, and `forgePanel/review-failed` otherwise. It keeps one read per change request in memory, keyed by head commit and the status's update time and bounded by `maxCachedReviewBytes`, and reads again once the kept read is `reviewRefreshMs` old or when `fresh` asks for it, as the first read after the reader refreshes the view does: on GitHub a new comment or reply changes a pull request's update time, but resolving a thread does not. The changes view asks again at every status it receives while visible, and overlays the threads on the files the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes.
`changeRequestReviewWrite(session, url, write)` passes one `ForgeReviewWrite` for a bound change request to `ctx.forge.writeReview` after checking its head commit, ids, text, and line range, and returns the `ForgeReviewWriteResult`. Once the provider answers, whatever the answer, it drops the kept threads of that change request and every read that started before, so the next `changeRequestReview` reads the host; `submitReview` drops them as well. The changes view sends one write at a time and reads the threads again after each write that may have changed them.
```ts type-equiv
/**
* Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order
@@ -923,6 +1110,30 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeReq
*/
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure>
/**
* Read the review threads of a change request at one head commit. A
* `stale` failure polls a watched change request again as {@link ForgeService.diff} does.
* @param ref - change request served by a registered provider.
* @param headSha - head commit the threads must be read at, usually the head of the displayed diff.
* @param signal - cancellation of the read.
* @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>
/**
* Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then
* poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls
* it as a stale read does.
* @param ref - change request served by a registered provider.
* @param write - the write and the head commit the user saw.
* @param signal - cancellation of the write.
* @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the
* outcome must be checked on the host before the write is tried again.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>
/**
* List the commits of a change request at its current head.
* @param ref - change request served by a registered provider.
@@ -1194,7 +1405,28 @@ Serves the forge panel. Following a Session inspects the checkout of its current
@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
/**
* Publish a line comment or completed review for a visible Session binding.
* Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read
* at the same head commit and update time are reused from memory, for any Session, until they are
* `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read
* again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull
* request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param headSha - head commit of the displayed diff.
* @param fresh - whether to read from the host even when threads at this head and update time are kept, as after the
* reader refreshes the view; the result replaces the kept threads.
* @param signal - request cancellation.
* @returns the threads at `headSha`, with `current` positions numbering the files of that diff.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
* `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again;
* `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the
* status was read and when the host does not provide the threads otherwise.
*/
@Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData>
/**
* Publish a line comment or completed review for a visible Session binding. The threads kept for the change request
* are dropped once the host answers, so the next read shows the comments.
* @param session - Session retaining the change request.
* @param url - visible binding URL.
* @param request - reviewed head, ranges, plain text, and explicit review decision.
@@ -1203,6 +1435,21 @@ Serves the forge panel. Following a Session inspects the checkout of its current
*/
@Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
* Write to the review threads or the pending review of a change request of a Session while its head is still the
* head the user saw. The threads kept for the change request are dropped once the host answers, so the next read
* shows the write, which a resolve does not show through a GitHub pull request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param write - the write and the head commit of the threads the user saw.
* @param signal - request cancellation.
* @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and
* `unknown` when the outcome must be checked on the host before the write is tried again.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error
* for a write without text, a head that is not a commit object name, or an invalid line range.
*/
@Remote async changeRequestReviewWrite( session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, ): Promise<ForgeReviewWriteResult>
/**
* Mark a draft change request of a Session ready for review; the change
* request is polled again once the host answers.
+253 -6
View File
@@ -47,6 +47,18 @@ interface ForgeProvider {
readonly forge: string
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
* Read the review threads of a change request at head commit `headSha`. The threads are returned only when the
* read names `headSha` as the head; once the head is another commit, the read resolves to a `stale` failure.
* Omission declares that this provider cannot read reviews.
*/
readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>
/**
* Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the
* head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares
* that this provider cannot write reviews, and its `readReview` then reports no viewer permission.
*/
writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>
/** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */
repositoryFromRemote(url: string): ForgeRepository | undefined
/** Map a change request web URL to its reference, or undefined when this provider does not serve it. */
@@ -244,9 +256,9 @@ 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; `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.
* a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure.
*/
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable'
readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable'
/** Human-readable cause. */
readonly message: string
}
@@ -303,7 +315,7 @@ interface ForgeActionFailure {
}
```
`ctx.forge.submitReview` 将明确指定的评论或完整评审交给 provider;未实现此能力的 provider 返回不支持。消费者保存待提交草稿,并在再次提交前核对结果不明的写操作。
`ctx.forge.submitReview` 将明确指定的评论或完整评审交给 provider;未实现此能力的 provider 返回不支持。消费者在再次提交前核对结果不明的写操作;留待之后一起提交的评论通过 `ctx.forge.writeReview` 写入代码托管平台的待提交评审。
```ts type-equiv
/** One inline comment addressed to the old or new side of a pull request diff. */
@@ -323,17 +335,188 @@ type ForgeReviewRequest = {
readonly headSha: string
} & (
| { readonly kind: 'comment'; readonly comment: ForgeLineComment }
| { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] }
| { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] }
)
```
```ts type-equiv
/** Result of a review write; unknown outcomes must be checked on the host before another submission. */
/** Result of a review submission; unknown outcomes must be checked on the host before another submission. */
type ForgeReviewResult =
| { readonly ok: true; readonly url: string }
| { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string }
```
## 评审讨论
`ctx.forge.readReview(ref, headSha, signal)` 读取变更请求在某个 head 提交处的评审讨论。只有当读取时的 head 就是 `headSha` 时,提供方才返回 `ForgeReviewData`;否则返回 `stale`,并像 diff 读取遇到 `stale` 时一样,立即重新轮询被关注的变更请求。提供方没有实现 `readReview` 时,服务返回 `unsupported`,使用方据此不显示讨论,也不报错。行级讨论有两套位置:`original` 是写下讨论时所在提交上的行,`current` 是本次读取的 head 上的行;托管平台不再把讨论放在该提交上时,`current` 为 null。显示 head diff 的使用方把讨论放在 `current` 位置,其余讨论用 `diffHunk` 展示;用 `fileText` 读取 `original.commit` 上的文件,可以看到写下讨论时的完整文件。GitHub 各字段如何映射到这两套位置,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。
```ts type-equiv
/** Opaque host identity of one review thread. */
type ForgeThreadId = Branded<'ForgeThreadId'>
```
```ts type-equiv
/** Opaque host identity of one review comment. */
type ForgeCommentId = Branded<'ForgeCommentId'>
```
```ts type-equiv
/** Consecutive lines on one side of a diff whose new side is one commit. */
interface ForgeAnchor {
/**
* Full object name of the commit the diff's new side shows: new-side (`R`) lines number this commit's file, and
* old-side (`L`) lines number the file at the diff's base.
*/
readonly commit: string
/** First line, inclusive. */
readonly startLine: number
/** Last line, inclusive. */
readonly endLine: number
}
```
```ts type-equiv
/** Account that wrote a review comment. */
interface ForgeCommentAuthor {
/** Login as the host spells it. */
readonly login: string
/** Avatar image URL, or null when the host reports none. */
readonly avatarUrl: string | null
/** Whether the account is an app or bot rather than a person. */
readonly bot: boolean
}
```
```ts type-equiv
/** One comment of a review thread. */
interface ForgeReviewComment {
/** Host identity of the comment. */
readonly id: ForgeCommentId
/** Author, or null when the account no longer exists. */
readonly author: ForgeCommentAuthor | null
/** Markdown source as the author wrote it; it may contain raw HTML, which readers must not render as HTML. */
readonly body: string
/** ISO 8601 time the comment was created. */
readonly createdAt: string
/** Whether the comment belongs to the signed-in user's review that is not submitted yet, which only that user sees. */
readonly pending: boolean
/** Web page of the comment, or null when the host reports none. */
readonly url: string | null
/** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */
readonly viewerCanEdit: boolean
/** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */
readonly viewerCanDelete: boolean
}
```
```ts type-equiv
/**
* One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was
* written on, and `current` on the head commit of the read. `current` is null once the host no longer places the
* thread on the head commit, as after later commits changed its lines.
*/
interface ForgeReviewThread {
/** Host identity of the thread. */
readonly id: ForgeThreadId
/** Repository-relative path the thread is on. */
readonly path: string
/** Old (`L`) or new (`R`) side of the diff the lines number. */
readonly side: 'L' | 'R'
/** Whether the thread is on lines or on the whole file. */
readonly subject: 'line' | 'file'
/** Lines in the diff that ends at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */
readonly current: ForgeAnchor | null
/** Lines in the diff that ended at the commit the thread was written on; null for a file thread. */
readonly original: ForgeAnchor | null
/** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */
readonly diffHunk: string | null
/** Whether the thread is marked resolved. */
readonly resolved: boolean
/** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */
readonly viewerCanReply: boolean
/**
* Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false
* for a provider without it.
*/
readonly viewerCanResolve: boolean
/** Comments oldest first; the first starts the thread. */
readonly comments: readonly ForgeReviewComment[]
}
```
```ts type-equiv
/** Review threads of a change request read at one head commit. */
interface ForgeReviewData {
/** Head commit the threads were read at; `current` positions number its files. */
readonly headSha: string
/** Login of the signed-in user the provider read as, or null when the host does not name one. */
readonly viewer: string | null
/** Threads in host order, at most the provider's limit. */
readonly threads: readonly ForgeReviewThread[]
/** Whether the change request has more threads than `threads` holds. */
readonly truncated: boolean
/** The signed-in user's pending review, or null without one. */
readonly pendingReview: ForgePendingReview | null
/**
* Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`;
* false for a provider without it.
*/
readonly viewerCanReview: boolean
}
```
`ctx.forge.writeReview(ref, write, signal)` 写入评审讨论和当前登录用户的待提交评审:回复讨论,立即发布,或在 `pending` 时加入待提交评审;把讨论标记为已解决或取消解决;编辑或删除评论;在 head 上添加一条行内评论到待提交评审;以及提交或丢弃待提交评审。用户还没有待提交评审时,待提交的回复或评论会先开始一个评审。每个写操作都带有用户看到的 head 提交;提供方先检查它,head 已变化时不写入,直接返回 `stale`,并像读取遇到 `stale` 时那样重新轮询被关注的变更请求;其他结果之后,服务都会立即重新轮询被关注的变更请求。写操作从不重试;结果为 `unknown` 时,必须先在托管平台上核对,再重试。提供方没有实现 `writeReview` 时,服务返回 `unsupported`。`ForgeReviewData` 带有待提交评审,以及用户对每个讨论、每条评论和待提交评审的权限;未实现 `writeReview` 的提供方把这些权限报告为没有,使用方据此只提供能够成功的写操作。GraphQL mutation 以及它们的结果如何对应到这些返回值,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。
```ts type-equiv
/** Opaque host identity of one review. */
type ForgeReviewId = Branded<'ForgeReviewId'>
```
```ts type-equiv
/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */
interface ForgePendingReview {
/** Host identity of the review. */
readonly id: ForgeReviewId
/** Comments the review holds. */
readonly comments: number
}
```
```ts type-equiv
/** Decision a submitted review records. */
type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes'
```
```ts type-equiv
/**
* One write to the review threads and the pending review of a change request. `pending` replies and `add-pending`
* comments join the signed-in user's pending review, which is started when the user has none. A host that adds every
* reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists.
*/
type ForgeReviewWrite = {
/** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */
readonly headSha: string
} & (
| { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean }
| { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean }
| { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string }
/** Deleting the only comment of a thread deletes the thread. */
| { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId }
/** A comment on lines of `headSha`. */
| { readonly kind: 'add-pending'; readonly comment: ForgeLineComment }
| { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string }
/** Delete the pending review with every comment it holds. */
| { readonly kind: 'discard-pending'; readonly review: ForgeReviewId }
)
```
```ts type-equiv
/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */
type ForgeReviewWriteResult =
| { readonly ok: true }
| { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string }
```
## Session 绑定
`ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。
@@ -623,6 +806,10 @@ type ForgeChangeRequestStatesFrame =
变更视图经同一个 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 重新读取。因此评审评论始终指向视图所显示行的那个提交。
`changeRequestReview(session, url, headSha, fresh)` 在视图所显示 diff 的 head 处读取已绑定变更请求的讨论;head 不同时以 `forgePanel/stale-head` 拒绝,提供方不支持读取讨论时返回 `forgePanel/review-unsupported`,其他失败返回 `forgePanel/review-failed`。每个变更请求在内存里保留一次读取结果,以 head 提交和状态的更新时间为键、受 `maxCachedReviewBytes` 约束,保留时间达到 `reviewRefreshMs` 后,或 `fresh` 要求时(读者刷新视图后的第一次读取就是这样)重新读取:在 GitHub 上,新评论和回复会改变 PR 的更新时间,解决讨论则不会。变更视图可见时,每收到一次状态就重新请求一次,并按[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package) 所述把讨论叠加到文件上。
`changeRequestReviewWrite(session, url, write)` 检查已绑定变更请求的一个 `ForgeReviewWrite` 的 head 提交、id、文字和行范围后,交给 `ctx.forge.writeReview`,并返回 `ForgeReviewWriteResult`。提供方给出答复后,无论结果如何,都会丢弃该变更请求保留的讨论,以及在此之前开始的所有读取,使下一次 `changeRequestReview` 从托管平台读取;`submitReview` 同样如此。变更视图一次只发送一个写操作,每个可能改变讨论的写操作之后都会重新读取讨论。
```ts type-equiv
/**
* Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order
@@ -923,6 +1110,30 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise<ChangeReq
*/
async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<string | ForgeFailure>
/**
* Read the review threads of a change request at one head commit. A
* `stale` failure polls a watched change request again as {@link ForgeService.diff} does.
* @param ref - change request served by a registered provider.
* @param headSha - head commit the threads must be read at, usually the head of the displayed diff.
* @param signal - cancellation of the read.
* @returns the threads read at `headSha`, or why the host did not provide them; `unsupported` when the provider cannot read reviews.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise<ForgeReviewData | ForgeFailure>
/**
* Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then
* poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls
* it as a stale read does.
* @param ref - change request served by a registered provider.
* @param write - the write and the head commit the user saw.
* @param signal - cancellation of the write.
* @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the
* outcome must be checked on the host before the write is tried again.
* @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
*/
async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise<ForgeReviewWriteResult>
/**
* List the commits of a change request at its current head.
* @param ref - change request served by a registered provider.
@@ -1194,7 +1405,28 @@ Serves the forge panel. Following a Session inspects the checkout of its current
@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise<string>
/**
* Publish a line comment or completed review for a visible Session binding.
* Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read
* at the same head commit and update time are reused from memory, for any Session, until they are
* `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read
* again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull
* request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param headSha - head commit of the displayed diff.
* @param fresh - whether to read from the host even when threads at this head and update time are kept, as after the
* reader refreshes the view; the result replaces the kept threads.
* @param signal - request cancellation.
* @returns the threads at `headSha`, with `current` positions numbering the files of that diff.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
* `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again;
* `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the
* status was read and when the host does not provide the threads otherwise.
*/
@Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData>
/**
* Publish a line comment or completed review for a visible Session binding. The threads kept for the change request
* are dropped once the host answers, so the next read shows the comments.
* @param session - Session retaining the change request.
* @param url - visible binding URL.
* @param request - reviewed head, ranges, plain text, and explicit review decision.
@@ -1203,6 +1435,21 @@ Serves the forge panel. Following a Session inspects the checkout of its current
*/
@Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
* Write to the review threads or the pending review of a change request of a Session while its head is still the
* head the user saw. The threads kept for the change request are dropped once the host answers, so the next read
* shows the write, which a resolve does not show through a GitHub pull request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param write - the write and the head commit of the threads the user saw.
* @param signal - request cancellation.
* @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and
* `unknown` when the outcome must be checked on the host before the write is tried again.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error
* for a write without text, a head that is not a commit object name, or an invalid line range.
*/
@Remote async changeRequestReviewWrite( session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, ): Promise<ForgeReviewWriteResult>
/**
* Mark a draft change request of a Session ready for review; the change
* request is polled again once the host answers.
@@ -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-ax-read-limits/guide.md
/:
en: a8ca814cf60ea12e
zh: f068d1ee13e80594
/macos-ax-tree-read-limits:
en: a7eed0c191ff2b32
zh: 15291798ba91329b
/macos-ax-tree-read-limits/change:
en: e4281d86095b950f
zh: 684ddf2957443ace
/macos-ax-tree-read-limits/migration:
en: 97a3885f5d1cb907
zh: 19313c56eff68835
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "macOS reads more AX nodes by default and accepts per-read overrides of configured traversal budgets."
---
# macOS AX tree read limits
English | [中文](guide.zh.md)
## Change
The default macOS node count rises from 2000 to 5000 and the default depth from 25 to 50. Reading a large window can take longer and emit more text to the model.
Configured `maxElements` and `maxDepth` now supply defaults independently for omitted arguments. Callers can request larger or smaller values for one read. Paste menu discovery continues to use the configured limits.
## Migration
1. To keep the previous budgets for ordinary reads, find the `@deepseek-ai/dsh-experimental-cua-macos` entry in your `cordis.yml` or profile patch. Set `maxElements: 2000` and `maxDepth: 25` in its existing `config`.
2. Restart the profile and confirm both defaults in the Computer Use model instructions.
3. If a script depends on specific traversal budgets, pass them explicitly to `getAccessibilityTree()`. An override applies only to that call.
@@ -0,0 +1,20 @@
---
kind: upgrade-guide
description: "macOS 默认读取更多 AX 节点,调用方可为单次读取覆盖配置值。"
---
# macOS AX 树读取范围
[English](guide.md) | 中文
## 变更
macOS 的默认节点数从 2000 增至 5000,默认深度从 25 增至 50。窗口中有更多节点可访问时,读取可能耗时更长,输出到模型的文本也可能增加。
`maxElements` 和 `maxDepth` 分别决定省略对应参数时的读取范围。调用方可以为一次读取指定高于或低于配置的值。查找粘贴菜单始终使用配置值。
## 迁移
1. 如需沿用原先的常规读取范围,在 `cordis.yml` 或配置补丁中找到 `@deepseek-ai/dsh-experimental-cua-macos`,在现有的 `config` 下设置 `maxElements: 2000` 和 `maxDepth: 25`。
2. 重启配置,确认 Computer Use 模型说明中的两个默认值与配置一致。
3. 如果脚本依赖特定的遍历范围,在 `getAccessibilityTree()` 的调用处显式传入这两个参数。一次调用的覆盖值不会影响后续读取。
@@ -12,5 +12,5 @@
en: e5d1027faa55adba
zh: 4b88ad6a70977fb3
/native-cua-application-and-window-api/migration:
en: a63e88dce467d6ee
zh: fc25bb283ca0eaff
en: 071b67613c512b84
zh: 7ee32d8dbcf7a0f2
@@ -16,7 +16,7 @@ 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()`. 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.
2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Application and window selection does not read AX. Before using element IDs, call `getAccessibilityTree()` explicitly; use `{ emit: false }` to retain the snapshot without displaying it. A screenshot does not require a successful AX read. Before coordinate input, including relative coordinates, obtain a successful AX observation covering the window or a screenshot; absolute coordinates require a screenshot. See [macOS AX read limits](../cua-ax-read-limits/guide.md) for changes to traversal defaults and configuration.
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`. 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.
@@ -16,7 +16,7 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享
## 迁移
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` 为真才读取。要显示树,请显式读取。
2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择应用或窗口不读取 AX。使用元素 ID 前须显式调用 `getAccessibilityTree()`;使用 `{ emit: false }` 可保留快照但不显示树。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)之前都须成功读取覆盖该窗口的 AX 或取得截图;绝对坐标要求截图。[读取上限的迁移说明](../cua-ax-read-limits/guide.zh.md)列出了 macOS 默认值和配置含义的变化。
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 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。
5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。
@@ -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-review-reads/guide.md
/:
en: 53dbdc67362a5851
zh: 9c7b2c4dd31cf666
/forge-failures-report-unsupported-reads:
en: 3e5488f3008886b7
zh: 8123e954c41d559c
/forge-failures-report-unsupported-reads/change:
en: 77712ff12908e838
zh: 00714f77f3b7ae80
/forge-failures-report-unsupported-reads/migration:
en: 698a34a7e09be2be
zh: a32a64dc130f496f
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "ForgeFailure gains the unsupported code, which ctx.forge.readReview returns for a provider without review reads."
---
# Forge failures report unsupported reads
English | [中文](guide.zh.md)
## Change
`ForgeFailure['code']` gains `unsupported`. `ctx.forge.readReview(ref, headSha, signal)`, new beside the optional `ForgeProvider.readReview`, returns it when the provider of the change request does not read review threads. Other reads keep their codes: a provider without `fetchChecks` still makes `ctx.forge.fetchChecks` return `unavailable`.
This affects code that switches exhaustively over `ForgeFailure['code']`, such as a `Record<ForgeFailure['code'], …>` lookup or a `switch` that ends in `assertNever`. All types come from `@deepseek-ai/dsh-experimental-forge`. Providers need no change: `readReview` is optional.
## Migration
1. Handle `unsupported` wherever code switches exhaustively over `ForgeFailure['code']`; treat it as a capability the provider lacks, not as a failed read to retry.
2. Run your type check; it succeeds when no `ForgeFailure` code is unhandled.
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "ForgeFailure 新增 unsupported 代码;提供方不支持读取评审讨论时,ctx.forge.readReview 返回它。"
---
# Forge 失败代码报告不支持的读取
[English](guide.md) | 中文
## 变更
`ForgeFailure['code']` 新增 `unsupported`。新增的 `ctx.forge.readReview(ref, headSha, signal)` 对应可选的 `ForgeProvider.readReview`;变更请求的提供方不支持读取评审讨论时,它返回 `unsupported`。其他读取的代码不变:提供方未实现 `fetchChecks` 时,`ctx.forge.fetchChecks` 仍返回 `unavailable`。
受影响的是对 `ForgeFailure['code']` 做穷举的代码,例如 `Record<ForgeFailure['code'], …>` 查表,或以 `assertNever` 结尾的 `switch`。所有类型都来自 `@deepseek-ai/dsh-experimental-forge`。提供方无需修改:`readReview` 是可选方法。
## 迁移
1. 在所有对 `ForgeFailure['code']` 做穷举的地方处理 `unsupported`,把它当作提供方缺少的能力,而不是需要重试的读取失败。
2. 运行类型检查;没有未处理的 `ForgeFailure` 代码时即通过。
@@ -118,8 +118,14 @@ it('ends a silent proxy connection and its Git child at the connection deadline'
await transport.connected
const result = await running
expect(result?.kind).toBe('timeout')
// The result records the status the terminated Git is read as; only the streamed run reports no exit code.
expect(result).toMatchObject({ exitCode: 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git') })
// Git's termination status varies by platform; preserve the observed status, or the fallback when absent.
const childRun = vi.mocked(subprocess.execa).mock.results.at(-1)
if (childRun?.type !== 'return') throw new Error('Git probe did not return a child process')
const childResult = await childRun.value
expect(childResult.timedOut).toBe(true)
expect(result).toMatchObject({
exitCode: childResult.exitCode ?? 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git'),
})
expect(result!.output).toContain('connection to github.com timed out after 3000ms')
await transport.disconnected
expect(transport.sockets.size).toBe(0)
@@ -137,6 +143,18 @@ it('cancels a connected Git probe and closes its transport before the deadline',
expect(transport.sockets.size).toBe(0)
})
it.each([128, undefined])('reports a timeout while retaining Git exit status %s', async (exitCode) => {
const { check } = await fixture()
const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({
failed: true, timedOut: true, exitCode,
} as Awaited<ReturnType<typeof subprocess.execa>>)
onTestFinished(() => { run.mockRestore() })
const result = await check('github:acme/plugin')
expect(result).toMatchObject({ exitCode: exitCode ?? 1, timedOut: true, kind: 'timeout' })
expect(result!.output).toContain('connection to github.com timed out after 3000ms')
expect(await readFile(result!.logPath, 'utf8')).toBe(result!.output)
})
it.each([undefined, 'Git could not start'])('retains a diagnostic when Git writes no stderr (%s)', async (shortMessage) => {
const { check } = await fixture()
const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ failed: true, shortMessage } as Awaited<ReturnType<typeof subprocess.execa>>)
@@ -0,0 +1,32 @@
/** Tests for the package-tree scan helpers that the stylesheet contracts range over. */
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { packageFiles } from './stylesheet-scan.ts'
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
it('skips dot directories holding transient roots', () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-stylesheet-scan-'))
roots.push(root)
mkdirSync(join(root, 'pkg', 'nested'), { recursive: true })
writeFileSync(join(root, 'pkg', 'package.json'), '{}')
writeFileSync(join(root, 'pkg', 'nested', 'package.json'), '{}')
mkdirSync(join(root, '.typert-worker-failure-probe'))
writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}')
// The helper reports `/`-separated paths on every platform, so the Windows
// temporary root's separators must not reach the expectation. Traversal
// reports the nested manifest before its parent, and directory order is not
// guaranteed, so both sides are compared sorted.
const normalized = root.replaceAll('\\', '/')
expect(packageFiles(name => name === 'package.json', root).sort()).toEqual([
`${normalized}/pkg/nested/package.json`,
`${normalized}/pkg/package.json`,
])
})
@@ -73,22 +73,28 @@ export function varReferences(value: string): string[] {
/**
* Every file shipped as package source whose name the predicate accepts,
* excluding build output and installed dependencies.
* excluding build output, installed dependencies, and dot directories.
* Dot directories hold VCS metadata and per-test temporary roots rather than
* shipped source, and their owner can remove one while a scan reads it.
* @param accepts - filename predicate.
* @returns absolute paths under packages/, `/`-separated on every platform so
* @param root - tree to walk, the packages directory by default.
* @returns absolute paths under `root`, `/`-separated on every platform so
* specs can match repo-relative suffixes verbatim.
*/
export function packageFiles(accepts: (name: string) => boolean): string[] {
export function packageFiles(accepts: (name: string) => boolean, root: string = PACKAGES_DIR): string[] {
const found: string[] = []
const walk = (dir: string): void => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name)
if (entry.isDirectory()) {
if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path)
// Dot directories hold VCS metadata and the temporary roots each spec
// creates inside the package tree, never shipped package source; a
// concurrent owner can remove one while a scan reads it.
if (!entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path)
} else if (accepts(entry.name)) found.push(path.replaceAll('\\', '/'))
}
}
walk(PACKAGES_DIR)
walk(root)
return found
}
@@ -15,23 +15,23 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
en: c7e1b7d87ccccd2e
zh: 42d864b918a6175c
en: dfa8a37cfe5da8ce
zh: 5583699567f6c053
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
en: eaf062b1439ed8b3
zh: d7c6a68779774825
en: 0feae5f8c5ef559f
zh: 5334adff35e3bebd
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
en: fa4d8c579ffc49ff
zh: 5856ed7469e4585b
/deepseek-ai-dsh-experimental-client-ui-forge/model-experience:
en: 10101427d1e0589b
zh: c981cec12f64eb75
en: 795766e162ebf4df
zh: 893de3302798330a
/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: 4124d453778daf7b
zh: 33cab3137381942e
en: da0e90e368524e68
zh: 1763d9c607926013
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
@@ -38,17 +38,18 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
- **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, 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. 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.
- **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. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress shown as a ring and a count, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. 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 Line truncated
- **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.
- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none.
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`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` 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`, `maxCachedReviewBytes`, `reviewRefreshMs`, `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 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.
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. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. 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. Once the review threads are read and the user may review, the GitHub split button starts the user's pending review on GitHub with the comment, or adds the comment to it; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately, which GitHub refuses while the user has a pending review, so the menu is then absent. Agent references and published comments remain beside their code. 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. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. On the user's own pull request, which GitHub lets its author only comment on, Approve and Request changes are unavailable. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments 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 them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. 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.
-----
@@ -69,11 +70,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/<remote>/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 :<path>` 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 tLine truncated
`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/<remote>/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 :<path>` 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 tLine truncated
`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/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, 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.<Session>`, 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.
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/<session>/local` and `dsh-resource://forge-changes/<session>/change/<url>`, 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.<Session>`, 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 or a jump to one of its review threads targets it, 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 |
|---|---|
@@ -96,6 +97,11 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
| [`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/ReviewThreads.tsx`](src/client/ReviewThreads.tsx) | Review thread cards and the outdated section |
| [`src/client/ThreadList.tsx`](src/client/ThreadList.tsx) | Thread list |
| [`src/client/review-threads.ts`](src/client/review-threads.ts) | Thread places, list filters, hunk excerpts, and thread quotes |
| [`src/client/thread-state.ts`](src/client/thread-state.ts) | Thread reads and their places in the shown changes |
| [`src/review-cache.ts`](src/review-cache.ts) | Review threads kept in memory |
| [`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 |
@@ -118,7 +124,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
<a id="model-experience"></a>
## 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, 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.
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. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line.
#### KV Cache effect
@@ -143,6 +149,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
- **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 thread writes** — a write through one changes view shows in other open views of the change request at their next status, or after `reviewRefreshMs` for a resolve, which does not change the pull request's update time. GitHub keeps one pending review per user and pull request. A comment draft an earlier version kept in the browser can join the pending review only while its file and lines still match the shown diff; otherwise it can only be edited or deleted. A comment on chosen commits can only be added to the input. Minimized comments show like others, and avatars load from the code host's image server in the browser.
- **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.
@@ -38,17 +38,18 @@ kind: "package-reference"
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
- **标签页**——顶部一行显示当前检出的分支(分离 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 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 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 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。
- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。
检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。
diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。
`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。
`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`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 分段按钮会用这条评论在 GitHub 上开始用户的待提交评审,或把评论加入其中;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时 GitHub 会拒绝单条评论,因此这时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。在用户自己的 PR 上,GitHub 只允许作者评论,因此“批准”和“请求更改”不可用。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。
-----
@@ -69,11 +70,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/<remote>/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 :<path>` 从暂存区读取,其余经 `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` 得出;当前检出分Line truncated
Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes/<remote>/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 :<path>` 从暂存区读取,其余经 `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` 得出;当前检出分Line truncated
`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/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内时才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。
浏览器入口先挂载 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/<session>/local` 与 `dsh-resource://forge-changes/<session>/change/<url>` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.<Session>` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。
| 源码 | 职责 |
|---|---|
@@ -96,6 +97,11 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
| [`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/ReviewThreads.tsx`](src/client/ReviewThreads.tsx) | 评审讨论卡片与已过期区域 |
| [`src/client/ThreadList.tsx`](src/client/ThreadList.tsx) | 讨论列表 |
| [`src/client/review-threads.ts`](src/client/review-threads.ts) | 讨论位置、列表筛选、hunk 摘录与讨论引用 |
| [`src/client/thread-state.ts`](src/client/thread-state.ts) | 读取讨论并确定它们在所显示变更中的位置 |
| [`src/review-cache.ts`](src/review-cache.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 缺失卡片 |
@@ -118,7 +124,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
<a id="model-experience"></a>
## 模型体验
间接影响,经由工作目录服务与 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 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。
#### KV Cache 影响
@@ -143,6 +149,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
- **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。
- **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。
- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。
- **评审讨论的写入**——在一个变更视图中的写操作,会在该变更请求的其他已打开视图收到下一次状态时显示;解决讨论不会改变 pull request 的更新时间,要等到 `reviewRefreshMs` 之后才显示。GitHub 每个用户在每个 pull request 上只保留一个待提交评审。早期版本保存在浏览器中的评论草稿,只有其文件和行仍与所显示的 diff 一致时才能加入待提交评审,否则只能编辑或删除。对所选提交的评论只能添加到输入框。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。
- **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.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)记录了它的接入位置。
@@ -76,6 +76,7 @@ const FAILURE: Record<ForgeFailure['code'], ForgePanelKey> = {
'unauthenticated': 'change.failure.unauthenticated',
'too-large': 'change.failure.unavailable',
'stale': 'change.failure.unavailable',
'unsupported': 'change.failure.unavailable',
'unavailable': 'change.failure.unavailable',
}
@@ -5,6 +5,8 @@
.row { box-sizing: border-box; display: flex; align-items: center; gap: 6px; width: 100%; min-width: 0; min-height: 30px; padding: 4px 6px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; }
.row svg { flex: none; }
.name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Unresolved host review threads of a file, in the thread count chip treatment of the file header. */
.threads { flex: none; min-width: 16px; padding: 0 5px; box-sizing: border-box; border-radius: var(--dsw-radius-xs); background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 12%, transparent); color: var(--dsw-alias-state-business-primary); font-size: 11px; line-height: 16px; text-align: center; }
.selected { background: var(--dsw-alias-interactive-bg-hover); }
.chevron { display: inline-flex; flex: 0 0 12px; }
.collapsed { transform: rotate(-90deg); }
@@ -12,6 +14,11 @@
.menu { width: min(360px, calc(100vw - 24px)); }
.trigger { display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 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; }
.trigger:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; }
/* The label ends in an ellipsis once its toolbar lets the entry shrink. */
.anchor { min-width: 0; max-width: 100%; }
.trigger { min-width: 0; max-width: 100%; }
.triggerLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.triggerChevron { flex: none; }
@media (hover: hover) { .row:hover, .trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } }
@media (pointer: coarse) { .row { min-height: 44px; } .search input { font-size: 16px; } }
@@ -25,6 +25,8 @@ export interface ChangedFilesProps extends PropsLocale<typeof NS> {
readonly jump: (path: string) => void
/** A menu row participates in the shared menu's keyboard walk. */
readonly menu?: boolean
/** Unresolved host review threads by file path; files without any are absent. */
readonly threadCounts?: ReadonlyMap<string, number>
}
function Rows({ nodes, depth, props }: {
@@ -32,10 +34,11 @@ function Rows({ nodes, depth, props }: {
readonly depth: number
readonly props: ChangedFilesProps
}): ReactNode {
const { state, toggle, jump, menu, t } = props
const { state, toggle, jump, menu, threadCounts, t } = props
return nodes.map((node) => {
const directory = node.kind === 'directory'
const expanded = directory && (state.query.trim() !== '' || state.collapsed[node.path] !== true)
const threads = node.kind === 'file' ? threadCounts?.get(node.path) ?? 0 : 0
const label = node.kind === 'file' && node.file.previousPath !== null
? t('diff.renamedPath', { from: node.file.previousPath, path: node.path }) : node.path
return <div key={node.path}>
@@ -54,6 +57,7 @@ function Rows({ nodes, depth, props }: {
</span>
{directory ? <IconFolderCloseRegular size={14} /> : <FileTypeIcon path={node.path} size={14} />}
<span className={css.name}>{node.name}</span>
{threads > 0 && <span className={css.threads} title={t('thread.treeCount', { count: threads })}>{threads}</span>}
{node.kind === 'file' && <Counts file={node.file} t={t} />}
</button>
</Tooltip>
@@ -129,9 +133,12 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode {
*/
export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode {
const [open, setOpen] = useState(false)
return <Menu open={visible && open} portal dense align="start" listClassName={css.menu} onClose={() => { setOpen(false) }}
return <Menu open={visible && open} portal dense align="start" className={css.anchor} listClassName={css.menu} onClose={() => { setOpen(false) }}
anchor={<button type="button" className={css.trigger} aria-haspopup="menu" aria-expanded={visible && open} disabled={props.files.length === 0}
onClick={() => { setOpen(value => !value) }}>{props.t('diff.allFiles', { count: props.files.length })}<IconChevronDownOutlineRegular size={12} /></button>}>
onClick={() => { setOpen(value => !value) }}>
<span className={css.triggerLabel}>{props.t('diff.allFiles', { count: props.files.length })}</span>
<IconChevronDownOutlineRegular size={12} className={css.triggerChevron} />
</button>}>
<ChangedFiles {...props} menu jump={(path) => { setOpen(false); props.jump(path) }} />
</Menu>
}
@@ -125,10 +125,10 @@
border-inline-end: 0;
}
/* One line of controls, never wrapped; the fold rules after `.tool` move controls into the More menu as it narrows. */
.toolbarMain {
display: flex;
flex: 1;
flex-wrap: wrap;
align-items: center;
gap: 0 4px;
box-sizing: border-box;
@@ -155,30 +155,12 @@
flex: 1;
}
.progressSlot {
.progressSlot,
.foldTests,
.filesSlot {
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;
}
flex: none;
min-width: 0;
}
.select {
@@ -293,6 +275,36 @@
transform: rotate(90deg);
}
/* `observeToolbarFold` sets `data-fold` on the toolbar row to the shallowest level whose items fit on one line: level 1
folds the line totals, expansion, side by side, and wrapping into the More menu; level 2 the test switch, with the
progress shown as a ring; level 3 refresh. */
.more {
display: none;
}
.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .foldViews,
.toolbarMain:is([data-fold='2'], [data-fold='3']) .foldTests,
.toolbarMain[data-fold='3'] .foldRefresh {
display: none;
}
/* With every control folded, the file list entry shortens its label before the row overflows. */
.toolbarMain[data-fold='3'] .filesSlot {
flex-shrink: 1;
}
.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .more {
display: inline-flex;
}
.toolbarMain:is([data-fold='2'], [data-fold='3']) .progressSlot [data-forge-progress='full'] {
display: none;
}
.toolbarMain:is([data-fold='2'], [data-fold='3']) .progressSlot [data-forge-progress='compact'] {
display: inline-flex;
}
/* A menu row with a path that shortens and its counts. */
.menuRow {
display: flex;
@@ -333,6 +345,7 @@
}
.body {
position: relative;
display: flex;
flex: 1;
min-height: 0;
@@ -678,6 +691,36 @@
background: var(--forge-diff-empty);
}
/* Comments under a side-by-side row: one cell per column, each continuing its line's gutter and background, with the
comments aligned to the code text. Either side holds its own comments, so both sides can show one at once. */
.notes {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
white-space: normal;
}
.noteCell {
display: grid;
grid-template-columns: var(--forge-number-width, 3.5em) minmax(0, 1fr);
min-width: 0;
}
.noteCell + .noteCell {
border-left: 0.5px solid var(--dsw-alias-border-l3);
}
.noteStack {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
padding: 8px 12px 10px calc(1.4em + 6px);
}
.noteStack:empty {
padding: 0;
}
/* Collapsed unchanged lines; the row expands them. */
/* Collapsed unchanged lines, a collapsed large file, and a file whose lines cannot be drawn share one strip;
only the first two open on a click. */
@@ -859,9 +902,76 @@
.code[data-split][data-native-side="L"] [data-diff-side="R"] *,
.code[data-split][data-native-side="R"] [data-diff-side="L"],
.code[data-split][data-native-side="R"] [data-diff-side="L"] * { user-select: none; }
.reviewSubmit { flex: none; white-space: nowrap; }
/* A header button keeps its label on one line; the menus and the title before it shorten instead. */
.headerAction { flex: none; white-space: nowrap; }
.code[data-single-side] .line { grid-template-columns: var(--forge-number-width) 1.4em minmax(0, 1fr); }
.code[data-single-side]:not([data-wrap]) .line { grid-template-columns: var(--forge-number-width) 1.4em max-content; }
.reviewFile { padding: 12px 0; }
.reviewFile > h3 { margin: 0 10px; font-size: 12px; font-weight: 500; overflow-wrap: anywhere; }
/* The unresolved thread count of a file opens the thread list at the file. */
.threadCount {
flex: none;
height: 20px;
padding: 0 6px;
border: 0;
border-radius: var(--dsw-radius-xs);
background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 12%, transparent);
color: var(--dsw-alias-state-business-primary);
font: inherit;
font-size: 11px;
line-height: 20px;
white-space: nowrap;
cursor: pointer;
}
/* Drawn inside the button, since the file title clips what overflows it. */
.threadCount:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -1px;
}
@media (hover: hover) {
.threadCount:hover { background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 20%, transparent); }
}
/* A view narrower than 480px shows the count alone. */
.threadCountNumber { display: none; }
@container forge-changes (max-width: 479px) {
.threadCountText { display: none; }
.threadCountNumber { display: inline; }
}
/* Opens the thread list; pressed while the list shows. */
.threadsToggle {
display: inline-flex;
flex: none;
align-items: center;
gap: 6px;
height: 28px;
padding: 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;
}
.threadsToggle[aria-pressed='true'] { background: var(--dsw-alias-interactive-bg-hover); }
@media (hover: hover) {
.threadsToggle:hover { background: var(--dsw-alias-interactive-bg-hover); }
}
.threadsTotal {
padding: 0 5px;
border-radius: var(--dsw-radius-xs);
background: var(--forge-fill);
color: var(--dsw-alias-label-secondary);
font-size: 11px;
line-height: 16px;
}
@@ -25,12 +25,16 @@ import {
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
import type {
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff,
ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState,
} from '../types.ts'
import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types'
import type {
ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult,
ForgeThreadId,
} 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'
@@ -51,6 +55,12 @@ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts'
import { ChangeRequestGlyph } from './glyphs.tsx'
import type { ForgePanelKey, NS } from './locales.ts'
import { RefreshGlyph } from './RefreshGlyph.tsx'
import { ViewOptionsMenu } from './ViewOptionsMenu.tsx'
import { observeToolbarFold } from './toolbar-fold.ts'
import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx'
import { inFileOrder, type ThreadFilter } from './review-threads.ts'
import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts'
import { ThreadList } from './ThreadList.tsx'
import type { PanelSnapshot } from './source.ts'
import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf } from './status.ts'
import css from './ChangesTab.module.css'
@@ -60,6 +70,12 @@ type Translate = PropsLocale<typeof NS>['t']
/** Kind of a local scope. */
type ScopeKind = ForgeLocalScope['kind']
/** A file the view scrolls to once, and the thread card it centers there with whether that card takes the focus. */
interface Wanted {
readonly path: string
readonly center: { readonly id: ForgeThreadId; readonly focus: boolean } | null
}
/** Business face of the changes tab body. */
export interface ChangesTabInjected {
/** Append a frozen comment to the main input without submitting it. */
@@ -90,6 +106,14 @@ export interface ChangesTabInjected {
readonly viewedFiles: ViewedFiles
/** Read one file of a change request at a commit. */
readonly changeRequestText: (url: string, commit: string, path: string) => Promise<RemoteResult<string>>
/** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */
readonly changeRequestReview: (
url: string, headSha: string, fresh: boolean, signal: AbortSignal,
) => Promise<RemoteResult<ForgeReviewData>>
/** Write to the review threads or the pending review of a change request; never retries a write. */
readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise<RemoteResult<ForgeReviewWriteResult>>
/** Quote a whole review thread of the change request at `url` in the main input without submitting it. */
readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean
/** Open a URL outside the app. */
readonly openLink: (url: string) => void
/** Copy a path to the clipboard and report the outcome. */
@@ -134,6 +158,12 @@ type ChangesData =
readonly fileUrls: Readonly<Record<string, string>>
}
/** Why the code host did not take a review write, and whether it may have applied it. */
interface WriteRefusal {
readonly message: string
readonly unknown: boolean
}
/** Unchanged lines read for one loaded diff: each file's new side and its expanded gaps. */
interface Expansion {
readonly data: ChangesData | null
@@ -302,7 +332,7 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis
{number !== null && <span className={css.headerNumber}>{t('change.number', { number })}</span>}
<span className={css.headerEnd}>
{commitMenu}
<Button size="sm" variant="outline" className={css.reviewSubmit} disabled={reviewDisabled} onClick={onReview}>
<Button size="sm" variant="outline" className={css.headerAction} disabled={reviewDisabled} onClick={onReview}>
{t('review.submit')}{reviewCount > 0 ? ` (${reviewCount})` : ''}
</Button>
</span>
@@ -353,7 +383,7 @@ function LocalHeader({ state, scope, base, missing, visible, diffBases, choose,
</>}
{(scope === 'branch' || creatable) && <span className={css.headerEnd}>
{scope === 'branch' && commitMenu}
{creatable && <Button size="sm" variant="outline" onClick={createChangeRequest}>{t('changes.local.create')}</Button>}
{creatable && <Button size="sm" variant="outline" className={css.headerAction} onClick={createChangeRequest}>{t('changes.local.create')}</Button>}
</span>}
</div>
)
@@ -416,7 +446,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale<typeof NS> & {
return <section className={css.reviewFile} data-forge-review-file={path}>
<h3>{path}</h3>
{state.threads.map(thread => <ReviewThread key={thread.key} thread={thread}
actions={actions} locked={state.locked} outdated split={false} t={t} />)}
actions={actions} locked={state.locked} outdated t={t} />)}
</section>
}
@@ -427,8 +457,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale<typeof NS> & {
*/
export function ChangesTab({
useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff,
changeRequestText, changeRequestCommits, viewedFiles,
openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t,
changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles,
openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t,
}: ChangesTabProps): ReactNode {
const { tab } = useTabInfo()
const { navigation, signal } = tab
@@ -476,8 +506,49 @@ export function ChangesTab({
setReviewBusy(false)
}
}
// Every write that may have changed the threads reads them again; writes run one at a time, so a write that starts a
// pending review settles before the next write looks for one.
const [reviewRevision, setReviewRevision] = useState(0)
const writing = useRef<Promise<unknown>>(Promise.resolve())
/**
* Send one write after the earlier ones.
* @returns undefined once the host took it, else its message and whether its outcome is unknown.
*/
const sendWrite = (url: string, write: ForgeReviewWrite): Promise<WriteRefusal | undefined> => {
const run = async (): Promise<WriteRefusal | undefined> => {
const response = await changeRequestReviewWrite(url, write)
if (!response.ok) {
if (response.error.code === 'forgePanel/not-bound') {
return { message: t('thread.writeFailed', { message: response.error.message }), unknown: false }
}
setReviewRevision(value => value + 1)
return { message: t('thread.writeUnknown'), unknown: true }
}
const result = response.value
if (result.ok) {
setReviewRevision(value => value + 1)
return undefined
}
switch (result.code) {
case 'unsupported': return { message: t('thread.writeUnsupported'), unknown: false }
case 'failed':
setReviewRevision(value => value + 1)
return { message: t('thread.writeFailed', { message: result.message }), unknown: false }
case 'stale': return { message: t('thread.writeStale'), unknown: false }
case 'unknown':
setReviewRevision(value => value + 1)
return { message: t('thread.writeUnknown'), unknown: true }
/* v8 ignore next -- closed ForgeReviewWriteResult code union exhaustiveness guard */
default: return assertNever(result.code, 'ForgeReviewWriteResult.code')
}
}
const next = writing.current.then(run, run)
writing.current = next
return next
}
const writeReview = async (url: string, write: ForgeReviewWrite): Promise<string | undefined> => (await sendWrite(url, write))?.message
const choices = useStore(store => store.byTab[tab.id])
const [wanted, setWanted] = useState<string | null>(null)
const [wanted, setWanted] = useState<Wanted | null>(null)
const [treeState, setTreeState] = useState<ChangedFilesState>({ query: '', collapsed: {}, selected: null })
const [treePosition, setTreePosition] = useState<FileTreePosition>('left')
const [treeWidth, setTreeWidth] = useState(0)
@@ -491,7 +562,7 @@ export function ChangesTab({
if (path === undefined) return
setTreeState(value => ({ ...value, selected: path }))
setChosen(value => ({ ...value, [path]: true }))
setWanted(path)
setWanted({ path, center: null })
}, [choices, navigation.revision, navigation.params, actions, tab.id])
// The tab's choices end with its record.
useEffect(() => {
@@ -564,6 +635,23 @@ export function ChangesTab({
return () => { controller.abort() }
}, [tab.visible, read, refused, waiting, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff])
const data = loaded !== null && loaded.key === dataKey ? loaded.data : null
// Threads show only while they were read at the head of the latest status and, for the whole change request, at
// the head the shown diff was read at, so their positions number the shown files.
const prHead = entry?.snapshot?.headSha ?? null
const prAuthor = entry?.snapshot?.author ?? null
const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead,
updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision, read: changeRequestReview })
const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead
&& (data.commits !== null || data.headSha === prHead) ? threadRead.review : null
const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null)
const [threadList, setThreadList] = useState<{
readonly open: boolean
readonly filter: ThreadFilter
/** Whether the reader just opened the list and it has not taken the focus yet. */
readonly claim: boolean
}>({ open: false, filter: 'unresolved', claim: false })
const threadsToggle = useRef<HTMLButtonElement>(null)
const [focus, setFocus] = useState<ThreadFocus | null>(null)
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,
@@ -587,6 +675,13 @@ export function ChangesTab({
const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file)
const sections = useRef(new Map<string, HTMLElement>())
const scrollport = useRef<HTMLDivElement | null>(null)
const toolbarRow = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
const row = toolbarRow.current
/* v8 ignore next -- the toolbar row renders in every state of the view */
if (row === null) return
return observeToolbarFold(row)
}, [])
const reach = useMemo(() => new SectionReach(), [])
const attachScrollport = useCallback((element: HTMLDivElement | null) => {
scrollport.current = element
@@ -597,14 +692,25 @@ export function ChangesTab({
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))
const hidden = allFiles.find(file => file.path === wanted.path && !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' })
const section = sections.current.get(wanted.path)
section?.scrollIntoView({ block: 'start' })
// A thread the reader opened from the thread list or a file's unresolved count centers inside its file, which the jump
// expanded and revealed; the jump ends here, so a later jump to the file stops at its header.
const { center } = wanted
if (center !== null) {
/* v8 ignore next 4 -- a centered thread's file is drawn and its card unfolded, so both are found. */
const card = [...section?.querySelectorAll<HTMLElement>('[data-forge-thread]') ?? []]
.find(element => element.dataset.forgeThread === center.id)
card?.scrollIntoView({ block: 'center' })
if (center.focus) card?.focus({ preventScroll: true })
}
if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop }
setWanted(null)
}, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id])
@@ -665,16 +771,68 @@ export function ChangesTab({
return list
}
// A review addresses the head commit, so it is submitted from the view of the whole change request.
// A review addresses the head commit, so it is submitted from the view of the whole change request. A pending review on
// the code host is submitted or discarded there; without one, the summary and any comment drafts kept in the browser
// are published as one review.
const pendingReview = review?.pendingReview ?? null
// Logins compare without case, as GitHub's do.
const ownChangeRequest = review?.viewer != null && prAuthor !== null && review.viewer.toLowerCase() === prAuthor.toLowerCase()
const finishWrite = async (send: () => Promise<string | undefined>, done: ForgePanelKey): Promise<void> => {
if (reviewRunning.current) return
reviewRunning.current = true
setReviewBusy(true)
setReviewError(null)
try {
const failure = await send()
if (failure !== undefined) {
setReviewError(failure)
return
}
report(done)
setReviewOpen(false)
} finally {
reviewRunning.current = false
setReviewBusy(false)
}
}
const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && data.commits === null && <SubmitReview queue={queue}
url={data.url} headSha={data.headSha} busy={reviewBusy} error={reviewError} close={() => { setReviewOpen(false) }}
url={data.url} headSha={data.headSha} pending={pendingReview} own={ownChangeRequest} busy={reviewBusy} error={reviewError}
close={() => { setReviewOpen(false) }}
check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }}
submit={() => {
const latest = queue.getSnapshot()
void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event,
body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url))
if (pendingReview === null) {
void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event,
body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url))
return
}
// The submission is kept as the write to reconcile until the host answers, so an unknown outcome blocks another
// submission, which would otherwise publish a second review once the pending review no longer reads.
void finishWrite(async () => {
if (!queue.begin({ kind: 'review', headSha: data.headSha, event: latest.event, body: latest.body, comments: [] })) {
return t('review.saveFailed')
}
const refusal = await sendWrite(data.url, { kind: 'submit-pending', headSha: data.headSha, review: pendingReview.id,
event: latest.event, body: latest.body })
if (refusal === undefined) {
if (!queue.finish(true)) report('review.saveFailed')
return undefined
}
if (!refusal.unknown) queue.finish(false)
return refusal.message
}, 'review.submitted')
}}
discard={pendingReview === null ? undefined : () => {
void finishWrite(() => writeReview(data.url, { kind: 'discard-pending', headSha: data.headSha, review: pendingReview.id }), 'review.discarded')
}} t={t} />
/** Add a comment to the pending review on the code host at the head the comment was selected on. */
const addPending = (selection: ReviewSelection): Promise<string | undefined> => {
if (selection.source.kind !== 'change') return Promise.resolve(t('review.stale'))
const { path, side, startLine, endLine, body } = selection.comment
return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } })
}
const recordActions: ReviewActions = {
source: shownSource ?? (source.kind === 'local'
? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) }
@@ -686,10 +844,57 @@ export function ChangesTab({
.filter(path => !data?.files.some(file => file.path === path))
const orphanRecords = absentPaths.map(path => <OrphanReviews key={path} path={path} actions={recordActions} t={t} />)
const jump = (path: string): void => {
// Thread groups keep their identity across renders that change neither the threads nor what their cards share, so
// only the sections whose threads changed redraw.
const url = data?.kind === 'change' ? data.url : null
const threadActions = useMemo((): ThreadActions | null => review === null || url === null ? null : {
author: prAuthor,
addToInput: (thread, range) => addThreadToInput(thread, url, range),
openLink,
readText: (commit, path) => changeRequestText(url, commit, path),
inputFailed: () => { live.current.report('thread.inputFailed') },
focused: focus,
writes: {
write: (write: ThreadWrite) => live.current.writeReview(url, { ...write, headSha: review.headSha }),
reviewStarted: review.pendingReview !== null,
canReview: review.viewerCanReview,
},
}, [review, url, prAuthor, addThreadToInput, openLink, changeRequestText, focus])
const fileThreads = useMemo(() => new Map<string, FileThreads>(threadActions === null ? []
: [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions])
/** Show a file's next unresolved thread in display order after the one last shown, or its first. */
const nextThread = (path: string): void => {
const order = inFileOrder(placed.entries.filter(({ thread }) => thread.path === path && !thread.resolved),
allFiles.find(file => file.path === path))
const next = order[(order.findIndex(({ thread }) => thread.id === focus?.id) + 1) % order.length]
/* v8 ignore next -- the count that calls this shows only while the file has an unresolved thread. */
if (next !== undefined) openThread(next, false)
}
/** Close the thread list at the reader's request and return the focus to its toggle. */
const closeThreadList = (): void => {
setThreadList(value => ({ ...value, open: false }))
threadsToggle.current?.focus()
}
/**
* Show a thread: all commits for a thread the chosen ones do not hold, whose diff holds the file of every thread with a
* position at the head, then its file, with the thread unfolded and centered; `focusCard` moves the focus to it. A
* thread on a file the shown changes lack opens on the host.
*/
const openThread = ({ thread, place }: PlacedThread, focusCard: boolean): void => {
if (place.kind === 'elsewhere') actions.committed(tab.id, null)
else if (!allFiles.some(file => file.path === thread.path)) {
const url = thread.comments[0]?.url ?? null
if (url !== null) openLink(url)
return
}
setFocus(value => ({ id: thread.id, revision: (value?.revision ?? 0) + 1 }))
setRevealed(value => new Set([...value, thread.path]))
jump(thread.path, { id: thread.id, focus: focusCard })
}
const jump = (path: string, center: Wanted['center'] = null): void => {
setTreeState(value => ({ ...value, selected: path }))
setChosen(value => ({ ...value, [path]: true }))
setWanted(path)
setWanted({ path, center })
}
/**
* The file being read: the file last jumped to while the scroll stays there, else the first file whose section still
@@ -738,7 +943,7 @@ export function ChangesTab({
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)
&& section.getBoundingClientRect().top < viewport.getBoundingClientRect().top) setWanted({ path: file.path, center: null })
// 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 })
}
@@ -765,8 +970,11 @@ export function ChangesTab({
// 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 callbacks = {
data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, t,
}
const live = useRef(callbacks)
live.current = callbacks
const handlers = useMemo((): DiffFileHandlers => ({
toggle: (file) => {
const byDefault = live.current.expandedByDefault(file)
@@ -792,26 +1000,31 @@ export function ChangesTab({
if (element === null) sections.current.delete(path)
else sections.current.set(path, element)
},
nextThread: (path) => { live.current.nextThread(path) },
reach,
}), [reach])
const reviewStarted = reviewState.comments.length > 0
const reviewStarted = pendingReview !== null
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
// Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments:
// into its pending review once the threads say the user may review, and on their own while the user has no pending
// review, since GitHub refuses a single comment beside one.
const whole = data?.kind === 'change' && data.commits === null
const queueable = whole && review?.viewerCanReview === true
const single = whole && pendingReview === 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'
...queueable ? { queue: (selection: ReviewSelection) => live.current.addPending(selection) } : {},
...single ? {
publish: (selection: ReviewSelection) => 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])
}, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single])
let body: ReactNode
if (data === null) {
@@ -868,6 +1081,8 @@ export function ChangesTab({
wrap={wrap}
badge={badgeOf(file, data, t)}
tooltip={pathTooltipOf(file, t)}
threads={fileThreads.get(path)}
drawNow={wanted !== null && wanted.center !== null && wanted.path === path}
viewed={viewedStateOf(marks, path, file.digest)}
handlers={handlers}
t={t}
@@ -883,10 +1098,15 @@ export function ChangesTab({
filter: (query) => { setTreeState(value => ({ ...value, query })) },
toggle: (path) => { setTreeState(value => ({ ...value, collapsed: { ...value.collapsed, [path]: value.collapsed[path] !== true } })) },
jump,
...review === null ? {} : { threadCounts: placed.unresolved },
}
// The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise.
const anyExpanded = files.some(isExpanded)
const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll')
const toggleExpansion = (): void => { setChosen(Object.fromEntries(files.map(file => [file.path, !anyExpanded]))) }
const toggleSplit = (): void => { actions.toggledSplit(tab.id) }
const toggleWrap = (): void => { actions.toggledWrap(tab.id) }
const toggleTests = (): void => { actions.toggledTests(tab.id) }
const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft')
let additions = 0
let deletions = 0
@@ -908,7 +1128,8 @@ export function ChangesTab({
? <LocalHeader state={state} scope={scope} base={base} missing={failed === 'forgePanel/base-missing'} visible={tab.visible}
diffBases={diffBases} choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu}
createChangeRequest={createChangeRequest} t={t} />
: <ChangeHeader url={source.url} entry={entry} openLink={openLink} commitMenu={commitMenu} reviewCount={reviewState.comments.length}
: <ChangeHeader url={source.url} entry={entry} openLink={openLink} commitMenu={commitMenu}
reviewCount={(pendingReview?.comments ?? 0) + reviewState.comments.length}
reviewDisabled={data === null || changeCommits !== null} onReview={() => { setReviewOpen(true) }} t={t} />}
{!reviewOpen && reviewState.error !== null && <Notice>{t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}</Notice>}
{!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' && <div className={css.reviewNotice} role="alert">
@@ -921,40 +1142,49 @@ export function ChangesTab({
<div className={css.toolbar} data-tree={treeShown ? treePosition : 'hidden'} style={toolbarStyle}>
{/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */}
{treeShown && <div className={css.lensCell}><LensControl {...lensProps} /></div>}
<div className={css.toolbarMain}>
<div ref={toolbarRow} className={css.toolbarMain}>
{tab.visible && source.kind === 'local' && <ScopeMenu scope={scope} choose={(next) => { actions.scoped(tab.id, next) }} t={t} />}
{tab.visible && <ChangedFilesMenu {...navigator} visible />}
{tab.visible && <span className={css.filesSlot}><ChangedFilesMenu {...navigator} visible /></span>}
{tab.visible && allFiles.length > 0 && (
<span className={clsx(css.lensMenu, css.reviewRow)}><LensMenu {...lensProps} visible /></span>
<span className={css.lensMenu}><LensMenu {...lensProps} visible /></span>
)}
{allFiles.length > 0 && <span className={css.reviewRow}>
<HideTestsSwitch hidden={hideTests} toggle={() => { actions.toggledTests(tab.id) }} t={t} />
{allFiles.length > 0 && <span className={css.foldTests}>
<HideTestsSwitch hidden={hideTests} toggle={toggleTests} t={t} />
</span>}
<span className={css.spacer} />
<span className={clsx(css.progressSlot, css.reviewRow)}><ViewedProgress viewed={viewedCount} total={files.length} t={t} /></span>
{files.length > 0 && <span className={css.totals}><Counts file={{ additions, deletions, binary: false }} t={t} /></span>}
<span className={css.spacer} data-fold-spacer="" />
{/* A truncated read keeps the list, whose footer says so, even when it kept no thread. */}
{review !== null && (review.threads.length > 0 || review.truncated) && (
<button ref={threadsToggle} type="button" className={css.threadsToggle} aria-pressed={threadList.open} data-forge-threads-toggle=""
aria-label={t('thread.listAria', { count: review.threads.length })}
onClick={() => { setThreadList(value => ({ ...value, open: !value.open, claim: !value.open })) }}>
{t('thread.list')}<span className={css.threadsTotal}>{review.threads.length}</span>
</button>
)}
<span className={css.progressSlot}><ViewedProgress viewed={viewedCount} total={files.length} t={t} /></span>
{files.length > 0 && (
<span className={clsx(css.totals, css.foldViews)}><Counts file={{ additions, deletions, binary: false }} t={t} /></span>
)}
<span className={css.tools}>
<Tooltip label={t('diff.refresh')} side="bottom">
<button type="button" className={css.tool} aria-label={t('diff.refresh')} onClick={refresh}>
<button type="button" className={clsx(css.tool, css.foldRefresh)} aria-label={t('diff.refresh')} onClick={refresh}>
<RefreshGlyph busy={rereading} size={16} />
</button>
</Tooltip>
<Tooltip label={expansionLabel} side="bottom">
<button type="button" className={css.tool} data-expanded={anyExpanded ? '' : undefined} aria-label={expansionLabel}
disabled={files.length === 0}
onClick={() => { setChosen(Object.fromEntries(files.map(file => [file.path, !anyExpanded]))) }}>
<button type="button" className={clsx(css.tool, css.foldViews)} data-expanded={anyExpanded ? '' : undefined} aria-label={expansionLabel}
disabled={files.length === 0} onClick={toggleExpansion}>
<IconChevronsUpDownOutlineRegular />
</button>
</Tooltip>
<Tooltip label={t(split ? 'diff.unified' : 'diff.split')} side="bottom">
<button type="button" className={css.tool} aria-pressed={split} aria-label={t('diff.splitAria')}
onClick={() => { actions.toggledSplit(tab.id) }}>
<button type="button" className={clsx(css.tool, css.foldViews)} aria-pressed={split} aria-label={t('diff.splitAria')}
onClick={toggleSplit}>
<IconCompareSplitOutlineRegular className={css.compareIcon} />
</button>
</Tooltip>
<Tooltip label={t(wrap ? 'diff.nowrap' : 'diff.wrap')} side="bottom">
<button type="button" className={css.tool} aria-pressed={wrap} aria-label={t('diff.wrapAria')}
onClick={() => { actions.toggledWrap(tab.id) }}>
<button type="button" className={clsx(css.tool, css.foldViews)} aria-pressed={wrap} aria-label={t('diff.wrapAria')}
onClick={toggleWrap}>
{wrap ? <IconNowrapFillRegular /> : <IconWrapFillRegular />}
</button>
</Tooltip>
@@ -967,8 +1197,11 @@ export function ChangesTab({
</button>
</Tooltip>
</span>
<ViewOptionsMenu visible={tab.visible} options={{
anyExpanded, hasFiles: files.length > 0, toggleExpansion, split, toggleSplit, wrap, toggleWrap,
hideTests: allFiles.length > 0 ? hideTests : undefined, toggleTests, refresh,
}} t={t} />
</span>
{allFiles.length > 0 && <span className={css.rowBreak} />}
</div>
</div>
{data !== null && failed !== null && (
@@ -982,10 +1215,26 @@ export function ChangesTab({
<Notice>{t('diff.stale', { count: data.localAhead })}</Notice>
)}
{data?.kind === 'local' && data.omitted > 0 && <Notice>{t('diff.omitted', { count: data.omitted })}</Notice>}
{data?.kind === 'change' && threadRead.failure !== null && (
<Notice action={<Button size="sm" variant="outline" className={css.noticeAction} onClick={refresh}>{t('retry')}</Button>}>
{t('thread.loadFailed', { message: threadRead.failure })}
</Notice>
)}
{reviewForm}
<div className={css.body}>
{body}
{allFiles.length > 0 && <FileTreePane {...navigator} id={treeId} position={treePosition} onWidth={setTreeWidth} />}
{review !== null && data?.kind === 'change' && threadList.open && (
<ThreadList entries={placed.entries} files={allFiles} truncated={review.truncated} url={data.url}
filter={threadList.filter} choose={(filter) => { setThreadList(value => ({ ...value, filter })) }}
claim={threadList.claim} claimed={() => { setThreadList(value => ({ ...value, claim: false })) }}
open={(entry, covering) => {
// A list that covers the files closes and hands the focus to the thread it opens, which it would cover.
if (covering) setThreadList(value => ({ ...value, open: false }))
openThread(entry, covering)
}}
openLink={openLink} close={closeThreadList} t={t} />
)}
</div>
</div>
)
@@ -20,6 +20,8 @@ import { drawnLines, segmentsOf, splitRows, type DiffRow, type SplitCell, type S
import { codeSideAt, readCodeSelection } from './code-selection.ts'
import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts'
import { ReviewThread, useFileReview } from './ReviewThread.tsx'
import { OutdatedThreads, ThreadCard, type FileThreads, type LineThread, type ThreadActions } from './ReviewThreads.tsx'
import { gapOf } from './review-threads.ts'
import type { FileReviewState } from './review-queue.ts'
import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx'
import reviewCss from './ReviewComposer.module.css'
@@ -59,6 +61,8 @@ export interface DiffFileHandlers {
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
/** Show a file's next unresolved host thread in display order after the last one shown, or its first. */
readonly nextThread: (path: string) => void
/** Tells each expanded section when it comes within reach of the scrollport, which draws its lines. */
readonly reach: SectionReach
}
@@ -91,6 +95,10 @@ export interface DiffFileProps {
readonly tooltip: string
/** Whether the reader marked this change viewed, or marked an earlier change of the file. */
readonly viewed: ViewedState
/** Review threads of the file from the code host, or undefined while none are read; the view keeps their identity. */
readonly threads?: FileThreads | undefined
/** Whether the section draws its lines at once, as the target of a thread jump, whose card must exist to be centered. */
readonly drawNow?: boolean | undefined
/** Actions shared by every section of the view. */
readonly handlers: DiffFileHandlers
/** Forge panel copy. */
@@ -153,13 +161,28 @@ function Code({ text, spans, old, next }: {
}
/** Whether a side-by-side row repeats an unchanged line or shows a change. */
/** Whether two comments cover the same lines of the same side. */
function sameRange(a: ReviewSelection['comment'], b: ReviewSelection['comment']): boolean {
return a.side === b.side && a.startLine === b.startLine && a.endLine === b.endLine
}
/** Whether a selection covers one line of a side. */
function covers(item: ReviewSelection, side: 'L' | 'R', line: number): boolean {
return item.comment.side === side && line >= item.comment.startLine && line <= item.comment.endLine
}
/** The editor key of a range, such as `R3-4`. */
function rangeKey(item: ReviewSelection): string {
return `${item.comment.side}${item.comment.startLine}-${item.comment.endLine}`
}
function pairKind(pair: SplitRow): 'context' | 'change' {
return pair.left !== null && pair.left.kind === 'context' ? 'context' : 'change'
}
/** The hunks of one file with their collapsed and expanded unchanged lines. */
function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, t }: Pick<DiffFileProps,
'file' | 'text' | 'open' | 'handlers' | 'split' | 'wrap' | 'review' | 'visible' | 't'> & { readonly comments: FileReviewState }): ReactNode {
function Lines({ file, text, open, handlers, split, wrap, review, visible, comments, threads, t }: Pick<DiffFileProps,
'file' | 'text' | 'open' | 'handlers' | 'split' | 'wrap' | 'review' | 'visible' | 'threads' | 't'> & { 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
@@ -168,33 +191,53 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
const style: CSSProperties & { '--forge-number-width': string } = { '--forge-number-width': `calc(${Math.max(2, String(maximum).length)}ch + 12px)` }
const highlighter = useCodeHighlighter(languageForPath(file.path))
const [selection, setSelection] = useState<ReviewSelection | null>(null)
// Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range.
const chosen = useRef<ReviewSelection | null>(null)
const select = (next: ReviewSelection | null): void => {
chosen.current = next
setSelection(next)
}
// Comments being written, in the order they opened; each keeps the range it opened with while new ranges are chosen.
const [editors, setEditors] = useState<readonly ReviewSelection[]>([])
const root = useRef<HTMLDivElement>(null)
const origin = useRef<{ side: 'L' | 'R'; line: number } | null>(null)
// `add` is a gutter drag that began on a row's hover plus and opens the editor when the pointer is released.
const dragging = useRef<'gutter' | 'add' | 'text' | null>(null)
const [selecting, setSelecting] = useState(false)
const [editing, setEditing] = useState(false)
const [nativeSide, setNativeSide] = useState<'L' | 'R' | null>(null)
const nativeSelection = useCallback((): void => {
if (editing || nativeSide === null || root.current === null || review === undefined) return
if (nativeSide === null || root.current === null || review === undefined) return
const selected = readCodeSelection(root.current, nativeSide)
if (selected === undefined) {
chosen.current = null
setSelection(null)
setNativeSide(null)
return
}
const comment = selectReviewLines(file, selected.side, selected.from, selected.to)
setSelection(previous => comment === undefined ? null
: previous?.comment.side === comment.side && previous.comment.startLine === comment.startLine
&& previous.comment.endLine === comment.endLine
? previous : { source: review.source, comment })
}, [editing, nativeSide, review, file])
const previous = chosen.current
const next = comment === undefined ? null
: previous !== null && sameRange(previous.comment, comment) ? previous : { source: review.source, comment }
chosen.current = next
setSelection(next)
}, [nativeSide, review, file])
useEffect(() => {
if (nativeSide === null || editing) return
if (nativeSide === null) return
const changed = (): void => { if (dragging.current === null) nativeSelection() }
document.addEventListener('selectionchange', changed)
return () => { document.removeEventListener('selectionchange', changed) }
}, [nativeSide, editing, nativeSelection])
}, [nativeSide, nativeSelection])
/** Open an editor for a range, or focus the one already open for it, and clear the selection for the next range. */
const compose = (target: ReviewSelection): void => {
const open = root.current?.querySelector<HTMLTextAreaElement>(`[data-forge-comment="${rangeKey(target)}"] textarea`) ?? null
if (open !== null) open.focus()
else setEditors(list => [...list, target])
const native = window.getSelection()
if (root.current?.contains(native?.anchorNode ?? null) === true) native?.removeAllRanges()
select(null)
setNativeSide(null)
origin.current = null
}
useEffect(() => {
if (nativeSide === null) return
const copy = (event: ClipboardEvent): void => {
@@ -212,10 +255,10 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
if (!selecting) return
const finish = (event: PointerEvent): void => {
if (dragging.current === 'text') nativeSelection()
const compose = dragging.current === 'add' && event.type === 'pointerup'
const release = dragging.current === 'add' && event.type === 'pointerup' ? chosen.current : null
dragging.current = null
setSelecting(false)
if (compose) setEditing(true)
if (release !== null) compose(release)
}
window.addEventListener('pointerup', finish)
window.addEventListener('pointercancel', finish)
@@ -229,12 +272,13 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
: { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), [file, lines, open, highlighter])
// Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection.
const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => {
if (review === undefined || editing) return false
/* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */
if (review === undefined) return false
const from = extend && origin.current?.side === side ? origin.current.line : line
const comment = selectReviewLines(file, side, from, line)
if (comment === undefined) return false
if (!extend || origin.current?.side !== side) origin.current = { side, line }
setSelection({ source: review.source, comment })
select({ source: review.source, comment })
return true
}
// A drag that began on a hover plus extends through every row with a line on its starting side, wherever the pointer crosses that row.
@@ -244,8 +288,10 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
const line = from.side === 'L' ? old : next
if (line !== null) choose(from.side, line, true)
}
const selected = (side: 'L' | 'R', line: number | null): boolean => line !== null && selection !== null
&& selection.comment.side === side && line >= selection.comment.startLine && line <= selection.comment.endLine
const selected = (side: 'L' | 'R', line: number | null): boolean => line !== null && selection !== null && covers(selection, side, line)
// The browser paints a native text range itself; a gutter range and every open editor's range take the highlight.
const marked = (side: 'L' | 'R', line: number | null): boolean => line !== null
&& ((selected(side, line) && nativeSide === null) || editors.some(item => covers(item, side, line)))
// `hover` adds the mouse shortcut: a plus shown while a hovering pointer is over this side of the row.
const number = (side: 'L' | 'R', line: number | null, hover: boolean): ReactNode => {
if (line === null || review === undefined || !file.hunks.some((hunk) => {
@@ -254,13 +300,14 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
})) {
return <span className={css.number}>{line ?? ''}</span>
}
const plus = !selecting && !editing && selection?.comment.side === side && selection.comment.endLine === line
const plus = !selecting && selection !== null && selection.comment.side === side && selection.comment.endLine === line
? selection : null
return <span className={clsx(css.number, reviewCss.gutter)} data-review-side={side}
onPointerEnter={(event) => { if (dragging.current === 'gutter' && origin.current?.side === side && event.buttons === 1) choose(side, line, true) }}>
<button type="button" className={reviewCss.line}
aria-label={t('review.selectLine', { line: `${side}${line}` })} aria-pressed={selected(side, line)}
onPointerDown={(event) => {
if (event.button !== 0 || editing) return
if (event.button !== 0) return
event.preventDefault()
window.getSelection()?.removeAllRanges()
setNativeSide(null)
@@ -274,16 +321,16 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
setNativeSide(null)
choose(side, line, event.shiftKey)
}}>{line}</button>
{plus && (
{plus !== null && (
<Tooltip label={t('review.addComment')} portal>
<button type="button" className={reviewCss.add} aria-label={t('review.addComment')}
onPointerDown={(event) => { event.preventDefault() }} onClick={() => { setEditing(true) }}>
onPointerDown={(event) => { event.preventDefault() }} onClick={() => { compose(plus) }}>
<IconPlusOutlineRegular size={14} />
</button>
</Tooltip>
)}
{/* Keyboard and assistive technology reach the same editor through the line button and the labeled plus above. */}
{hover && !plus && !editing && (
{hover && plus === null && (
<span className={reviewCss.hoverAdd} aria-hidden="true" data-review-add={`${side}${line}`}
onPointerDown={(event) => {
if (event.button !== 0) return
@@ -302,33 +349,59 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
}
const cell = (value: SplitCell | null, spans: SideSpans, side: 'L' | 'R'): ReactNode => value === null
? <span className={clsx(css.cell, css.empty)} data-diff-side={side} />
: <span className={clsx(css.cell, css[value.kind], selected(side, value.no) && (editing || nativeSide === null) && reviewCss.selected)}
: <span className={clsx(css.cell, css[value.kind], marked(side, value.no) && reviewCss.selected)}
data-diff-side={side}>
{number(side, value.no, true)}<Code text={value.text} spans={spans?.get(value.no)} old={side === 'L' ? value.no : null} next={side === 'R' ? value.no : null} />
</span>
const rows: ReactNode[] = []
let inserted = false
const editor = review === undefined || selection === null || !editing ? null : <ReviewComposer key="comment" selection={selection} visible={visible} split={columns}
actions={review} close={() => {
const native = window.getSelection()
if (root.current?.contains(native?.anchorNode ?? null) === true) native?.removeAllRanges()
setSelection(null)
setEditing(false)
setNativeSide(null)
origin.current = null
}} t={t} />
const remaining = new Set(comments.threads)
const appendComments = (old: number | null, next: number | null): void => {
if (review === undefined) return
for (const thread of remaining) {
const comment = thread.selection.comment
if ((comment.side === 'L' ? old : next) !== comment.endLine || !reviewMatches(thread.selection, review.source, file)) continue
rows.push(<ReviewThread key={`record-${thread.key}`} thread={thread} actions={review} locked={comments.locked} outdated={false} split={columns} t={t} />)
remaining.delete(thread)
}
}
const endsAt = (old: number | null, next: number | null): boolean => selection !== null
&& (selection.comment.side === 'L' ? old : next) === selection.comment.endLine
const rows: ReactNode[] = []
const unplacedEditors = new Set(editors)
const remaining = new Set(comments.threads)
// A host thread follows the row of its last line, or the collapsed unchanged lines that hold it.
const unplaced = new Set(threads === undefined ? [] : threads.lines.map(item => ({ ...item, actions: threads.actions })))
const threadCard = (item: LineThread & { readonly actions: ThreadActions }): ReactNode =>
<ThreadCard key={`thread-${item.thread.id}`} thread={item.thread} place={item.place} actions={item.actions} t={t} />
// The editors, the saved comments, then the host threads whose ranges end on this side's line.
const commentsAt = (side: 'L' | 'R', line: number | null): ReactNode[] => {
const nodes: ReactNode[] = []
if (line === null) return nodes
if (review !== undefined) {
for (const item of unplacedEditors) {
if (item.comment.side !== side || item.comment.endLine !== line) continue
nodes.push(editorOf(item, review))
unplacedEditors.delete(item)
}
for (const thread of remaining) {
const comment = thread.selection.comment
if (comment.side !== side || comment.endLine !== line || !reviewMatches(thread.selection, review.source, file)) continue
nodes.push(<ReviewThread key={`record-${thread.key}`} thread={thread} actions={review} locked={comments.locked} outdated={false} t={t} />)
remaining.delete(thread)
}
}
for (const item of unplaced) {
if (item.place.side !== side || item.place.endLine !== line) continue
nodes.push(threadCard(item))
unplaced.delete(item)
}
return nodes
}
const editorOf = (item: ReviewSelection, actions: ReviewActions): ReactNode =>
<ReviewComposer key={`comment-${rangeKey(item)}`} selection={item} visible={visible} actions={actions}
close={() => { setEditors(list => list.filter(open => !sameRange(open.comment, item.comment))) }} t={t} />
// Side by side, a row's comments sit in a row of two cells under its columns, each continuing its line's background.
const notes = (key: string, pair: SplitRow): void => {
const left = commentsAt('L', pair.left?.no ?? null)
const right = commentsAt('R', pair.right?.no ?? null)
if (left.length === 0 && right.length === 0) return
const side = (value: SplitCell | null, nodes: ReactNode[]): ReactNode => (
<div className={clsx(css.noteCell, css[value?.kind ?? 'empty'])}>
<span className={css.number} />
<div className={css.noteStack} data-forge-comments="">{nodes}</div>
</div>
)
rows.push(<div key={key} className={css.notes} data-forge-notes="">{side(pair.left, left)}{side(pair.right, right)}</div>)
}
for (const [at, segment] of prepared.entries()) {
if (segment.kind === 'gap') {
rows.push(<button key={`gap-${segment.index}`} type="button" className={css.gap} disabled={text === 'loading'}
@@ -336,39 +409,40 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
<IconChevronsUpDownOutlineRegular size={12} />
{segment.count === null ? t('diff.unchangedRest') : t('diff.unchanged', { count: segment.count.toLocaleString('en-US') })}
</button>)
for (const item of unplaced) {
if (gapOf(file, item.place.side, item.place.endLine) !== segment.index) continue
rows.push(threadCard(item))
unplaced.delete(item)
}
} else if (columns) {
for (const [index, pair] of splitRows(segment.rows).entries()) {
rows.push(<div key={`${at}-${index}`} className={css.pair} data-diff-pair={pairKind(pair)}
onPointerEnter={(event) => { extendAdd(event.buttons, pair.left?.no ?? null, pair.right?.no ?? null) }}>
{cell(pair.left, segment.old, 'L')}{cell(pair.right, segment.new, 'R')}
</div>)
if (!inserted && endsAt(pair.left?.no ?? null, pair.right?.no ?? null)) {
rows.push(editor)
inserted = true
}
appendComments(pair.left?.no ?? null, pair.right?.no ?? null)
notes(`notes-${at}-${index}`, pair)
}
} else {
for (const [index, row] of segment.rows.entries()) {
// Both numbers place their plus in the sign column, so a row showing the labeled plus offers no hover plus.
const labeled = !selecting && !editing && endsAt(row.old, row.new)
rows.push(<div key={`${at}-${index}`} className={clsx(css.line, css[row.kind], (selected('L', row.old) || selected('R', row.new)) && (editing || nativeSide === null) && reviewCss.selected)} data-diff-line={row.kind}
const labeled = !selecting && endsAt(row.old, row.new)
rows.push(<div key={`${at}-${index}`} className={clsx(css.line, css[row.kind], (marked('L', row.old) || marked('R', row.new)) && reviewCss.selected)} data-diff-line={row.kind}
onPointerEnter={(event) => { extendAdd(event.buttons, row.old, row.new) }}>
{singleSide !== 'R' && number('L', row.old, row.kind === 'del' && !labeled)}{singleSide !== 'L' && number('R', row.new, row.kind !== 'del' && !labeled)}<span className={css.sign}>{SIGN[row.kind]}</span>
<Code text={row.text} old={row.old} next={row.new} spans={row.kind === 'del' ? segment.old?.get(row.old) : segment.new?.get(row.new)} />
</div>)
if (!inserted && endsAt(row.old, row.new)) {
rows.push(editor)
inserted = true
}
appendComments(row.old, row.new)
rows.push(...commentsAt('L', row.old), ...commentsAt('R', row.new))
}
}
}
if (review !== undefined) for (const thread of remaining) {
rows.push(<ReviewThread key={`record-${thread.key}`} thread={thread} actions={review} locked={comments.locked} outdated split={false} t={t} />)
if (review !== undefined) {
// An editor whose last line no longer draws, after a refresh or a narrower choice of commits, follows the lines.
for (const item of unplacedEditors) rows.push(editorOf(item, review))
for (const thread of remaining) {
rows.push(<ReviewThread key={`record-${thread.key}`} thread={thread} actions={review} locked={comments.locked} outdated t={t} />)
}
}
if (!inserted) rows.push(editor)
for (const item of unplaced) rows.push(threadCard(item))
return <div ref={root} className={css.code} style={style} data-single-side={singleSide ?? undefined} data-split={columns ? '' : undefined} data-wrap={wrap ? '' : undefined}
data-review={review === undefined ? undefined : ''}
data-native-side={nativeSide ?? undefined}
@@ -377,12 +451,11 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme
const side = codeSideAt(event.currentTarget, event.target)
if (side === undefined) return
if (!event.shiftKey || nativeSide !== side) window.getSelection()?.removeAllRanges()
if (!editing) dragging.current = 'text'
dragging.current = 'text'
// The chosen column must allow selection before the browser starts its native text range.
flushSync(() => {
setNativeSide(side)
if (editing) return
setSelection(null)
select(null)
setSelecting(true)
})
}}>{rows}</div>
@@ -393,26 +466,39 @@ function drawsLines(file: ForgeDiffFile, large: boolean, revealed: boolean): boo
return !file.binary && !file.oversized && file.hunks.length > 0 && (!large || revealed)
}
function Body(props: DiffFileProps): ReactNode {
const { file, large, revealed, handlers, review, t } = props
/** The file's lines or the note that replaces them, with its saved comments; host threads on lines follow when no lines show. */
function Content(props: DiffFileProps): ReactNode {
const { file, large, revealed, handlers, review, threads, t } = props
const comments = useFileReview(review, file.path)
const records = review === undefined ? null : comments.threads.map(thread => <ReviewThread key={thread.key} thread={thread}
actions={review} locked={comments.locked} outdated={!reviewMatches(thread.selection, review.source, file)} split={false} t={t} />)
if (file.binary) return <><p className={css.fileNote}>{t('diff.binary')}</p>{records}</>
if (file.oversized) return <><p className={css.fileNote}>{t('diff.fileTooLarge')}</p>{records}</>
if (file.hunks.length === 0) return records
actions={review} locked={comments.locked} outdated={!reviewMatches(thread.selection, review.source, file)} t={t} />)
const lineThreads = threads?.lines.map(item => <ThreadCard key={item.thread.id} thread={item.thread} place={item.place}
actions={threads.actions} t={t} />)
if (file.binary) return <><p className={css.fileNote}>{t('diff.binary')}</p>{records}{lineThreads}</>
if (file.oversized) return <><p className={css.fileNote}>{t('diff.fileTooLarge')}</p>{records}{lineThreads}</>
if (file.hunks.length === 0) return <>{records}{lineThreads}</>
if (large && !revealed) {
// A large file starts as one collapsed strip, drawn and opened like the collapsed unchanged lines.
return (
<><button type="button" className={css.gap} onClick={() => { handlers.reveal(file.path) }}>
<IconChevronsUpDownOutlineRegular size={12} />
{t('diff.largeCollapsed', { count: (file.additions + file.deletions).toLocaleString('en-US') })}
</button>{records}</>
</button>{records}{lineThreads}</>
)
}
return <Lines {...props} comments={comments} />
}
/** Host threads on the whole file, the lines, then the host threads that later commits made outdated. */
function Body(props: DiffFileProps): ReactNode {
const { threads, t } = props
return <>
{threads?.file.map(thread => <ThreadCard key={thread.id} thread={thread} place={{ kind: 'file' }} actions={threads.actions} t={t} />)}
<Content {...props} />
{threads !== undefined && <OutdatedThreads threads={threads.outdated} actions={threads.actions} t={t} />}
</>
}
/** File actions live only while their owning tab is visible. */
function FileMenu({ name, file, handlers, t }: {
readonly name: string
@@ -458,17 +544,19 @@ function FileMenu({ name, file, handlers, t }: {
}
/**
* 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.
* Render one file of a diff. Until the section first comes within reach of the scrollport or a thread jump targets it,
* 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.
*/
function DiffFileSection(props: DiffFileProps): ReactNode {
const { file, expanded, large, revealed, badge, tooltip, viewed, handlers, t } = props
const { file, expanded, large, revealed, badge, tooltip, viewed, threads, handlers, t } = props
const name = file.path.slice(file.path.lastIndexOf('/') + 1)
const element = useRef<HTMLElement | null>(null)
const [reached, setReached] = useState(false)
const waiting = expanded && !reached && drawsLines(file, large, revealed)
// A thread jump draws the section for good, so it does not fall back to the box once the jump ends.
if (props.drawNow === true && !reached) setReached(true)
const waiting = expanded && !reached && props.drawNow !== true && drawsLines(file, large, revealed)
useEffect(() => {
/* v8 ignore next -- React attaches the section before it runs effects */
if (!waiting || element.current === null) return
@@ -500,6 +588,15 @@ function DiffFileSection(props: DiffFileProps): ReactNode {
{viewed === 'changed' && (
<Tag tone="warning" className={css.changedTag}><span className={css.changedText}>{t('viewed.changed')}</span></Tag>
)}
{threads !== undefined && threads.unresolved > 0 && (
<Tooltip label={t('thread.next')} side="bottom">
<button type="button" className={css.threadCount} aria-label={t('thread.unresolvedAria', { name, count: threads.unresolved })}
onClick={() => { handlers.nextThread(file.path) }}>
<span className={css.threadCountText}>{t('thread.unresolvedCount', { count: threads.unresolved })}</span>
<span className={css.threadCountNumber}>{threads.unresolved}</span>
</button>
</Tooltip>
)}
<span className={css.fileSpacer} data-forge-path-spacer="" />
{badge !== '' && <span className={css.badge}>{badge}</span>}
</span>
@@ -2,7 +2,8 @@
.root, .thread { box-sizing: border-box; width: calc(100% - 20px); max-width: 680px; margin: 10px; padding: 12px; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); white-space: normal; }
.root { background: var(--dsw-alias-bg-layer-2); border-radius: var(--dsw-radius-lg); }
.root:focus-within { border-color: var(--dsw-alias-border-l4); }
.root[data-split][data-side="R"], .thread[data-split][data-side="R"] { margin-inline-start: clamp(10px, calc(100% - 700px), calc(50% + 10px)); }
/* Side by side, a comment fills its side's cell under the code instead of the row's width. */
[data-forge-comments] > .root, [data-forge-comments] > .thread { width: auto; max-width: none; margin: 0; }
.title { margin-bottom: 12px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
/* Fixed-size textarea layout stays local during typing; native resizing can still change its outer height. */
.input { display: block; box-sizing: border-box; width: 100%; height: 88px; min-height: 88px; contain: strict; padding: 10px 12px; resize: vertical; border: 0.5px solid var(--dsw-alias-border-l4); border-radius: var(--dsw-radius-md); outline: none; background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-primary); font: inherit; }
@@ -15,7 +15,7 @@ export interface ReviewActions {
readonly source: ReviewSource
/** Browser records shared by the changes tab. */
readonly records?: ReviewQueue
/** Whether another comment already started a pending review. */
/** Whether the signed-in user has a pending review on the code host that the next comment joins. */
readonly reviewStarted?: boolean
/** Open the confirmed publication URL. */
readonly openLink?: (url: string) => void
@@ -27,26 +27,32 @@ export interface ReviewActions {
readonly onQuoted?: (selection: ReviewSelection) => void
/** Publish one comment; an error string preserves the editor. */
readonly publish?: (selection: ReviewSelection) => Promise<string | undefined>
/** Keep one comment for the final review; false preserves the editor. */
readonly queue?: (selection: ReviewSelection) => boolean
/** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */
readonly queue?: (selection: ReviewSelection) => Promise<string | undefined>
}
function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocale<typeof NS> & {
/**
* Render a primary action with an optional second action in its menu.
* @param props - the main action, the optional menu action, the menu's name, and availability.
* @returns the split button.
*/
export function SplitAction({ disabled, label, run, menuLabel, menu, other }: {
readonly disabled: boolean
readonly busy: boolean
readonly started: boolean
readonly queue: () => void
readonly publish: (() => void) | undefined
readonly label: string
readonly run: () => void
/** Accessible name of the menu button. */
readonly menuLabel: string
/** Label of the action in the menu, or undefined without one. */
readonly other: string | undefined
readonly menu: () => void
}): ReactNode {
const [open, setOpen] = useState(false)
return <div className={css.gitAction}>
<Button size="sm" variant="primary" className={clsx(css.gitMain)} disabled={disabled} onClick={queue}>
{t(busy ? 'review.publishing' : started ? 'review.queue' : 'review.startReview')}
</Button>
{publish !== undefined && <Menu open={open && !disabled} portal dense align="end" autoFocus onClose={() => { setOpen(false) }}
<Button size="sm" variant="primary" className={clsx(other !== undefined && css.gitMain)} disabled={disabled} onClick={run}>{label}</Button>
{other !== undefined && <Menu open={open && !disabled} portal dense align="end" autoFocus onClose={() => { setOpen(false) }}
anchor={<Button size="sm" variant="primary" className={clsx(css.gitArrow)} disabled={disabled} aria-haspopup="menu" aria-expanded={open && !disabled}
aria-label={t('review.githubActions')} onClick={() => { setOpen(value => !value) }}><IconChevronDownOutlineRegular size={14} /></Button>}>
<MenuItemButton onSelect={() => { setOpen(false); publish() }}>{t('review.publish')}</MenuItemButton>
aria-label={menuLabel} onClick={() => { setOpen(value => !value) }}><IconChevronDownOutlineRegular size={14} /></Button>}>
<MenuItemButton onSelect={() => { setOpen(false); menu() }}>{other}</MenuItemButton>
</Menu>}
</div>
}
@@ -56,9 +62,8 @@ function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocal
* @param props - frozen selection, actions, cancellation, and localized copy.
* @returns the inline comment form.
*/
export function ReviewComposer({ selection, actions, close, visible = true, split = false, t }: PropsLocale<typeof NS> & {
export function ReviewComposer({ selection, actions, close, visible = true, t }: PropsLocale<typeof NS> & {
readonly visible?: boolean
readonly split?: boolean
readonly selection: ReviewSelection
readonly actions: ReviewActions
readonly close: () => void
@@ -73,13 +78,14 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli
useEffect(() => { input.current?.focus() }, [])
const comment = (): ReviewSelection => ({ ...selection, comment: { ...selection.comment, body: body.current } })
const range = reviewRange(selection.comment)
const publish = async (): Promise<void> => {
if (running.current || actions.publish === undefined) return
/** Send the comment to the code host, closing the form once it is taken and keeping its text otherwise. */
const send = async (destination: ((selection: ReviewSelection) => Promise<string | undefined>) | undefined): Promise<void> => {
if (running.current || destination === undefined) return
running.current = true
setBusy(true)
setError(null)
try {
const failure = await actions.publish(comment())
const failure = await destination(comment())
if (failure === undefined) close()
else setError(failure)
} catch (_error) {
@@ -90,7 +96,8 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli
}
}
return (
<section className={css.root} data-side={selection.comment.side} data-split={split ? '' : undefined} aria-label={t('review.range', { range })} data-forge-comment="">
<section className={css.root} aria-label={t('review.range', { range })}
data-forge-comment={`${selection.comment.side}${selection.comment.startLine}-${selection.comment.endLine}`}>
<div className={css.title}>{t('review.range', { range })}</div>
<textarea ref={input} className={css.input} rows={3} defaultValue={selection.comment.body} disabled={busy}
aria-label={t('review.comment')} placeholder={t('review.comment')}
@@ -108,14 +115,12 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli
if (actions.addToInput(selected)) { actions.onQuoted?.(selected); close() }
else setError(t('review.inputFailed'))
}}>{t('review.addToInput')}</Button>
{visible && actions.queue !== undefined && <GitHubAction
disabled={busy || actions.publishingBlocked === true || empty} busy={busy} started={actions.reviewStarted === true}
queue={() => {
if (actions.queue?.(comment()) === true) close()
else setError(t('review.saveFailed'))
}} publish={actions.publish === undefined ? undefined : () => { void publish() }} t={t} />}
{visible && actions.queue !== undefined && <SplitAction disabled={busy || actions.publishingBlocked === true || empty}
label={t(busy ? 'review.publishing' : actions.reviewStarted === true ? 'review.queue' : 'review.startReview')}
run={() => { void send(actions.queue) }} menuLabel={t('review.githubActions')}
other={actions.publish === undefined ? undefined : t('review.publish')} menu={() => { void send(actions.publish) }} />}
{actions.queue === undefined && actions.publish !== undefined && <Button size="sm" variant="primary"
disabled={busy || actions.publishingBlocked === true || empty} onClick={() => { void publish() }}>{t('review.publish')}</Button>}
disabled={busy || actions.publishingBlocked === true || empty} onClick={() => { void send(actions.publish) }}>{t('review.publish')}</Button>}
</div>
</section>
@@ -1,6 +1,7 @@
/* Review controls of the changes toolbar. The lens draws the segmented track and raised indicator of the shared
segmented control at the toolbar's 28px control height and 12px text, with each segment's file count after its label. */
.lens {
/* Review controls of the changes toolbar. The segmented radio group of the lens and the thread list's filter draws the
track and raised indicator of the shared segmented control at the toolbar's 28px control height and 12px text, with
each segment's count after its label. */
.segmented {
box-sizing: border-box;
display: grid;
grid-auto-columns: minmax(0, 1fr);
@@ -145,3 +146,37 @@
corner-shape: round;
background: var(--dsw-alias-state-success-primary);
}
.progressForm {
display: inline-flex;
align-items: center;
gap: 8px;
}
/* A narrow toolbar shows this form in place of the label and bar. */
.progressForm[data-forge-progress='compact'] {
display: none;
gap: 6px;
}
/* The ring starts at twelve o’clock and fills clockwise with the viewed share. */
.ring {
flex: none;
width: 14px;
height: 14px;
transform: rotate(-90deg);
}
.ringTrack,
.ringFill {
fill: none;
stroke-width: 2px;
}
.ringTrack {
stroke: var(--dsw-alias-border-l3);
}
.ringFill {
stroke: var(--dsw-alias-state-success-primary);
}
@@ -1,7 +1,7 @@
/**
* Review controls of the changes toolbar: the lens that keeps the files of one review layer, as a full-width
* radio group above the file tree or as a menu where no tree shows; the switch that hides test files; and the
* share of shown files the reader marked viewed.
* share of shown files the reader marked viewed. The thread list shares the segmented radio group.
*/
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
@@ -33,17 +33,35 @@ export interface LensProps extends PropsLocale<typeof NS> {
readonly choose: (lens: ChangesLens) => void
}
/** One segment of a {@link SegmentedChoice}. */
export interface Segment<Value extends string> {
/** Value the segment chooses. */
readonly value: Value
/** Localized label. */
readonly label: string
/** Count shown after the label, or null for none. */
readonly count: number | null
/** Localized hover text of a disabled segment, or null for an enabled one. */
readonly disabledTip: string | null
}
/**
* Render the lens as a radio group whose segments share its width; arrow keys, Home, and End move between enabled lenses.
* @param props - the lens, its counts, whether test files hide, the choose action, and copy.
* Render a radio group whose segments share its width, each with a count after its label; arrow keys, Home, and End
* move between enabled segments.
* @param props - the segments, the chosen value, the choose action, and the group's localized accessible name.
* @returns the radio group.
*/
export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): ReactNode {
export function SegmentedChoice<Value extends string>({ segments, value, choose, label }: {
readonly segments: readonly Segment<Value>[]
readonly value: Value
readonly choose: (value: Value) => void
readonly label: string
}): ReactNode {
const group = useRef<HTMLDivElement>(null)
const enabled = LENSES.filter(item => item !== 'test' || !hideTests)
const enabled = segments.filter(segment => segment.disabledTip === null).map(segment => segment.value)
const move = (event: KeyboardEvent<HTMLButtonElement>): void => {
const at = enabled.indexOf(lens)
let next: ChangesLens | undefined
const at = enabled.indexOf(value)
let next: Value | undefined
switch (event.key) {
case 'ArrowLeft': case 'ArrowUp': next = enabled[(at + enabled.length - 1) % enabled.length]; break
case 'ArrowRight': case 'ArrowDown': next = enabled[(at + 1) % enabled.length]; break
@@ -53,28 +71,40 @@ export function LensControl({ lens, counts, hideTests, choose, t }: LensProps):
}
event.preventDefault()
event.stopPropagation()
/* v8 ignore next -- at most the test lens is disabled, so every key lands on an enabled lens */
/* v8 ignore next -- every caller keeps a segment enabled, so every key lands on one */
if (next === undefined) return
choose(next)
group.current?.querySelector<HTMLButtonElement>(`[data-forge-lens="${next}"]`)?.focus()
group.current?.querySelector<HTMLButtonElement>(`[data-segment="${next}"]`)?.focus()
}
return (
<div ref={group} role="radiogroup" aria-label={t('lens.aria')} className={css.lens}>
{LENSES.map((item) => {
const disabled = item === 'test' && hideTests
<div ref={group} role="radiogroup" aria-label={label} className={css.segmented}>
{segments.map((segment) => {
const button = (
<button key={item} type="button" role="radio" className={css.segment} aria-checked={lens === item} disabled={disabled}
tabIndex={lens === item ? 0 : -1} data-forge-lens={item} onKeyDown={move} onClick={() => { choose(item) }}>
<span className={css.segmentLabel}>{t(LENS_LABEL[item])}</span>
<span className={css.count}>{disabled ? '' : counts[item]}</span>
<button key={segment.value} type="button" role="radio" className={css.segment} aria-checked={value === segment.value}
disabled={segment.disabledTip !== null} tabIndex={value === segment.value ? 0 : -1} data-segment={segment.value}
onKeyDown={move} onClick={() => { choose(segment.value) }}>
<span className={css.segmentLabel}>{segment.label}</span>
<span className={css.count}>{segment.count ?? ''}</span>
</button>
)
return disabled ? <Tooltip key={item} label={t('lens.testHidden')} side="bottom">{button}</Tooltip> : button
return segment.disabledTip === null ? button : <Tooltip key={segment.value} label={segment.disabledTip} side="bottom">{button}</Tooltip>
})}
</div>
)
}
/**
* Render the lens as a radio group whose segments share its width.
* @param props - the lens, its counts, whether test files hide, the choose action, and copy.
* @returns the radio group.
*/
export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): ReactNode {
// A disabled lens shows no count, since hidden test files are not counted.
return <SegmentedChoice label={t('lens.aria')} value={lens} choose={choose} segments={LENSES.map(item => item === 'test' && hideTests
? { value: item, label: t(LENS_LABEL[item]), count: null, disabledTip: t('lens.testHidden') }
: { value: item, label: t(LENS_LABEL[item]), count: counts[item], disabledTip: null })} />
}
/**
* Render the lens as a menu button, for a toolbar without the file tree beside it.
* @param props - the lens, its counts, whether test files hide, the choose action, copy, and whether the owning tab is visible.
@@ -129,8 +159,12 @@ export function HideTestsSwitch({ hidden, toggle, t }: PropsLocale<typeof NS> &
)
}
/** Radius of the compact progress ring, inside its 14px box with a 2px stroke. */
const RING_RADIUS = 5.5
/**
* Render how many of the shown files the reader marked viewed, as a count and a bar.
* Render how many of the shown files the reader marked viewed: a label with a bar, and a ring with the bare count that a
* narrow toolbar shows instead (`data-forge-progress` names each form for the toolbar's styles).
* @param props - the viewed and shown file counts, and copy.
* @returns the progress, or nothing without shown files.
*/
@@ -139,13 +173,25 @@ export function ViewedProgress({ viewed, total, t }: PropsLocale<typeof NS> & {
readonly total: number
}): ReactNode {
if (total === 0) return null
const label = t('viewed.progress', { viewed: String(viewed), total: String(total) })
const counts = { viewed: String(viewed), total: String(total) }
const label = t('viewed.progress', counts)
const circumference = 2 * Math.PI * RING_RADIUS
return (
<span className={css.progress} role="progressbar" aria-label={t('viewed.progressAria')} aria-valuemin={0} aria-valuemax={total}
aria-valuenow={viewed} aria-valuetext={label} data-forge-viewed-progress={`${viewed}/${total}`}>
<span className={css.progressLabel}>{label}</span>
<span className={css.bar} aria-hidden="true">
<span className={css.fill} style={{ width: `${(viewed / total) * 100}%` }} />
<span className={css.progressForm} data-forge-progress="full">
<span className={css.progressLabel}>{label}</span>
<span className={css.bar} aria-hidden="true">
<span className={css.fill} style={{ width: `${(viewed / total) * 100}%` }} />
</span>
</span>
<span className={css.progressForm} data-forge-progress="compact">
<svg className={css.ring} viewBox="0 0 14 14" aria-hidden="true">
<circle className={css.ringTrack} cx="7" cy="7" r={RING_RADIUS} />
<circle className={css.ringFill} cx="7" cy="7" r={RING_RADIUS}
strokeDasharray={`${(viewed / total) * circumference} ${circumference}`} />
</svg>
{t('viewed.count', counts)}
</span>
</span>
)
@@ -1,4 +1,4 @@
/** Inline comment records and editing of a pending review at its captured code location. */
/** Inline comment records and the editing of comment drafts kept in the browser at their captured code location. */
import { useCallback, useState, useSyncExternalStore, type ReactNode } from 'react'
import { Button, Tag } from '@deepseek-ai/dsh-client-ui-primitives'
@@ -24,27 +24,42 @@ export function useFileReview(actions: ReviewActions | undefined, path: string):
}
/**
* Render a saved comment at its line, with pending edits kept in the browser queue.
* Render a saved comment at its line. A comment draft kept in the browser can be edited, deleted, or moved into the
* pending review on the code host.
* @param props - record, edit availability, source actions, and localized copy.
* @returns one compact inline comment card.
*/
export function ReviewThread({ thread, actions, locked, outdated, split, t }: PropsLocale<typeof NS> & {
export function ReviewThread({ thread, actions, locked, outdated, t }: PropsLocale<typeof NS> & {
readonly thread: Thread
readonly actions: ReviewActions
readonly locked: boolean
readonly outdated: boolean
readonly split: boolean
}): ReactNode {
const [editing, setEditing] = useState(false)
const [body, setBody] = useState(thread.selection.comment.body)
const [error, setError] = useState<string | null>(null)
const [moving, setMoving] = useState(false)
const comment = thread.selection.comment
const quoted = editing && thread.kind === 'pending' ? { ...thread.selection, comment: { ...comment, body } } : thread.selection
const range = reviewRange(comment)
const status = thread.kind === 'pending' ? 'review.pending' : thread.kind === 'published' ? 'review.published' : 'review.quoted'
const status = thread.kind === 'pending' ? 'review.browserDraft' : thread.kind === 'published' ? 'review.published' : 'review.quoted'
const save = (): boolean => actions.records?.editThread(thread.key, body) === true
return <section className={css.thread} data-forge-review-thread={thread.kind} data-side={comment.side}
data-split={split ? '' : undefined} aria-label={t('review.range', { range })}>
const queue = actions.queue
/** Add the draft to the pending review on the code host, then delete it from the browser. */
const move = async (add: NonNullable<ReviewActions['queue']>): Promise<void> => {
setMoving(true)
setError(null)
try {
const failure = await add(thread.selection)
if (failure !== undefined) setError(failure)
else if (actions.records?.editThread(thread.key, null) !== true) setError(t('review.saveFailed'))
} catch (_error) {
setError(t('review.unknown'))
} finally {
setMoving(false)
}
}
return <section className={css.thread} data-forge-review-thread={thread.kind} data-side={comment.side} aria-label={t('review.range', { range })}>
<div className={css.threadHeader}>
<span className={css.author}>{t('review.yourComment')}</span>
<span className={css.range}>{range}</span>
@@ -65,13 +80,15 @@ export function ReviewThread({ thread, actions, locked, outdated, split, t }: Pr
}}>{t('review.addToInput')}</Button>
{thread.kind === 'pending' && <>
{editing
? <Button size="sm" disabled={locked || body.trim() === ''} onClick={() => {
? <Button size="sm" disabled={locked || moving || body.trim() === ''} onClick={() => {
if (save()) { setEditing(false); setError(null) } else setError(t('review.saveFailed'))
}}>{t('review.done')}</Button>
: <Button size="sm" disabled={locked} onClick={() => { setBody(comment.body); setEditing(true) }}>{t('review.edit')}</Button>}
<Button size="sm" disabled={locked} onClick={() => {
: <Button size="sm" disabled={locked || moving} onClick={() => { setBody(comment.body); setEditing(true) }}>{t('review.edit')}</Button>}
<Button size="sm" disabled={locked || moving} onClick={() => {
if (actions.records?.editThread(thread.key, null) !== true) setError(t('review.saveFailed'))
}}>{t('review.remove')}</Button>
{queue !== undefined && !editing && !outdated && <Button size="sm" disabled={locked || moving}
onClick={() => { void move(queue) }}>{t(moving ? 'review.publishing' : 'review.queue')}</Button>}
</>}
{thread.kind === 'published' && actions.openLink !== undefined && <Button size="sm" onClick={() => { actions.openLink?.(thread.url) }}>{t('review.recheck')}</Button>}
</div>
@@ -0,0 +1,326 @@
/* Review thread cards share the inline review form's card material; comment rows follow the conversation's 13px detail size. */
.card,
.folded {
box-sizing: border-box;
width: calc(100% - 20px);
max-width: 720px;
margin: 10px;
border: 0.5px solid var(--dsw-alias-border-l3);
border-radius: var(--dsw-radius-md);
background: var(--dsw-alias-bg-layer-1);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xs-13);
font-family: Inter, var(--dsw-font-family);
white-space: normal;
}
.card { padding: 10px 12px; }
/* A card a jump from a covering thread list focused; a pointer jump shows no ring. */
.card:focus { outline: none; }
.card:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -1px;
}
/* Side by side, a card fills its side's cell under the code instead of the row's width. */
[data-forge-comments] > .card,
[data-forge-comments] > .folded {
width: auto;
max-width: none;
margin: 0;
}
.card[data-resolved] {
/* An elevated surface: the excerpt and the file at that commit scroll inside it, so the thumb takes the l2 pair,
which inherits down to them (see ui-theme styles/scrollbar.css for the rebinding contract). */
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
background: var(--dsw-alias-bg-layer-2);
}
.folded {
display: flex;
align-items: center;
gap: 6px;
min-height: 32px;
padding: 4px 12px;
color: var(--dsw-alias-label-secondary);
}
.folded > svg { flex: none; color: var(--dsw-alias-state-success-primary); }
.foldedText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.header {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
margin-bottom: 8px;
}
.place {
min-width: 0;
color: var(--dsw-alias-label-secondary);
font-size: 12px;
overflow-wrap: anywhere;
}
.spacer { flex: 1; }
/* Text actions inside a card: no fill, accent ink, the same height as the tags beside them. */
.link {
display: inline-flex;
flex: none;
align-items: center;
gap: 2px;
padding: 0;
border: 0;
background: transparent;
color: var(--dsw-alias-state-business-primary);
font: inherit;
font-size: 12px;
cursor: pointer;
}
.link:disabled { color: var(--dsw-alias-label-dimmed); cursor: default; }
.link:focus-visible {
border-radius: var(--dsw-radius-xs);
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: 2px;
}
@media (hover: hover) {
.link:not(:disabled):hover { text-decoration: underline; }
}
.turned { transform: rotate(-90deg); }
.comments {
display: flex;
flex-direction: column;
gap: 12px;
}
.comment {
display: flex;
gap: 8px;
min-width: 0;
}
.avatar {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: 50%;
corner-shape: round;
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-secondary);
font-weight: 500;
line-height: 1;
user-select: none;
}
.avatar img {
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
corner-shape: round;
object-fit: cover;
}
.commentMain {
flex: 1;
min-width: 0;
}
.commentHeader {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
min-height: 20px;
}
.login { font-weight: 500; overflow-wrap: anywhere; }
.time { color: var(--dsw-alias-label-tertiary); font-size: 12px; }
.body {
min-width: 0;
margin-top: 2px;
overflow-wrap: anywhere;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin: 10px -8px -4px;
}
/* A reply or a comment edit uses the inline review form's field; its actions sit under it like the form's. */
.form { margin-top: 10px; }
.formActions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 8px;
margin-top: 8px;
}
/* The collapsed reply field, a field-shaped button that opens the reply form. */
.replyPrompt {
display: block;
box-sizing: border-box;
width: 100%;
min-height: 32px;
margin-top: 10px;
padding: 6px 12px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: var(--dsw-radius-md);
background: var(--dsw-alias-bg-layer-3);
color: var(--dsw-alias-label-dimmed);
font: inherit;
text-align: start;
cursor: text;
}
.replyPrompt:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: 2px;
}
.menuAnchor { display: inline-flex; flex: none; }
/* The comment menu's icon button keeps the 20px row height of the header it ends. */
.icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: 0;
border-radius: var(--dsw-radius-xs);
background: transparent;
color: var(--dsw-alias-label-secondary);
cursor: pointer;
}
.icon[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
.icon:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: 1px;
}
@media (hover: hover) {
.icon:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
}
/* Confirming a deletion replaces nothing: the comment stays readable above the question. */
.confirm {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 8px;
}
.confirmText { flex: 1 1 auto; min-width: 0; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
.confirmError,
.actionError { flex-basis: 100%; margin-top: 0; }
.actionError { padding-inline: 8px; }
/* The end of the recorded hunk, drawn like the diff rows it came from. */
.excerpt,
.original {
margin-bottom: 10px;
overflow-x: auto;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-sm);
font: var(--dsw-font-markdown-code-block);
}
.excerptLine,
.originalLine {
min-height: 20px;
padding: 0 10px;
line-height: 20px;
white-space: pre;
}
.excerptHeader { color: var(--dsw-alias-label-tertiary); }
.added { background: var(--dsw-alias-file-diff-added-bg); }
.deleted { background: var(--dsw-alias-file-diff-deleted-bg); }
.original {
max-height: 320px;
overflow: auto;
}
.originalLine {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 12px;
}
.originalNumber {
min-width: 3ch;
color: var(--dsw-alias-label-tertiary);
text-align: right;
user-select: none;
}
.marked { background: var(--dsw-alias-interactive-bg-hover); }
.originalNote {
padding: 8px 10px;
color: var(--dsw-alias-label-secondary);
font-family: Inter, var(--dsw-font-family);
}
/* Outdated threads of one file, after its lines. */
.outdated {
border-top: 0.5px solid var(--dsw-alias-border-l3);
padding-bottom: 2px;
}
.outdatedHeader {
display: flex;
align-items: center;
gap: 6px;
min-height: 32px;
padding: 0 12px;
color: var(--dsw-alias-label-secondary);
font: var(--dsw-font-xs-13);
font-family: Inter, var(--dsw-font-family);
}
/* A changes view narrower than 480px gives the code more width; the query names no container, since CSS Modules rename
a container name per file, and the nearest inline-size container is the changes view. */
@container (max-width: 479px) {
.card,
.folded {
width: calc(100% - 12px);
margin: 6px;
}
}
@@ -0,0 +1,443 @@
/**
* Review threads of a change request inside the changes view: a thread card at its lines or at the top of its file, a
* resolved thread folded into one row, and the outdated threads of a file in a section after its lines. A card offers
* the writes the signed-in user may make: a reply, published at once or added to the pending review, resolving or
* unresolving the thread, and editing or deleting the user's own comments.
*/
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
import {
Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEllipsisOutlineRegular, IconRightUpOutlineRegular, MarkdownText,
Menu, Tag, Tooltip, type MarkdownLabels,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { ForgeReviewComment, ForgeReviewThread, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { formatAgo } from './format.ts'
import { anchorRange, hunkExcerpt, type ThreadPlace } from './review-threads.ts'
import { SplitAction } from './ReviewComposer.tsx'
import type { NS } from './locales.ts'
import css from './ReviewThreads.module.css'
import composerCss from './ReviewComposer.module.css'
type Translate = PropsLocale<typeof NS>['t']
/** Each member of a union without its `headSha`. */
type WithoutHead<T> = T extends unknown ? Omit<T, 'headSha'> : never
/** A write to one thread or its comments, without the head commit the changes view adds. */
export type ThreadWrite = WithoutHead<Extract<ForgeReviewWrite, { readonly kind: 'reply' | 'resolve' | 'edit-comment' | 'delete-comment' }>>
/** Writes the signed-in user can make to the threads of one changes view. */
export interface ThreadWrites {
/** Send a write; resolves to the message to show, or undefined once the code host took it. */
readonly write: (write: ThreadWrite) => Promise<string | undefined>
/** Whether the user has a pending review, which every reply then joins. */
readonly reviewStarted: boolean
/** Whether the user can add a reply to a pending review, starting one when needed. */
readonly canReview: boolean
}
/** Reads, actions, and identities every thread card of one changes view shares. */
export interface ThreadActions {
/** Login of the change request's author, or null when the host hides it. */
readonly author: string | null
/** Quote the whole thread in the main input without sending it; false when the input refused it. */
readonly addToInput: (thread: ForgeReviewThread, range: string | null) => boolean
/** Open a URL outside the app. */
readonly openLink: (url: string) => void
/** Read a file of the change request's repository at a commit. */
readonly readText: (commit: string, path: string) => Promise<RemoteResult<string>>
/** Report that the input refused a thread. */
readonly inputFailed: () => void
/** The latest jump to a thread, which unfolds that thread and its section until the reader folds them again; null before any. */
readonly focused: ThreadFocus | null
/** Writes the user can make, or null when the code host takes none from this view. */
readonly writes: ThreadWrites | null
}
/** One jump to a thread; each jump has its own revision, so a jump to the same thread unfolds it again. */
export interface ThreadFocus {
readonly id: ForgeThreadId
readonly revision: number
}
/** A host thread shown on lines of one side. */
export interface LineThread {
readonly thread: ForgeReviewThread
readonly place: Extract<ThreadPlace, { readonly kind: 'line' }>
}
/** Host threads of one file and the actions their cards share. */
export interface FileThreads {
/** Threads on lines, which follow the row of their last line. */
readonly lines: readonly LineThread[]
/** Threads on the whole file, shown above its lines. */
readonly file: readonly ForgeReviewThread[]
/** Threads no longer on the head's lines, shown after them. */
readonly outdated: readonly ForgeReviewThread[]
/** Unresolved threads of the file in every place, including threads the chosen commits do not show. */
readonly unresolved: number
/** Reads, actions, and identities shared by the cards. */
readonly actions: ThreadActions
}
/** The commit a thread was written on, abbreviated, or null for a file thread. */
function writtenOn(thread: ForgeReviewThread): string | null {
return thread.original === null ? null : thread.original.commit.slice(0, 7)
}
/**
* Build the Markdown chrome copy of comment bodies.
* @param t - forge panel copy.
* @returns labels for code fences and footnotes.
*/
export function useMarkdownLabels(t: Translate): MarkdownLabels {
return useMemo(() => ({
code: { copyLabel: t('thread.copy'), copiedLabel: t('thread.copied'),
toolbarLabels: { codeLabel: t('thread.codeBlock'), wrapLabel: t('thread.wrap'), unwrapLabel: t('thread.unwrap') } },
footnotes: t('thread.footnotes'),
}), [t])
}
/**
* Render an author's avatar, or the first letter of the login when the image is missing or fails.
* @param props - the comment's author and the avatar size.
* @returns the round avatar.
*/
export function Avatar({ author, size = 20 }: { readonly author: ForgeReviewComment['author']; readonly size?: number }): ReactNode {
const [failed, setFailed] = useState(false)
const login = author?.login ?? '?'
return <span className={css.avatar} style={{ width: size, height: size, fontSize: Math.round(size * 0.45) }} aria-hidden="true">
{author?.avatarUrl != null && !failed
? <img src={author.avatarUrl} alt="" width={size} height={size} referrerPolicy="no-referrer" onError={() => { setFailed(true) }} />
: login.slice(0, 1).toUpperCase()}
</span>
}
/** Run one write at a time for a card section, keeping its error until the next attempt. */
function useWriting(t: Translate): {
readonly busy: boolean
readonly error: string | null
readonly run: (send: () => Promise<string | undefined>) => Promise<boolean>
} {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const running = useRef(false)
const run = async (send: () => Promise<string | undefined>): Promise<boolean> => {
if (running.current) return false
running.current = true
setBusy(true)
setError(null)
try {
const failure = await send()
setError(failure ?? null)
return failure === undefined
} catch (_error) {
setError(t('thread.writeUnknown'))
return false
} finally {
running.current = false
setBusy(false)
}
}
return { busy, error, run }
}
/** A plain-text field with Cancel and the actions that send it, for a reply or a comment edit. */
function TextForm({ label, initial, busy, error, cancel, children }: {
readonly label: string
readonly initial: string
readonly busy: boolean
readonly error: string | null
readonly cancel: { readonly label: string; readonly run: () => void }
/** The sending actions, given the current text and whether it is blank. */
readonly children: (text: string, blank: boolean) => ReactNode
}): ReactNode {
const [text, setText] = useState(initial)
return <div className={css.form}>
<textarea autoFocus className={composerCss.input} rows={3} value={text} disabled={busy} aria-label={label} placeholder={label}
onChange={(event) => { setText(event.target.value) }} />
{error !== null && <div className={composerCss.error} role="alert">{error}</div>}
<div className={css.formActions}>
<Button size="sm" className={clsx(composerCss.cancel)} disabled={busy} onClick={cancel.run}>{cancel.label}</Button>
{children(text, text.trim() === '')}
</div>
</div>
}
/** Tells the card which of its forms hold text the reader is writing, so it does not fold them away. */
type Drafting = (form: string, active: boolean) => void
function Comment({ comment, last, actions, labels, now, drafting, t }: {
readonly comment: ForgeReviewComment
readonly drafting: Drafting
/** Whether the comment is the only one of its thread, so deleting it deletes the thread. */
readonly last: boolean
readonly actions: ThreadActions
readonly labels: MarkdownLabels
readonly now: number
readonly t: Translate
}): ReactNode {
const [mode, setMode] = useState<'view' | 'edit' | 'delete'>('view')
useEffect(() => {
drafting(comment.id, mode === 'edit')
return () => { drafting(comment.id, false) }
}, [drafting, comment.id, mode])
const [menu, setMenu] = useState(false)
const writing = useWriting(t)
const writes = actions.writes
const login = comment.author?.login ?? null
const editable = writes !== null && comment.viewerCanEdit
const deletable = writes !== null && comment.viewerCanDelete
const menuLabel = t('thread.commentActions', { author: login ?? t('thread.deletedAuthor') })
const send = async (write: ThreadWrite): Promise<void> => {
if (writes !== null && await writing.run(() => writes.write(write))) setMode('view')
}
return <div className={css.comment} data-forge-thread-comment={comment.id}>
<Avatar author={comment.author} />
<div className={css.commentMain}>
<div className={css.commentHeader}>
<span className={css.login}>{login ?? t('thread.deletedAuthor')}</span>
<span className={css.time} title={comment.createdAt}>{formatAgo(comment.createdAt, now, t) ?? comment.createdAt}</span>
{login !== null && login === actions.author && <Tag tone="outline">{t('thread.author')}</Tag>}
{comment.author?.bot === true && <Tag tone="outline">{t('thread.bot')}</Tag>}
{comment.pending && <Tag tone="warning">{t('review.pending')}</Tag>}
{(editable || deletable) && mode === 'view' && <>
<span className={css.spacer} />
<Menu open={menu} portal dense align="end" autoFocus onClose={() => { setMenu(false) }}
items={[...editable ? [{ id: 'edit', label: t('review.edit') }] : [], ...deletable ? [{ id: 'delete', label: t('review.remove') }] : []]}
onSelect={(id) => { setMenu(false); setMode(id === 'edit' ? 'edit' : 'delete') }}
anchor={<span className={css.menuAnchor}><Tooltip label={menuLabel} side="bottom">
<button type="button" className={css.icon} aria-label={menuLabel} aria-haspopup="menu" aria-expanded={menu}
onClick={() => { setMenu(value => !value) }}><IconEllipsisOutlineRegular size={14} /></button>
</Tooltip></span>} />
</>}
</div>
{mode === 'edit'
? <TextForm label={t('thread.editAria')} initial={comment.body} busy={writing.busy} error={writing.error}
cancel={{ label: t('review.cancel'), run: () => { setMode('view') } }}>
{(text, blank) => <Button size="sm" variant="primary" disabled={writing.busy || blank || text === comment.body}
onClick={() => { void send({ kind: 'edit-comment', comment: comment.id, body: text }) }}>
{t(writing.busy ? 'thread.saving' : 'thread.save')}
</Button>}
</TextForm>
// Raw HTML renders nothing, as GitHub hides comments and unknown tags, and never enters the DOM.
: <div className={css.body}><MarkdownText text={comment.body} labels={labels} variant="body" omitHtml /></div>}
{mode === 'delete' && <div className={css.confirm} role="group" aria-label={t(last ? 'thread.deleteLast' : 'thread.deleteConfirm')}>
<span className={css.confirmText}>{t(last ? 'thread.deleteLast' : 'thread.deleteConfirm')}</span>
<Button size="sm" disabled={writing.busy} onClick={() => { setMode('view') }}>{t('review.cancel')}</Button>
<Button size="sm" variant="primary" disabled={writing.busy} onClick={() => { void send({ kind: 'delete-comment', comment: comment.id }) }}>
{t(writing.busy ? 'thread.deleting' : 'review.remove')}
</Button>
{writing.error !== null && <div className={clsx(composerCss.error, css.confirmError)} role="alert">{writing.error}</div>}
</div>}
</div>
</div>
}
/**
* The reply field of a thread. Without a pending review it replies at once, and its menu starts one with the reply; with
* one, it adds the reply to it, since GitHub adds every reply of the user to the pending review.
*/
function Reply({ thread, writes, drafting, t }: PropsLocale<typeof NS> & {
readonly thread: ForgeReviewThread
readonly writes: ThreadWrites
readonly drafting: Drafting
}): ReactNode {
const [open, setOpen] = useState(false)
useEffect(() => {
drafting('reply', open)
return () => { drafting('reply', false) }
}, [drafting, open])
const writing = useWriting(t)
if (!open) {
return <button type="button" className={css.replyPrompt} onClick={() => { setOpen(true) }}>{t('thread.replyPlaceholder')}</button>
}
const send = async (text: string, pending: boolean): Promise<void> => {
if (await writing.run(() => writes.write({ kind: 'reply', thread: thread.id, body: text, pending }))) setOpen(false)
}
return <TextForm label={t('thread.replyPlaceholder')} initial="" busy={writing.busy} error={writing.error}
cancel={{ label: t('review.cancel'), run: () => { setOpen(false) } }}>
{(text, blank) => writes.reviewStarted
? <Button size="sm" variant="primary" disabled={writing.busy || blank} onClick={() => { void send(text, true) }}>
{t(writing.busy ? 'review.publishing' : 'review.queue')}
</Button>
: <SplitAction disabled={writing.busy || blank} label={t(writing.busy ? 'review.publishing' : 'thread.reply')}
run={() => { void send(text, false) }} menuLabel={t('thread.replyActions')}
other={writes.canReview ? t('review.startReview') : undefined} menu={() => { void send(text, true) }} />}
</TextForm>
}
/** Resolve or unresolve a thread. */
function Resolution({ thread, writes, t }: PropsLocale<typeof NS> & {
readonly thread: ForgeReviewThread
readonly writes: ThreadWrites
}): ReactNode {
const writing = useWriting(t)
return <>
<Button size="sm" disabled={writing.busy}
onClick={() => { void writing.run(() => writes.write({ kind: 'resolve', thread: thread.id, resolved: !thread.resolved })) }}>
{t(thread.resolved ? 'thread.unresolve' : 'thread.resolve')}
</Button>
{writing.error !== null && <div className={clsx(composerCss.error, css.actionError)} role="alert">{writing.error}</div>}
</>
}
/**
* Render one thread: its place, every comment, its reply field, and its actions. A resolved thread folds into one row
* until the reader unfolds it or jumps to it.
* @param props - the thread, where it shows, the shared actions, and copy.
* @returns the thread card or its folded row.
*/
export function ThreadCard({ thread, place, actions, t }: PropsLocale<typeof NS> & {
readonly thread: ForgeReviewThread
readonly place: ThreadPlace
readonly actions: ThreadActions
}): ReactNode {
const [open, setOpen] = useState(false)
// The jump the reader folded the thread after, which no longer unfolds it.
const [foldedAt, setFoldedAt] = useState<number | null>(null)
const labels = useMarkdownLabels(t)
const now = Date.now()
const focused = actions.focused?.id === thread.id && actions.focused.revision !== foldedAt
// A thread resolved elsewhere while the reader writes a reply or an edit stays open, so the text is not lost.
const [drafts, setDrafts] = useState<ReadonlySet<string>>(() => new Set())
const drafting = useCallback<Drafting>((form, active) => {
setDrafts((value) => {
if (value.has(form) === active) return value
const next = new Set(value)
if (active) next.add(form)
else next.delete(form)
return next
})
}, [])
const unfolded = open || !thread.resolved || focused || drafts.size > 0
const side = place.kind === 'line' ? place.side : thread.side
const original = place.kind === 'outdated' && thread.original !== null ? thread.original : null
// The composer names an outdated thread by the lines it was written on, as its label does.
const range = place.kind === 'line' ? anchorRange(place.side, place) : original !== null ? anchorRange(thread.side, original) : null
const commit = writtenOn(thread)
const first = thread.comments[0]
const url = first?.url ?? null
const writes = actions.writes
if (!unfolded) {
return <div className={css.folded} data-forge-thread={thread.id} data-side={side}>
<IconCheckOutlineRegular size={14} />
<span className={css.foldedText}>{t('thread.resolvedRow', { author: first?.author?.login ?? t('thread.deletedAuthor') })}</span>
<button type="button" className={css.link} aria-expanded={false} onClick={() => { setOpen(true) }}>{t('thread.expand')}</button>
</div>
}
const label = original !== null ? t('thread.originally', { range: anchorRange(thread.side, original) }) : range ?? t('thread.fileLevel')
return <section className={css.card} data-forge-thread={thread.id} data-side={side}
data-resolved={thread.resolved ? '' : undefined} aria-label={label} tabIndex={-1}>
<div className={css.header}>
<span className={css.place}>
{label}
{commit !== null && <> · {t('thread.onCommit', { commit })}</>}
</span>
{place.kind === 'outdated' && <Tag tone="warning">{t('thread.outdatedTag')}</Tag>}
{thread.resolved && <Tag tone="success">{t('thread.filter.resolved')}</Tag>}
<span className={css.spacer} />
{thread.resolved && <button type="button" className={css.link} aria-expanded onClick={() => {
setOpen(false)
setFoldedAt(actions.focused?.revision ?? null)
}}>{t('thread.collapse')}</button>}
{original !== null && thread.side === 'R' && <OriginalFile thread={thread} commit={original.commit} actions={actions} t={t} />}
</div>
{place.kind === 'outdated' && thread.diffHunk !== null && original !== null
&& <Excerpt hunk={thread.diffHunk} side={thread.side} lines={original.endLine - original.startLine + 1} />}
<div className={css.comments}>
{thread.comments.map(comment => <Comment key={comment.id} comment={comment} last={thread.comments.length === 1}
actions={actions} labels={labels} now={now} drafting={drafting} t={t} />)}
</div>
{writes !== null && thread.viewerCanReply && <Reply thread={thread} writes={writes} drafting={drafting} t={t} />}
<div className={css.actions}>
<Button size="sm" onClick={() => { if (!actions.addToInput(thread, range)) actions.inputFailed() }}>
{t('review.addToInput')}
</Button>
{url !== null && <Button size="sm" onClick={() => { actions.openLink(url) }}>
<IconRightUpOutlineRegular size={14} />{t('thread.openOnHost')}
</Button>}
{writes !== null && thread.viewerCanResolve && <Resolution thread={thread} writes={writes} t={t} />}
</div>
</section>
}
/** The end of a recorded diff hunk: the lines a thread was written on and a few before them. */
function Excerpt({ hunk, side, lines }: { readonly hunk: string; readonly side: 'L' | 'R'; readonly lines: number }): ReactNode {
const excerpt = hunkExcerpt(hunk, side, lines)
return <div className={css.excerpt}>
{excerpt.header !== null && <div className={clsx(css.excerptLine, css.excerptHeader)}>{excerpt.header}</div>}
{excerpt.lines.map((line, index) => <div key={index} className={clsx(css.excerptLine,
line.startsWith('+') && css.added, line.startsWith('-') && css.deleted)}>{line}</div>)}
</div>
}
/**
* Show the whole file at the commit a thread was written on, with the thread's lines marked, under the thread header.
* Only a new-side thread offers it: its lines number that commit's file.
*/
function OriginalFile({ thread, commit, actions, t }: PropsLocale<typeof NS> & {
readonly thread: ForgeReviewThread
readonly commit: string
readonly actions: ThreadActions
}): ReactNode {
const [state, setState] = useState<{ readonly lines: readonly string[] } | 'closed' | 'loading' | { readonly failed: string }>('closed')
const marked = useRef<HTMLDivElement>(null)
useEffect(() => { marked.current?.scrollIntoView({ block: 'center' }) }, [state])
const toggle = (): void => {
if (state !== 'closed' && state !== 'loading') { setState('closed'); return }
setState('loading')
void actions.readText(commit, thread.path).then((result) => {
setState(result.ok ? { lines: result.value.split('\n') } : { failed: result.error.message })
})
}
const open = state !== 'closed'
const range = thread.original
return <>
<button type="button" className={css.link} aria-expanded={open} disabled={state === 'loading'} onClick={toggle}>
{t(open ? 'thread.hideOriginal' : 'thread.viewOriginal')}
</button>
{open && <div className={css.original} role="region" aria-label={t('thread.viewOriginal')}>
{state === 'loading' ? <div className={css.originalNote}>{t('thread.originalLoading')}</div>
: 'failed' in state ? <div className={css.originalNote} role="alert">{t('thread.originalFailed', { message: state.failed })}</div>
: state.lines.map((line, index) => {
const number = index + 1
const inside = range !== null && number >= range.startLine && number <= range.endLine
return <div key={index} ref={inside && number === range.startLine ? marked : undefined}
className={clsx(css.originalLine, inside && css.marked)}>
<span className={css.originalNumber}>{number}</span><span>{line}</span>
</div>
})}
</div>}
</>
}
/**
* Render the outdated threads of a file after its lines, as one section the reader can fold.
* @param props - the threads, the shared actions, and copy.
* @returns the section, or nothing without outdated threads.
*/
export function OutdatedThreads({ threads, actions, t }: PropsLocale<typeof NS> & {
readonly threads: readonly ForgeReviewThread[]
readonly actions: ThreadActions
}): ReactNode {
// The section is folded after the jump with this revision, or -1 before any jump, or null while unfolded.
const [folded, setFolded] = useState<number | null>(null)
if (threads.length === 0) return null
const jump = actions.focused
const open = folded === null || (jump !== null && jump.revision !== folded && threads.some(thread => thread.id === jump.id))
return <section className={css.outdated} data-forge-outdated-threads="">
<div className={css.outdatedHeader}>
<span>{t('thread.outdatedSection', { count: threads.length })}</span>
<span className={css.spacer} />
<button type="button" className={css.link} aria-expanded={open} onClick={() => { setFolded(open ? jump?.revision ?? -1 : null) }}>
{t(open ? 'thread.collapse' : 'thread.expand')}
<IconChevronDownOutlineRegular size={12} className={clsx(!open && css.turned)} />
</button>
</div>
{open && threads.map(thread => <ThreadCard key={thread.id} thread={thread} place={{ kind: 'outdated' }} actions={actions} t={t} />)}
</section>
}
@@ -13,3 +13,14 @@
.decisions label:has(input:disabled) { cursor: default; opacity: 0.5; }
.error { color: var(--dsw-alias-state-error-primary); overflow-wrap: anywhere; }
.reconcile { display: flex; flex-wrap: wrap; gap: 8px; }
.discard { margin-inline-end: auto; }
.confirm {
display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 12px;
border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md);
/* An elevated surface inside the scrolling dialog body, so anything that scrolls in it takes the l2 thumb pair
(see ui-theme styles/scrollbar.css for the rebinding contract). */
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
background: var(--dsw-alias-bg-layer-2);
}
.confirmText { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
@@ -1,51 +1,75 @@
/** Centered review submission with a summary, decision, and pending-comment count. */
/** Centered review submission with a summary, decision, and pending-comment count, and the discarding of a pending review. */
import { useId, useSyncExternalStore, type ReactNode } from 'react'
import { useId, useState, useSyncExternalStore, type ReactNode } from 'react'
import clsx from 'clsx'
import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { ForgePendingReview } from '@deepseek-ai/dsh-experimental-forge/types'
import type { ReviewQueue } from './review-queue.ts'
import type { NS } from './locales.ts'
import css from './SubmitReview.module.css'
import reviewCss from './ReviewComposer.module.css'
/**
* Submit a review independently of the diff scroll position; comments remain at their code locations.
* @param props - durable queue, current head, submission outcome, and modal actions.
* Submit a review independently of the diff scroll position; comments remain at their code locations. With a pending
* review on the code host, the review holds its comments, and comment drafts kept in the browser must leave first.
* @param props - durable queue, current head, the pending review, submission outcome, and modal actions.
* @returns a portalled modal with keyboard focus ownership.
*/
export function SubmitReview({ queue, url, headSha, busy, error, submit, close, check, reconcile, t }: PropsLocale<typeof NS> & {
export function SubmitReview({
queue, url, headSha, pending, own, busy, error, submit, discard, close, check, reconcile, t,
}: PropsLocale<typeof NS> & {
readonly queue: ReviewQueue
readonly url: string
readonly headSha: string
/** The signed-in user's pending review on the code host, or null without one. */
readonly pending: ForgePendingReview | null
/** Whether the signed-in user authored the change request, which the code host lets them only comment on. */
readonly own: boolean
readonly busy: boolean
readonly error: string | null
readonly submit: () => void
/** Discard the pending review, or undefined without one. */
readonly discard: (() => void) | undefined
readonly close: () => void
readonly check: () => void
readonly reconcile: () => void
}): ReactNode {
const state = useSyncExternalStore(queue.subscribe, queue.getSnapshot)
const [confirming, setConfirming] = useState(false)
const name = useId()
const summaryHint = `${name}-summary-hint`
const requiresSummary = state.event === 'request-changes'
const locked = busy || state.uncertain !== null
const stale = state.comments.some(item => item.source.kind !== 'change' || item.source.url !== url || item.source.headSha !== headSha)
const empty = state.comments.some(item => item.comment.body.trim() === '')
// A decision kept from another change request stays chosen until the reader picks Comment.
const refused = own && state.event !== 'comment'
const count = pending?.comments ?? state.comments.length
// Drafts kept in the browser join only a review published without a pending one on the code host.
const blocked = pending !== null && state.comments.length > 0
const stale = pending === null
&& state.comments.some(item => item.source.kind !== 'change' || item.source.url !== url || item.source.headSha !== headSha)
const empty = (pending === null && state.comments.some(item => item.comment.body.trim() === ''))
|| (requiresSummary && state.body.trim() === '')
|| (state.event === 'comment' && state.body.trim() === '' && state.comments.length === 0)
|| (state.event === 'comment' && state.body.trim() === '' && count === 0)
const notice = state.error !== null ? t(state.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')
: stale ? t('review.stale') : error
: blocked ? t('review.browserDrafts', { count: state.comments.length }) : stale ? t('review.stale') : error
return <Modal open onClose={close} title={t('review.submit')} closeLabel={t('review.close')}
className={clsx(css.modal)} contentClassName={clsx(css.content)}
footer={<>
{discard !== undefined && <Button variant="outline" className={clsx(css.discard)} disabled={locked || confirming}
onClick={() => { setConfirming(true) }}>{t('review.discard')}</Button>}
<Button variant="outline" onClick={close}>{t('review.cancel')}</Button>
<Button variant="primary" disabled={locked || stale || empty || state.error !== null} onClick={submit}>
{t(busy ? 'review.submitting' : 'review.submit')}
<Button variant="primary" disabled={locked || confirming || blocked || stale || empty || refused || state.error !== null} onClick={submit}>
{t(busy && !confirming ? 'review.submitting' : 'review.submit')}
</Button>
</>}>
<div className={css.form}>
<div className={css.count}>{t('review.drafts', { count: state.comments.length })}</div>
<div className={css.count}>{t('review.drafts', { count })}</div>
{discard !== undefined && confirming && <div className={css.confirm} role="group" aria-label={t('review.discard')}>
<span className={css.confirmText}>{t('review.discardConfirm', { count })}</span>
<Button size="sm" variant="outline" disabled={busy} onClick={() => { setConfirming(false) }}>{t('review.cancel')}</Button>
<Button size="sm" variant="primary" disabled={busy} onClick={discard}>{t(busy ? 'review.discarding' : 'review.discard')}</Button>
</div>}
<div className={css.summary}>
<textarea data-modal-autofocus className={clsx(reviewCss.input, css.input)} rows={4} disabled={locked} value={state.body}
aria-label={t('review.summary')} placeholder={t('review.summary')} required={requiresSummary}
@@ -55,11 +79,12 @@ export function SubmitReview({ queue, url, headSha, busy, error, submit, close,
</div>
<div className={css.decisions}>
{(['comment', 'approve', 'request-changes'] as const).map(value => <label key={value}>
<input type="radio" name={name} value={value} checked={state.event === value} disabled={locked}
<input type="radio" name={name} value={value} checked={state.event === value} disabled={locked || (own && value !== 'comment')}
onChange={() => { queue.summarize(state.body, value) }} />
{t(value === 'comment' ? 'review.commentOnly' : value === 'approve' ? 'review.approve' : 'review.requestChanges')}
</label>)}
</div>
{own && <div className={css.hint}>{t('review.ownChangeRequest')}</div>}
{notice !== null && <div className={css.error} role="alert">{notice}</div>}
{state.uncertain !== null && !busy && <div className={css.reconcile}>
<Button size="sm" variant="outline" onClick={check}>{t('review.recheck')}</Button>
@@ -0,0 +1,218 @@
/* The thread list docks at the end of the changes body in a view at least 1040px wide, which leaves the code about
480px beside the file tree and the list; it floats over the files with a scrim behind it in a narrower view, and
takes the files' whole width below 480px. The queries name no container, since CSS Modules rename a container name
per file; the nearest inline-size container is the changes view. */
.scrim { display: none; }
.pane {
display: flex;
flex: none;
flex-direction: column;
box-sizing: border-box;
width: 320px;
min-height: 0;
border-inline-start: 0.5px solid var(--dsw-alias-border-l3);
background: var(--forge-changes-bg, var(--dsw-alias-bg-base));
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xs-13);
font-family: Inter, var(--dsw-font-family);
}
.pane:focus { outline: none; }
.header {
display: flex;
align-items: center;
gap: 6px;
min-height: 40px;
padding: 0 6px 0 12px;
}
.title { font-weight: 500; }
/* Takes the place of the title and the close button where the list covers the files' whole width. */
.back {
display: none;
align-items: center;
gap: 2px;
height: 28px;
padding: 0 8px 0 4px;
border: 0;
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-primary);
font: inherit;
cursor: pointer;
}
@media (hover: hover) {
.back:hover { background: var(--dsw-alias-interactive-bg-hover); }
}
.total {
padding: 0 6px;
border-radius: var(--dsw-radius-xs);
background: var(--dsw-alias-card-fill);
color: var(--dsw-alias-label-secondary);
font-size: 11px;
line-height: 18px;
}
.spacer { flex: 1; }
.close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-secondary);
cursor: pointer;
}
@media (hover: hover) {
.close:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
}
.filters {
padding: 0 12px 10px;
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
}
.rows {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 4px 6px;
}
.group + .group { margin-top: 6px; }
.path {
margin: 0;
padding: 8px 6px 4px;
font: inherit;
font-size: 12px;
font-weight: 500;
}
.item {
display: flex;
gap: 8px;
box-sizing: border-box;
width: 100%;
padding: 8px 6px;
border: 0;
border-radius: var(--dsw-radius-md);
background: transparent;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
}
@media (hover: hover) {
.item:hover { background: var(--dsw-alias-interactive-bg-hover); }
}
.item:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -1px;
}
.itemMain {
display: flex;
flex: 1;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.meta { color: var(--dsw-alias-label-tertiary); font-size: 12px; }
.excerpt {
display: -webkit-box;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow-wrap: anywhere;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.tags:empty { display: none; }
.note {
padding: 24px 12px;
color: var(--dsw-alias-label-secondary);
text-align: center;
}
.footer {
padding: 10px 12px;
border-top: 0.5px solid var(--dsw-alias-border-l3);
color: var(--dsw-alias-label-secondary);
font-size: 12px;
}
.link {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 0;
border: 0;
background: transparent;
color: var(--dsw-alias-state-business-primary);
font: inherit;
cursor: pointer;
}
@media (hover: hover) {
.link:hover { text-decoration: underline; }
}
/* Above the sticky file headers (z-index 2). */
@container (max-width: 1039px) {
.scrim {
position: absolute;
z-index: 3;
inset: 0;
display: block;
background: var(--dsw-alias-bg-mask-1);
}
.pane {
position: absolute;
z-index: 3;
inset-block: 0;
inset-inline-end: 0;
width: min(340px, calc(100% - 40px));
box-shadow: var(--dsw-elevation-panel);
}
}
@container (max-width: 479px) {
.scrim { display: none; }
.pane {
width: 100%;
border-inline-start: 0;
box-shadow: none;
}
.header { padding-inline-start: 6px; }
.back { display: inline-flex; }
.title,
.total,
.close { display: none; }
}
@@ -0,0 +1,165 @@
/**
* The thread list of a change request beside its changes: every thread grouped by file in file tree order, narrowed
* by whether it is resolved, each opening the place it shows at. A wide changes view docks the list beside the files;
* a narrower one floats it over them, and the narrowest gives it their whole width.
*/
import { useLayoutEffect, useMemo, useRef, type KeyboardEvent, type ReactNode } from 'react'
import { IconChevronLeftOutlineRegular, IconCloseOutlineRegular, IconRightUpOutlineRegular, Tag, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
import type { ForgeDiffFile } from '../types.ts'
import { FileLabel } from './FileLabel.tsx'
import { SegmentedChoice } from './ReviewControls.tsx'
import { Avatar } from './ReviewThreads.tsx'
import { anchorRange, inFileOrder, passesFilter, THREAD_FILTERS, type ThreadFilter, type ThreadPlace } from './review-threads.ts'
import type { NS } from './locales.ts'
import type { PlacedThread } from './thread-state.ts'
import css from './ThreadList.module.css'
type Translate = PropsLocale<typeof NS>['t']
/** Props of the thread list. */
export interface ThreadListProps extends PropsLocale<typeof NS> {
/** Every thread read, in host order, with where the current changes show it. */
readonly entries: readonly PlacedThread[]
/** Changed files in file tree order; threads on other paths follow them. */
readonly files: readonly ForgeDiffFile[]
/** Whether the host has more threads than were read. */
readonly truncated: boolean
/** Web page of the change request. */
readonly url: string
/** The active filter. */
readonly filter: ThreadFilter
/** Choose a filter. */
readonly choose: (filter: ThreadFilter) => void
/** Whether the reader just opened the list, so a list that covers the files takes the focus. */
readonly claim: boolean
/** Report that the list handled `claim`. */
readonly claimed: () => void
/** Open the place of a thread; `covering` says the list covers the files, so the owner closes it first. */
readonly open: (entry: PlacedThread, covering: boolean) => void
/** Open a URL outside the app. */
readonly openLink: (url: string) => void
/** Close the list at the reader's request. */
readonly close: () => void
}
function meta(thread: ForgeReviewThread, place: ThreadPlace, t: Translate): string {
const replies = thread.comments.length - 1
const parts: string[] = []
if (thread.subject === 'file') parts.push(t('thread.fileLevel'))
else if (place.kind === 'line') parts.push(anchorRange(place.side, place))
else if (thread.original !== null) {
parts.push(t('thread.originally', { range: anchorRange(thread.side, thread.original) }), t('thread.onCommit', { commit: thread.original.commit.slice(0, 7) }))
}
if (replies > 0) parts.push(t('thread.replies', { count: replies }))
return parts.join(' · ')
}
/** Whether the list floats over the files or takes their width, which its narrow-view styles decide. */
function covers(pane: HTMLElement | null): pane is HTMLElement {
return pane !== null && getComputedStyle(pane).position === 'absolute'
}
/**
* The first comment as one line of plain text: without raw HTML, strong, strikethrough, and code marks, quote or
* heading marks, and link targets.
*/
function plainExcerpt(body: string): string {
return body.replace(/<[^>]*>/g, ' ').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^\s*(?:#{1,6}|>)\s*/gm, '')
.replace(/\*\*|__|~~|`/g, '').replace(/\s+/g, ' ').trim()
}
function Item({ entry, open, t }: {
readonly entry: PlacedThread
readonly open: (entry: PlacedThread) => void
readonly t: Translate
}): ReactNode {
const { thread, place } = entry
const first = thread.comments[0]
return <button type="button" className={css.item} data-forge-thread-item={thread.id} onClick={() => { open(entry) }}>
<Avatar author={first?.author ?? null} size={22} />
<span className={css.itemMain}>
<span className={css.meta}>{meta(thread, place, t)}</span>
<span className={css.excerpt}>{plainExcerpt(first?.body ?? '')}</span>
<span className={css.tags}>
{place.kind === 'outdated' && <Tag tone="warning">{t('thread.outdatedTag')}</Tag>}
{place.kind === 'elsewhere' && <Tag tone="neutral">{t('thread.elsewhereTag')}</Tag>}
{thread.resolved && <Tag tone="success">{t('thread.filter.resolved')}</Tag>}
{first?.author?.bot === true && <Tag tone="outline">{t('thread.bot')}</Tag>}
</span>
</span>
</button>
}
/**
* Render the thread list.
* @param props - threads, their places, the file order, the filter, and the list's actions.
* @returns the list pane and the scrim behind it where it floats over the files.
*/
export function ThreadList(props: ThreadListProps): ReactNode {
const { entries, files, filter, t } = props
const threads = useMemo(() => entries.map(entry => entry.thread), [entries])
const counts = useMemo(() => Object.fromEntries(THREAD_FILTERS.map(item => [item,
threads.filter(thread => passesFilter(thread, item)).length])) as Record<ThreadFilter, number>, [threads])
const groups = useMemo(() => {
const known = new Map(files.map((file, index) => [file.path, { file, index }]))
const byPath = new Map<string, PlacedThread[]>()
for (const entry of entries) {
if (!passesFilter(entry.thread, filter)) continue
const list = byPath.get(entry.thread.path)
if (list === undefined) byPath.set(entry.thread.path, [entry])
else list.push(entry)
}
const position = (path: string): number => known.get(path)?.index ?? files.length
return [...byPath].sort(([a], [b]) => position(a) - position(b) || a.localeCompare(b))
.map(([path, list]) => [path, inFileOrder(list, known.get(path)?.file)] as const)
}, [entries, files, filter])
const pane = useRef<HTMLElement>(null)
useLayoutEffect(() => {
if (!props.claim) return
props.claimed()
if (covers(pane.current)) pane.current.focus({ preventScroll: true })
}, [props.claim])
const escape = (event: KeyboardEvent<HTMLElement>): void => {
if (event.key !== 'Escape') return
event.preventDefault()
event.stopPropagation()
props.close()
}
const open = (entry: PlacedThread): void => { props.open(entry, covers(pane.current)) }
return <>
<div className={css.scrim} aria-hidden="true" onClick={props.close} />
<aside ref={pane} className={css.pane} tabIndex={-1} aria-label={t('thread.listAria', { count: threads.length })} data-forge-thread-list=""
onKeyDown={escape}>
<div className={css.header}>
<button type="button" className={css.back} onClick={props.close}><IconChevronLeftOutlineRegular size={14} />{t('thread.back')}</button>
<span className={css.title}>{t('thread.list')}</span>
<span className={css.total}>{threads.length}</span>
<span className={css.spacer} />
<Tooltip label={t('thread.close')} side="bottom">
<button type="button" className={css.close} aria-label={t('thread.close')} onClick={props.close}><IconCloseOutlineRegular size={14} /></button>
</Tooltip>
</div>
<div className={css.filters}>
<SegmentedChoice label={t('thread.filterAria')} value={filter} choose={props.choose}
segments={THREAD_FILTERS.map(item => ({ value: item, label: t(`thread.filter.${item}`), count: counts[item], disabledTip: null }))} />
</div>
<div className={css.rows}>
{threads.length === 0 ? <div className={css.note}>{t('thread.empty')}</div>
: groups.length === 0 ? <div className={css.note}>{t('thread.none')}</div>
: groups.map(([path, list]) => <section key={path} className={css.group} data-forge-thread-group={path}>
<h3 className={css.path}><FileLabel path={path} /></h3>
{list.map(entry => <Item key={entry.thread.id} entry={entry} open={open} t={t} />)}
</section>)}
</div>
<div className={css.footer}>
{props.truncated && <>{t('thread.truncated', { count: threads.length })}{' · '}</>}
<button type="button" className={css.link} onClick={() => { props.openLink(props.url) }}>
<IconRightUpOutlineRegular size={14} />{t('thread.openAll')}
</button>
</div>
</aside>
</>
}
@@ -0,0 +1,79 @@
/** The changes toolbar's More menu, which holds the view controls a narrow toolbar folds out of its row. */
import { useState, type ReactNode } from 'react'
import clsx from 'clsx'
import { IconEllipsisOutlineRegular, Menu, Tooltip, type MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { NS } from './locales.ts'
import { foldOf } from './toolbar-fold.ts'
import css from './ChangesTab.module.css'
/** Toolbar state and actions the menu repeats. */
export interface ViewOptions {
/** Whether any shown file is expanded, so the expansion row collapses them all. */
readonly anyExpanded: boolean
/** Whether any file shows, so the expansion row has files to change. */
readonly hasFiles: boolean
readonly toggleExpansion: () => void
readonly split: boolean
readonly toggleSplit: () => void
readonly wrap: boolean
readonly toggleWrap: () => void
/** Whether test files hide, or undefined when the toolbar offers no test switch. */
readonly hideTests: boolean | undefined
readonly toggleTests: () => void
readonly refresh: () => void
}
/**
* Render the More button and its menu, which lists the controls of the toolbar's fold level when it opens (see
* `observeToolbarFold`); the toolbar's styles hide the button while nothing folds.
* @param props - the toolbar state and actions, whether the owning tab is visible, and copy.
* @returns the button and its portalled menu.
*/
export function ViewOptionsMenu({ options, visible, t }: PropsLocale<typeof NS> & {
readonly options: ViewOptions
readonly visible: boolean
}): ReactNode {
const [fold, setFold] = useState<number | null>(null)
const open = visible && fold !== null
const entries: MenuEntry[] = []
if (fold !== null) {
entries.push(
{ id: 'expansion', label: t(options.anyExpanded ? 'diff.collapseAll' : 'diff.expandAll'), disabled: !options.hasFiles },
{ id: 'split', label: t('diff.splitAria') },
{ id: 'wrap', label: t('diff.wrapAria') },
)
if (fold >= 2 && options.hideTests !== undefined) entries.push({ type: 'separator', id: 'tests-separator' }, { id: 'tests', label: t('tests.hide') })
if (fold >= 3) entries.push({ type: 'separator', id: 'refresh-separator' }, { id: 'refresh', label: t('diff.refresh') })
}
const selected = [options.split && 'split', options.wrap && 'wrap', options.hideTests === true && 'tests'].filter(item => item !== false)
const run = (id: string): void => {
switch (id) {
case 'expansion': options.toggleExpansion(); break
case 'split': options.toggleSplit(); break
case 'wrap': options.toggleWrap(); break
case 'tests': options.toggleTests(); break
case 'refresh': options.refresh(); break
/* v8 ignore next -- the menu offers only the rows above */
default: break
}
}
return (
<Menu open={open} portal dense align="end" autoFocus items={entries} selectedIds={selected}
onClose={() => { setFold(null) }}
onSelect={(id) => {
setFold(null)
run(id)
}}
anchor={(
<Tooltip label={t('diff.moreOptions')} side="bottom">
<button type="button" className={clsx(css.tool, css.more)} aria-label={t('diff.moreOptions')}
aria-haspopup="menu" aria-expanded={open} data-forge-view-options=""
onClick={(event) => { setFold(fold === null ? foldOf(event.currentTarget) : null) }}>
<IconEllipsisOutlineRegular />
</button>
</Tooltip>
)} />
)
}
@@ -47,6 +47,7 @@ export const zh = {
'review.approve': '批准',
'review.requestChanges': '请求更改',
'review.summaryRequired': '请求更改时,请填写评审总结',
'review.ownChangeRequest': '这是你自己的 PR,GitHub 只允许评论,不能批准或请求更改',
'review.commentOnly': '评论',
'review.drafts': '待提交评论({count})',
'review.edit': '编辑',
@@ -192,6 +193,7 @@ export const zh = {
'viewed.changed': '有新改动',
'viewed.progress': '已审阅 {viewed} / {total}',
'viewed.progressAria': '已审阅的文件',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': '无法保存已审阅状态',
'commits.all': '全部提交',
'commits.range': '{from}…{to}',
@@ -215,6 +217,7 @@ export const zh = {
'diff.wrap': '开启自动换行',
'diff.nowrap': '关闭自动换行',
'diff.wrapAria': '自动换行',
'diff.moreOptions': '更多视图选项',
'diff.unchanged': '{count} 行未变更',
'diff.unchangedRest': '其余未变更的行',
'diff.newFile': '新文件',
@@ -308,6 +311,70 @@ export const zh = {
'toast.expandStale': '文件在读取变更后又有修改,刷新后再展开',
'toast.prompted': '已发送:{text}',
'toast.promptFailed': '无法发送消息',
'thread.list': '讨论',
'thread.listAria': '讨论列表,共 {count} 个',
'thread.close': '关闭讨论列表',
'thread.filterAria': '筛选讨论',
'thread.filter.unresolved': '未解决',
'thread.filter.resolved': '已解决',
'thread.filter.all': '全部',
'thread.none': '没有符合筛选条件的讨论',
'thread.empty': '还没有评审讨论',
'thread.back': '返回变更',
'thread.truncated': '讨论太多,只显示了前 {count} 个',
'thread.openAll': '在 GitHub 中查看',
'thread.replies': '{count} 条回复',
'thread.fileLevel': '文件级讨论',
'thread.onCommit': '在 {commit} 上',
'thread.originally': '原在 {range}',
'thread.outdatedTag': '已过期',
'thread.elsewhereTag': '不在所选提交中',
'thread.author': '作者',
'thread.bot': 'bot',
'thread.deletedAuthor': '已删除的账号',
'thread.resolvedRow': '已解决的讨论 · {author}',
'thread.expand': '展开',
'thread.collapse': '收起',
'thread.outdatedSection': '{count} 条讨论已过期:所在代码已被后续提交修改',
'thread.viewOriginal': '查看当时的文件',
'thread.hideOriginal': '收起当时的文件',
'thread.originalLoading': '正在读取当时的文件…',
'thread.originalFailed': '无法读取当时的文件:{message}',
'thread.openOnHost': '在 GitHub 中查看',
'thread.unresolvedCount': '{count} 条未解决',
'thread.unresolvedAria': '{name} 有 {count} 条未解决的讨论,跳到下一条',
'thread.next': '跳到下一条未解决的讨论',
'thread.treeCount': '{count} 条未解决的讨论',
'thread.loadFailed': '无法读取 GitHub 讨论:{message}',
'thread.inputFailed': '输入框暂时无法添加这个讨论,请稍后重试',
'thread.copy': '复制',
'thread.copied': '复制成功',
'thread.codeBlock': '代码块',
'thread.wrap': '自动换行',
'thread.unwrap': '取消自动换行',
'thread.footnotes': '脚注',
'review.browserDraft': '浏览器草稿',
'review.browserDrafts': '有 {count} 条评论草稿只保存在此浏览器中,不在 GitHub 的待提交评审里。请先将它们加入评审或删除',
'review.discard': '丢弃评审',
'review.discardConfirm': '丢弃待提交的评审及其中的 {count} 条评论?此操作无法撤销',
'review.discarding': '丢弃中…',
'review.discarded': '已丢弃评审',
'thread.reply': '回复',
'thread.replyPlaceholder': '回复…',
'thread.replyActions': '回复选项',
'thread.resolve': '解决讨论',
'thread.unresolve': '取消解决',
'thread.commentActions': '{author} 的评论操作',
'thread.editAria': '编辑评论',
'thread.save': '保存',
'thread.saving': '保存中…',
'thread.deleting': '删除中…',
'thread.deleteConfirm': '删除这条评论?',
'thread.deleteLast': '删除这条评论?它是讨论中唯一的评论,讨论也会一并删除',
'thread.writeUnknown': '无法确认 GitHub 是否已执行。正在重新读取讨论,请核对后再重试',
'thread.writeFailed': 'GitHub 未执行此操作:{message}',
'thread.writeStale': 'PR 已有新提交。讨论会按新提交重新读取,请核对后重试',
'thread.writeUnsupported': '此代码托管服务不支持在这里修改讨论',
} as const
/** Key of the forge panel dictionaries. */
@@ -357,6 +424,7 @@ export const en: Record<ForgePanelKey, string> = {
'review.approve': 'Approve',
'review.requestChanges': 'Request changes',
'review.summaryRequired': 'Enter a review summary to request changes.',
'review.ownChangeRequest': 'This is your own PR. GitHub lets you comment on it, but not approve it or request changes.',
'review.commentOnly': 'Comment',
'review.drafts': 'Pending comments ({count})',
'review.edit': 'Edit',
@@ -502,6 +570,7 @@ export const en: Record<ForgePanelKey, string> = {
'viewed.changed': 'Changed since viewed',
'viewed.progress': '{viewed} / {total} viewed',
'viewed.progressAria': 'Viewed files',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'Could not save the viewed state',
'commits.all': 'All commits',
'commits.range': '{from}…{to}',
@@ -525,6 +594,7 @@ export const en: Record<ForgePanelKey, string> = {
'diff.wrap': 'Wrap long lines',
'diff.nowrap': 'Stop wrapping long lines',
'diff.wrapAria': 'Wrap lines',
'diff.moreOptions': 'More view options',
'diff.unchanged': '{count} unchanged lines',
'diff.unchangedRest': 'Remaining unchanged lines',
'diff.newFile': 'New file',
@@ -618,6 +688,70 @@ export const en: Record<ForgePanelKey, string> = {
'toast.expandStale': 'The file changed after its changes were read; refresh before expanding',
'toast.prompted': 'Sent: {text}',
'toast.promptFailed': 'The message could not be sent',
'thread.list': 'Threads',
'thread.listAria': 'Review threads, {count} in total',
'thread.close': 'Close the thread list',
'thread.filterAria': 'Filter threads',
'thread.filter.unresolved': 'Unresolved',
'thread.filter.resolved': 'Resolved',
'thread.filter.all': 'All',
'thread.none': 'No threads match this filter',
'thread.empty': 'No review threads yet',
'thread.back': 'Back to changes',
'thread.truncated': 'Too many threads; showing the first {count}',
'thread.openAll': 'View on GitHub',
'thread.replies': '{count} replies',
'thread.fileLevel': 'File thread',
'thread.onCommit': 'on {commit}',
'thread.originally': 'Originally {range}',
'thread.outdatedTag': 'Outdated',
'thread.elsewhereTag': 'Not in the chosen commits',
'thread.author': 'Author',
'thread.bot': 'bot',
'thread.deletedAuthor': 'Deleted account',
'thread.resolvedRow': 'Resolved thread · {author}',
'thread.expand': 'Expand',
'thread.collapse': 'Collapse',
'thread.outdatedSection': '{count} outdated threads: later commits changed their code',
'thread.viewOriginal': 'View file at that commit',
'thread.hideOriginal': 'Hide file at that commit',
'thread.originalLoading': 'Reading the file at that commit…',
'thread.originalFailed': 'Could not read the file at that commit: {message}',
'thread.openOnHost': 'View on GitHub',
'thread.unresolvedCount': '{count} unresolved',
'thread.unresolvedAria': '{name} has {count} unresolved threads; go to the next one',
'thread.next': 'Go to the next unresolved thread',
'thread.treeCount': '{count} unresolved threads',
'thread.loadFailed': 'Could not read GitHub threads: {message}',
'thread.inputFailed': 'The input could not take this thread; try again later',
'thread.copy': 'Copy',
'thread.copied': 'Copied',
'thread.codeBlock': 'Code block',
'thread.wrap': 'Wrap lines',
'thread.unwrap': 'Do not wrap lines',
'thread.footnotes': 'Footnotes',
'review.browserDraft': 'Browser draft',
'review.browserDrafts': '{count} comment drafts are saved only in this browser, not in your pending GitHub review. Add them to the review or delete them first.',
'review.discard': 'Discard review',
'review.discardConfirm': 'Discard your pending review and its {count} comments? This cannot be undone.',
'review.discarding': 'Discarding…',
'review.discarded': 'Review discarded',
'thread.reply': 'Reply',
'thread.replyPlaceholder': 'Reply…',
'thread.replyActions': 'Reply options',
'thread.resolve': 'Resolve thread',
'thread.unresolve': 'Unresolve thread',
'thread.commentActions': 'Actions for the comment by {author}',
'thread.editAria': 'Edit comment',
'thread.save': 'Save',
'thread.saving': 'Saving…',
'thread.deleting': 'Deleting…',
'thread.deleteConfirm': 'Delete this comment?',
'thread.deleteLast': 'Delete this comment? It is the only comment, so the thread is deleted too.',
'thread.writeUnknown': 'Could not confirm whether GitHub applied this. The threads are being read again; check them before retrying.',
'thread.writeFailed': 'GitHub did not apply this: {message}',
'thread.writeStale': 'The PR has new commits. The threads are read again at the new head; check them, then retry.',
'thread.writeUnsupported': 'This code host does not support changing threads here.',
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
@@ -671,6 +805,7 @@ export const ja: Record<ForgePanelKey, string> = {
'review.approve': '承認',
'review.requestChanges': '変更を要求',
'review.summaryRequired': '変更を要求するには、レビューの概要を入力してください。',
'review.ownChangeRequest': '自分の PR です。GitHub ではコメントのみ可能で、承認や変更の要求はできません。',
'review.commentOnly': 'コメント',
'review.drafts': '保留中のコメント({count})',
'review.edit': '編集',
@@ -816,6 +951,7 @@ export const ja: Record<ForgePanelKey, string> = {
'viewed.changed': '確認後に変更あり',
'viewed.progress': '確認済み {viewed} / {total}',
'viewed.progressAria': '確認済みのファイル',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': '確認済みの状態を保存できませんでした',
'commits.all': 'すべてのコミット',
'commits.range': '{from}…{to}',
@@ -839,6 +975,7 @@ export const ja: Record<ForgePanelKey, string> = {
'diff.wrap': '長い行を折り返す',
'diff.nowrap': '長い行を折り返さない',
'diff.wrapAria': '行を折り返す',
'diff.moreOptions': 'その他の表示オプション',
'diff.unchanged': '未変更 {count} 行',
'diff.unchangedRest': '残りの未変更行',
'diff.newFile': '新規ファイル',
@@ -932,6 +1069,70 @@ export const ja: Record<ForgePanelKey, string> = {
'toast.expandStale': '変更の読み取り後にファイルが更新されています。更新してから展開してください',
'toast.prompted': '送信しました:{text}',
'toast.promptFailed': 'メッセージを送信できませんでした',
'thread.list': 'スレッド',
'thread.listAria': 'レビュースレッド(全 {count} 件)',
'thread.close': 'スレッド一覧を閉じる',
'thread.filterAria': 'スレッドを絞り込む',
'thread.filter.unresolved': '未解決',
'thread.filter.resolved': '解決済み',
'thread.filter.all': 'すべて',
'thread.none': 'この条件に一致するスレッドはありません',
'thread.empty': 'レビュースレッドはまだありません',
'thread.back': '変更に戻る',
'thread.truncated': 'スレッドが多いため、最初の {count} 件のみ表示しています',
'thread.openAll': 'GitHub で表示',
'thread.replies': '返信 {count} 件',
'thread.fileLevel': 'ファイルへのスレッド',
'thread.onCommit': '{commit} 上',
'thread.originally': '元の位置 {range}',
'thread.outdatedTag': '古い',
'thread.elsewhereTag': '選択したコミットにない',
'thread.author': '作成者',
'thread.bot': 'bot',
'thread.deletedAuthor': '削除されたアカウント',
'thread.resolvedRow': '解決済みのスレッド · {author}',
'thread.expand': '展開',
'thread.collapse': '折りたたむ',
'thread.outdatedSection': '古いスレッド {count} 件:後のコミットで該当コードが変更されました',
'thread.viewOriginal': '当時のファイルを表示',
'thread.hideOriginal': '当時のファイルを閉じる',
'thread.originalLoading': '当時のファイルを読み込み中…',
'thread.originalFailed': '当時のファイルを読み込めません:{message}',
'thread.openOnHost': 'GitHub で表示',
'thread.unresolvedCount': '未解決 {count} 件',
'thread.unresolvedAria': '{name} に未解決のスレッドが {count} 件あります。次のスレッドへ移動',
'thread.next': '次の未解決のスレッドへ移動',
'thread.treeCount': '未解決のスレッド {count} 件',
'thread.loadFailed': 'GitHub のスレッドを読み込めません:{message}',
'thread.inputFailed': '入力欄にこのスレッドを追加できません。しばらくしてから再試行してください',
'thread.copy': 'コピー',
'thread.copied': 'コピーしました',
'thread.codeBlock': 'コードブロック',
'thread.wrap': '行を折り返す',
'thread.unwrap': '行を折り返さない',
'thread.footnotes': '脚注',
'review.browserDraft': 'ブラウザーの下書き',
'review.browserDrafts': '{count} 件のコメントの下書きはこのブラウザーにのみ保存され、GitHub の保留中のレビューに含まれていません。先にレビューに追加するか削除してください。',
'review.discard': 'レビューを破棄',
'review.discardConfirm': '保留中のレビューとその {count} 件のコメントを破棄しますか?この操作は元に戻せません。',
'review.discarding': '破棄中…',
'review.discarded': 'レビューを破棄しました',
'thread.reply': '返信',
'thread.replyPlaceholder': '返信…',
'thread.replyActions': '返信のオプション',
'thread.resolve': 'スレッドを解決',
'thread.unresolve': '解決を取り消す',
'thread.commentActions': '{author} のコメントの操作',
'thread.editAria': 'コメントを編集',
'thread.save': '保存',
'thread.saving': '保存中…',
'thread.deleting': '削除中…',
'thread.deleteConfirm': 'このコメントを削除しますか?',
'thread.deleteLast': 'このコメントを削除しますか?スレッド唯一のコメントのため、スレッドも削除されます。',
'thread.writeUnknown': 'GitHub に反映されたか確認できません。スレッドを再読み込みしています。確認してから再試行してください。',
'thread.writeFailed': 'GitHub はこの操作を実行しませんでした:{message}',
'thread.writeStale': 'PR に新しいコミットがあります。新しいヘッドでスレッドを再読み込みします。確認してから再試行してください。',
'thread.writeUnsupported': 'このホストでは、ここからスレッドを変更できません。',
}
/** Spanish copy with the same keys. */
@@ -978,6 +1179,7 @@ export const es: Record<ForgePanelKey, string> = {
'review.approve': 'Aprobar',
'review.requestChanges': 'Solicitar cambios',
'review.summaryRequired': 'Escribe un resumen de la revisión para solicitar cambios.',
'review.ownChangeRequest': 'Este PR es tuyo. GitHub te permite comentarlo, pero no aprobarlo ni solicitar cambios.',
'review.commentOnly': 'Comentar',
'review.drafts': 'Comentarios pendientes ({count})',
'review.edit': 'Editar',
@@ -1123,6 +1325,7 @@ export const es: Record<ForgePanelKey, string> = {
'viewed.changed': 'Cambió tras revisarlo',
'viewed.progress': '{viewed} / {total} revisados',
'viewed.progressAria': 'Archivos revisados',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'No se pudo guardar el estado de revisión',
'commits.all': 'Todos los commits',
'commits.range': '{from}…{to}',
@@ -1146,6 +1349,7 @@ export const es: Record<ForgePanelKey, string> = {
'diff.wrap': 'Ajustar líneas largas',
'diff.nowrap': 'No ajustar líneas largas',
'diff.wrapAria': 'Ajustar líneas',
'diff.moreOptions': 'Más opciones de vista',
'diff.unchanged': '{count} líneas sin cambios',
'diff.unchangedRest': 'Líneas restantes sin cambios',
'diff.newFile': 'Archivo nuevo',
@@ -1239,6 +1443,70 @@ export const es: Record<ForgePanelKey, string> = {
'toast.expandStale': 'El archivo cambió después de leer sus cambios; actualiza antes de expandir',
'toast.prompted': 'Enviado: {text}',
'toast.promptFailed': 'No se pudo enviar el mensaje',
'thread.list': 'Hilos',
'thread.listAria': 'Hilos de revisión, {count} en total',
'thread.close': 'Cerrar la lista de hilos',
'thread.filterAria': 'Filtrar hilos',
'thread.filter.unresolved': 'Sin resolver',
'thread.filter.resolved': 'Resueltos',
'thread.filter.all': 'Todos',
'thread.none': 'Ningún hilo coincide con este filtro',
'thread.empty': 'Aún no hay hilos de revisión',
'thread.back': 'Volver a los cambios',
'thread.truncated': 'Hay demasiados hilos; se muestran los primeros {count}',
'thread.openAll': 'Ver en GitHub',
'thread.replies': '{count} respuestas',
'thread.fileLevel': 'Hilo del archivo',
'thread.onCommit': 'en {commit}',
'thread.originally': 'Originalmente {range}',
'thread.outdatedTag': 'Desactualizado',
'thread.elsewhereTag': 'No está en los commits elegidos',
'thread.author': 'Autor',
'thread.bot': 'bot',
'thread.deletedAuthor': 'Cuenta eliminada',
'thread.resolvedRow': 'Hilo resuelto · {author}',
'thread.expand': 'Expandir',
'thread.collapse': 'Contraer',
'thread.outdatedSection': '{count} hilos desactualizados: commits posteriores cambiaron su código',
'thread.viewOriginal': 'Ver el archivo en ese commit',
'thread.hideOriginal': 'Ocultar el archivo de ese commit',
'thread.originalLoading': 'Leyendo el archivo de ese commit…',
'thread.originalFailed': 'No se pudo leer el archivo de ese commit: {message}',
'thread.openOnHost': 'Ver en GitHub',
'thread.unresolvedCount': '{count} sin resolver',
'thread.unresolvedAria': '{name} tiene {count} hilos sin resolver; ir al siguiente',
'thread.next': 'Ir al siguiente hilo sin resolver',
'thread.treeCount': '{count} hilos sin resolver',
'thread.loadFailed': 'No se pudieron leer los hilos de GitHub: {message}',
'thread.inputFailed': 'El campo de entrada no pudo recibir este hilo; inténtalo más tarde',
'thread.copy': 'Copiar',
'thread.copied': 'Copiado',
'thread.codeBlock': 'Bloque de código',
'thread.wrap': 'Ajustar líneas',
'thread.unwrap': 'No ajustar líneas',
'thread.footnotes': 'Notas a pie de página',
'review.browserDraft': 'Borrador del navegador',
'review.browserDrafts': '{count} borradores de comentarios solo están guardados en este navegador, no en tu revisión pendiente de GitHub. Añádelos a la revisión o elimínalos primero.',
'review.discard': 'Descartar revisión',
'review.discardConfirm': '¿Descartar tu revisión pendiente y sus {count} comentarios? No se puede deshacer.',
'review.discarding': 'Descartando…',
'review.discarded': 'Revisión descartada',
'thread.reply': 'Responder',
'thread.replyPlaceholder': 'Responder…',
'thread.replyActions': 'Opciones de respuesta',
'thread.resolve': 'Resolver hilo',
'thread.unresolve': 'Reabrir hilo',
'thread.commentActions': 'Acciones del comentario de {author}',
'thread.editAria': 'Editar comentario',
'thread.save': 'Guardar',
'thread.saving': 'Guardando…',
'thread.deleting': 'Eliminando…',
'thread.deleteConfirm': '¿Eliminar este comentario?',
'thread.deleteLast': '¿Eliminar este comentario? Es el único del hilo, así que también se elimina el hilo.',
'thread.writeUnknown': 'No se pudo confirmar si GitHub aplicó el cambio. Se están volviendo a leer los hilos; revísalos antes de reintentar.',
'thread.writeFailed': 'GitHub no aplicó el cambio: {message}',
'thread.writeStale': 'El PR tiene nuevos commits. Los hilos se vuelven a leer en el nuevo head; revísalos y reintenta.',
'thread.writeUnsupported': 'Este servicio no admite cambiar hilos desde aquí.',
}
/** French copy with the same keys. */
@@ -1285,6 +1553,7 @@ export const fr: Record<ForgePanelKey, string> = {
'review.approve': 'Approuver',
'review.requestChanges': 'Demander des modifications',
'review.summaryRequired': 'Saisissez un résumé de la revue pour demander des modifications.',
'review.ownChangeRequest': 'Cette PR est la vôtre. GitHub vous permet de la commenter, mais pas de l’approuver ni de demander des modifications.',
'review.commentOnly': 'Commenter',
'review.drafts': 'Commentaires en attente ({count})',
'review.edit': 'Modifier',
@@ -1430,6 +1699,7 @@ export const fr: Record<ForgePanelKey, string> = {
'viewed.changed': 'Modifié depuis la revue',
'viewed.progress': '{viewed} / {total} vus',
'viewed.progressAria': 'Fichiers vus',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'Impossible d’enregistrer l’état de revue',
'commits.all': 'Tous les commits',
'commits.range': '{from}…{to}',
@@ -1453,6 +1723,7 @@ export const fr: Record<ForgePanelKey, string> = {
'diff.wrap': 'Replier les lignes longues',
'diff.nowrap': 'Ne pas replier les lignes longues',
'diff.wrapAria': 'Activer le retour à la ligne',
'diff.moreOptions': 'Plus d’options d’affichage',
'diff.unchanged': '{count} lignes inchangées',
'diff.unchangedRest': 'Lignes inchangées restantes',
'diff.newFile': 'Nouveau fichier',
@@ -1546,6 +1817,70 @@ export const fr: Record<ForgePanelKey, string> = {
'toast.expandStale': 'Le fichier a changé depuis la lecture des modifications ; actualisez avant de développer',
'toast.prompted': 'Envoyé : {text}',
'toast.promptFailed': 'Impossible d’envoyer le message',
'thread.list': 'Fils',
'thread.listAria': 'Fils de revue, {count} au total',
'thread.close': 'Fermer la liste des fils',
'thread.filterAria': 'Filtrer les fils',
'thread.filter.unresolved': 'Non résolus',
'thread.filter.resolved': 'Résolus',
'thread.filter.all': 'Tous',
'thread.none': 'Aucun fil ne correspond à ce filtre',
'thread.empty': 'Aucun fil de revue pour le moment',
'thread.back': 'Retour aux modifications',
'thread.truncated': 'Trop de fils ; seuls les {count} premiers sont affichés',
'thread.openAll': 'Voir sur GitHub',
'thread.replies': '{count} réponses',
'thread.fileLevel': 'Fil du fichier',
'thread.onCommit': 'sur {commit}',
'thread.originally': 'À l’origine {range}',
'thread.outdatedTag': 'Obsolète',
'thread.elsewhereTag': 'Hors des commits choisis',
'thread.author': 'Auteur',
'thread.bot': 'bot',
'thread.deletedAuthor': 'Compte supprimé',
'thread.resolvedRow': 'Fil résolu · {author}',
'thread.expand': 'Développer',
'thread.collapse': 'Réduire',
'thread.outdatedSection': '{count} fils obsolètes : des commits ultérieurs ont modifié leur code',
'thread.viewOriginal': 'Voir le fichier à ce commit',
'thread.hideOriginal': 'Masquer le fichier à ce commit',
'thread.originalLoading': 'Lecture du fichier à ce commit…',
'thread.originalFailed': 'Impossible de lire le fichier à ce commit : {message}',
'thread.openOnHost': 'Voir sur GitHub',
'thread.unresolvedCount': '{count} non résolus',
'thread.unresolvedAria': '{name} a {count} fils non résolus ; aller au suivant',
'thread.next': 'Aller au fil non résolu suivant',
'thread.treeCount': '{count} fils non résolus',
'thread.loadFailed': 'Impossible de lire les fils GitHub : {message}',
'thread.inputFailed': 'Le champ de saisie n’a pas pu recevoir ce fil ; réessayez plus tard',
'thread.copy': 'Copier',
'thread.copied': 'Copié',
'thread.codeBlock': 'Bloc de code',
'thread.wrap': 'Activer le retour à la ligne',
'thread.unwrap': 'Désactiver le retour à la ligne',
'thread.footnotes': 'Notes de bas de page',
'review.browserDraft': 'Brouillon du navigateur',
'review.browserDrafts': '{count} brouillons de commentaires sont enregistrés uniquement dans ce navigateur, pas dans votre revue GitHub en attente. Ajoutez-les à la revue ou supprimez-les d’abord.',
'review.discard': 'Abandonner la revue',
'review.discardConfirm': 'Abandonner votre revue en attente et ses {count} commentaires ? Cette action est irréversible.',
'review.discarding': 'Abandon…',
'review.discarded': 'Revue abandonnée',
'thread.reply': 'Répondre',
'thread.replyPlaceholder': 'Répondre…',
'thread.replyActions': 'Options de réponse',
'thread.resolve': 'Résoudre le fil',
'thread.unresolve': 'Rouvrir le fil',
'thread.commentActions': 'Actions du commentaire de {author}',
'thread.editAria': 'Modifier le commentaire',
'thread.save': 'Enregistrer',
'thread.saving': 'Enregistrement…',
'thread.deleting': 'Suppression…',
'thread.deleteConfirm': 'Supprimer ce commentaire ?',
'thread.deleteLast': 'Supprimer ce commentaire ? C’est le seul du fil, qui sera donc supprimé aussi.',
'thread.writeUnknown': 'Impossible de confirmer que GitHub a appliqué la modification. Les fils sont en cours de relecture ; vérifiez-les avant de réessayer.',
'thread.writeFailed': 'GitHub n’a pas appliqué la modification : {message}',
'thread.writeStale': 'La PR contient de nouveaux commits. Les fils sont relus au nouveau head ; vérifiez-les, puis réessayez.',
'thread.writeUnsupported': 'Ce service ne permet pas de modifier les fils ici.',
}
/** German copy with the same keys. */
@@ -1592,6 +1927,7 @@ export const de: Record<ForgePanelKey, string> = {
'review.approve': 'Genehmigen',
'review.requestChanges': 'Änderungen anfordern',
'review.summaryRequired': 'Gib eine Zusammenfassung des Reviews ein, um Änderungen anzufordern.',
'review.ownChangeRequest': 'Das ist dein eigener PR. GitHub erlaubt Kommentare, aber keine Genehmigung und keine Änderungsanforderung.',
'review.commentOnly': 'Kommentieren',
'review.drafts': 'Ausstehende Kommentare ({count})',
'review.edit': 'Bearbeiten',
@@ -1737,6 +2073,7 @@ export const de: Record<ForgePanelKey, string> = {
'viewed.changed': 'Seit dem Ansehen geändert',
'viewed.progress': '{viewed} / {total} angesehen',
'viewed.progressAria': 'Angesehene Dateien',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'Der Ansichtsstatus konnte nicht gespeichert werden',
'commits.all': 'Alle Commits',
'commits.range': '{from}…{to}',
@@ -1760,6 +2097,7 @@ export const de: Record<ForgePanelKey, string> = {
'diff.wrap': 'Lange Zeilen umbrechen',
'diff.nowrap': 'Lange Zeilen nicht umbrechen',
'diff.wrapAria': 'Zeilen umbrechen',
'diff.moreOptions': 'Weitere Ansichtsoptionen',
'diff.unchanged': '{count} unveränderte Zeilen',
'diff.unchangedRest': 'Übrige unveränderte Zeilen',
'diff.newFile': 'Neue Datei',
@@ -1853,6 +2191,70 @@ export const de: Record<ForgePanelKey, string> = {
'toast.expandStale': 'Die Datei wurde nach dem Lesen der Änderungen verändert; vor dem Aufklappen aktualisieren',
'toast.prompted': 'Gesendet: {text}',
'toast.promptFailed': 'Nachricht konnte nicht gesendet werden',
'thread.list': 'Threads',
'thread.listAria': 'Review-Threads, insgesamt {count}',
'thread.close': 'Threadliste schließen',
'thread.filterAria': 'Threads filtern',
'thread.filter.unresolved': 'Ungelöst',
'thread.filter.resolved': 'Gelöst',
'thread.filter.all': 'Alle',
'thread.none': 'Keine Threads entsprechen diesem Filter',
'thread.empty': 'Noch keine Review-Threads',
'thread.back': 'Zurück zu den Änderungen',
'thread.truncated': 'Zu viele Threads; die ersten {count} werden angezeigt',
'thread.openAll': 'Auf GitHub ansehen',
'thread.replies': '{count} Antworten',
'thread.fileLevel': 'Thread zur Datei',
'thread.onCommit': 'auf {commit}',
'thread.originally': 'Ursprünglich {range}',
'thread.outdatedTag': 'Veraltet',
'thread.elsewhereTag': 'Nicht in den gewählten Commits',
'thread.author': 'Autor',
'thread.bot': 'Bot',
'thread.deletedAuthor': 'Gelöschtes Konto',
'thread.resolvedRow': 'Gelöster Thread · {author}',
'thread.expand': 'Aufklappen',
'thread.collapse': 'Zuklappen',
'thread.outdatedSection': '{count} veraltete Threads: Spätere Commits haben ihren Code geändert',
'thread.viewOriginal': 'Datei in diesem Commit ansehen',
'thread.hideOriginal': 'Datei in diesem Commit ausblenden',
'thread.originalLoading': 'Datei in diesem Commit wird gelesen…',
'thread.originalFailed': 'Die Datei in diesem Commit konnte nicht gelesen werden: {message}',
'thread.openOnHost': 'Auf GitHub ansehen',
'thread.unresolvedCount': '{count} ungelöst',
'thread.unresolvedAria': '{name} hat {count} ungelöste Threads; zum nächsten springen',
'thread.next': 'Zum nächsten ungelösten Thread springen',
'thread.treeCount': '{count} ungelöste Threads',
'thread.loadFailed': 'GitHub-Threads konnten nicht gelesen werden: {message}',
'thread.inputFailed': 'Das Eingabefeld konnte diesen Thread nicht aufnehmen; später erneut versuchen',
'thread.copy': 'Kopieren',
'thread.copied': 'Kopiert',
'thread.codeBlock': 'Codeblock',
'thread.wrap': 'Zeilen umbrechen',
'thread.unwrap': 'Zeilen nicht umbrechen',
'thread.footnotes': 'Fußnoten',
'review.browserDraft': 'Browser-Entwurf',
'review.browserDrafts': '{count} Kommentarentwürfe sind nur in diesem Browser gespeichert, nicht in deiner ausstehenden GitHub-Review. Füge sie zuerst zur Review hinzu oder lösche sie.',
'review.discard': 'Review verwerfen',
'review.discardConfirm': 'Deine ausstehende Review und ihre {count} Kommentare verwerfen? Das lässt sich nicht rückgängig machen.',
'review.discarding': 'Wird verworfen…',
'review.discarded': 'Review verworfen',
'thread.reply': 'Antworten',
'thread.replyPlaceholder': 'Antworten…',
'thread.replyActions': 'Antwortoptionen',
'thread.resolve': 'Thread lösen',
'thread.unresolve': 'Lösung aufheben',
'thread.commentActions': 'Aktionen für den Kommentar von {author}',
'thread.editAria': 'Kommentar bearbeiten',
'thread.save': 'Speichern',
'thread.saving': 'Wird gespeichert…',
'thread.deleting': 'Wird gelöscht…',
'thread.deleteConfirm': 'Diesen Kommentar löschen?',
'thread.deleteLast': 'Diesen Kommentar löschen? Er ist der einzige im Thread, daher wird auch der Thread gelöscht.',
'thread.writeUnknown': 'Es ließ sich nicht bestätigen, ob GitHub die Änderung übernommen hat. Die Threads werden neu gelesen; prüfe sie vor einem erneuten Versuch.',
'thread.writeFailed': 'GitHub hat die Änderung nicht übernommen: {message}',
'thread.writeStale': 'Der PR enthält neue Commits. Die Threads werden am neuen Head neu gelesen; prüfe sie und versuche es erneut.',
'thread.writeUnsupported': 'Dieser Dienst unterstützt hier keine Änderungen an Threads.',
}
/** Russian copy with the same keys. */
@@ -1899,6 +2301,7 @@ export const ru: Record<ForgePanelKey, string> = {
'review.approve': 'Одобрить',
'review.requestChanges': 'Запросить изменения',
'review.summaryRequired': 'Чтобы запросить изменения, добавьте итоговый комментарий.',
'review.ownChangeRequest': 'Это ваш собственный PR. GitHub позволяет его комментировать, но не одобрять и не запрашивать изменения.',
'review.commentOnly': 'Комментарий',
'review.drafts': 'Ожидающие комментарии ({count})',
'review.edit': 'Изменить',
@@ -2044,6 +2447,7 @@ export const ru: Record<ForgePanelKey, string> = {
'viewed.changed': 'Изменён после просмотра',
'viewed.progress': 'Просмотрено {viewed} из {total}',
'viewed.progressAria': 'Просмотренные файлы',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'Не удалось сохранить отметку о просмотре',
'commits.all': 'Все коммиты',
'commits.range': '{from}…{to}',
@@ -2067,6 +2471,7 @@ export const ru: Record<ForgePanelKey, string> = {
'diff.wrap': 'Переносить длинные строки',
'diff.nowrap': 'Не переносить длинные строки',
'diff.wrapAria': 'Переносить строки',
'diff.moreOptions': 'Другие параметры просмотра',
'diff.unchanged': 'Неизменённых строк: {count}',
'diff.unchangedRest': 'Остальные неизменённые строки',
'diff.newFile': 'Новый файл',
@@ -2160,6 +2565,70 @@ export const ru: Record<ForgePanelKey, string> = {
'toast.expandStale': 'Файл изменился после чтения изменений; обновите перед разворачиванием',
'toast.prompted': 'Отправлено: {text}',
'toast.promptFailed': 'Не удалось отправить сообщение',
'thread.list': 'Обсуждения',
'thread.listAria': 'Обсуждения ревью, всего {count}',
'thread.close': 'Закрыть список обсуждений',
'thread.filterAria': 'Фильтр обсуждений',
'thread.filter.unresolved': 'Нерешённые',
'thread.filter.resolved': 'Решённые',
'thread.filter.all': 'Все',
'thread.none': 'Нет обсуждений, подходящих под фильтр',
'thread.empty': 'Обсуждений ревью пока нет',
'thread.back': 'Назад к изменениям',
'thread.truncated': 'Обсуждений слишком много; показаны первые {count}',
'thread.openAll': 'Открыть на GitHub',
'thread.replies': 'Ответов: {count}',
'thread.fileLevel': 'Обсуждение файла',
'thread.onCommit': 'в {commit}',
'thread.originally': 'Изначально {range}',
'thread.outdatedTag': 'Устарело',
'thread.elsewhereTag': 'Нет в выбранных коммитах',
'thread.author': 'Автор',
'thread.bot': 'бот',
'thread.deletedAuthor': 'Удалённая учётная запись',
'thread.resolvedRow': 'Решённое обсуждение · {author}',
'thread.expand': 'Развернуть',
'thread.collapse': 'Свернуть',
'thread.outdatedSection': 'Устаревших обсуждений: {count}. Их код изменили более поздние коммиты',
'thread.viewOriginal': 'Открыть файл в том коммите',
'thread.hideOriginal': 'Скрыть файл в том коммите',
'thread.originalLoading': 'Чтение файла в том коммите…',
'thread.originalFailed': 'Не удалось прочитать файл в том коммите: {message}',
'thread.openOnHost': 'Открыть на GitHub',
'thread.unresolvedCount': 'Нерешённых: {count}',
'thread.unresolvedAria': 'В {name} нерешённых обсуждений: {count}. Перейти к следующему',
'thread.next': 'Перейти к следующему нерешённому обсуждению',
'thread.treeCount': 'Нерешённых обсуждений: {count}',
'thread.loadFailed': 'Не удалось прочитать обсуждения GitHub: {message}',
'thread.inputFailed': 'Не удалось добавить обсуждение в поле ввода; повторите попытку позже',
'thread.copy': 'Копировать',
'thread.copied': 'Скопировано',
'thread.codeBlock': 'Блок кода',
'thread.wrap': 'Переносить строки',
'thread.unwrap': 'Не переносить строки',
'thread.footnotes': 'Сноски',
'review.browserDraft': 'Черновик в браузере',
'review.browserDrafts': 'Черновики комментариев ({count}) сохранены только в этом браузере и не входят в вашу ожидающую проверку на GitHub. Сначала добавьте их в проверку или удалите.',
'review.discard': 'Отменить проверку',
'review.discardConfirm': 'Отменить ожидающую проверку и её комментарии ({count})? Это действие необратимо.',
'review.discarding': 'Отмена…',
'review.discarded': 'Проверка отменена',
'thread.reply': 'Ответить',
'thread.replyPlaceholder': 'Ответить…',
'thread.replyActions': 'Варианты ответа',
'thread.resolve': 'Отметить как решённое',
'thread.unresolve': 'Снять отметку о решении',
'thread.commentActions': 'Действия с комментарием {author}',
'thread.editAria': 'Изменить комментарий',
'thread.save': 'Сохранить',
'thread.saving': 'Сохранение…',
'thread.deleting': 'Удаление…',
'thread.deleteConfirm': 'Удалить этот комментарий?',
'thread.deleteLast': 'Удалить этот комментарий? Он единственный в обсуждении, поэтому обсуждение тоже будет удалено.',
'thread.writeUnknown': 'Не удалось подтвердить, применил ли GitHub изменение. Обсуждения читаются заново; проверьте их перед повторной попыткой.',
'thread.writeFailed': 'GitHub не применил изменение: {message}',
'thread.writeStale': 'В PR появились новые коммиты. Обсуждения будут прочитаны заново для нового head; проверьте их и повторите попытку.',
'thread.writeUnsupported': 'Этот сервис не поддерживает изменение обсуждений отсюда.',
}
/** Portuguese copy with the same keys. */
@@ -2206,6 +2675,7 @@ export const pt: Record<ForgePanelKey, string> = {
'review.approve': 'Aprovar',
'review.requestChanges': 'Solicitar alterações',
'review.summaryRequired': 'Escreva um resumo da revisão para solicitar alterações.',
'review.ownChangeRequest': 'Este PR é seu. O GitHub permite comentá-lo, mas não aprová-lo nem solicitar alterações.',
'review.commentOnly': 'Comentar',
'review.drafts': 'Comentários pendentes ({count})',
'review.edit': 'Editar',
@@ -2351,6 +2821,7 @@ export const pt: Record<ForgePanelKey, string> = {
'viewed.changed': 'Alterado após a revisão',
'viewed.progress': '{viewed} / {total} revisados',
'viewed.progressAria': 'Arquivos revisados',
'viewed.count': '{viewed}/{total}',
'viewed.saveFailed': 'Não foi possível salvar o estado de revisão',
'commits.all': 'Todos os commits',
'commits.range': '{from}…{to}',
@@ -2374,6 +2845,7 @@ export const pt: Record<ForgePanelKey, string> = {
'diff.wrap': 'Quebrar linhas longas',
'diff.nowrap': 'Não quebrar linhas longas',
'diff.wrapAria': 'Quebrar linhas',
'diff.moreOptions': 'Mais opções de exibição',
'diff.unchanged': '{count} linhas sem alterações',
'diff.unchangedRest': 'Demais linhas sem alterações',
'diff.newFile': 'Novo arquivo',
@@ -2467,4 +2939,68 @@ export const pt: Record<ForgePanelKey, string> = {
'toast.expandStale': 'O arquivo mudou após a leitura das alterações; atualize antes de expandir',
'toast.prompted': 'Enviado: {text}',
'toast.promptFailed': 'Não foi possível enviar a mensagem',
'thread.list': 'Discussões',
'thread.listAria': 'Discussões de revisão, {count} no total',
'thread.close': 'Fechar a lista de discussões',
'thread.filterAria': 'Filtrar discussões',
'thread.filter.unresolved': 'Não resolvidas',
'thread.filter.resolved': 'Resolvidas',
'thread.filter.all': 'Todas',
'thread.none': 'Nenhuma discussão corresponde a este filtro',
'thread.empty': 'Ainda não há discussões de revisão',
'thread.back': 'Voltar às alterações',
'thread.truncated': 'Há discussões demais; mostrando as primeiras {count}',
'thread.openAll': 'Ver no GitHub',
'thread.replies': '{count} respostas',
'thread.fileLevel': 'Discussão do arquivo',
'thread.onCommit': 'em {commit}',
'thread.originally': 'Originalmente {range}',
'thread.outdatedTag': 'Desatualizada',
'thread.elsewhereTag': 'Fora dos commits escolhidos',
'thread.author': 'Autor',
'thread.bot': 'bot',
'thread.deletedAuthor': 'Conta excluída',
'thread.resolvedRow': 'Discussão resolvida · {author}',
'thread.expand': 'Expandir',
'thread.collapse': 'Recolher',
'thread.outdatedSection': '{count} discussões desatualizadas: commits posteriores alteraram o código delas',
'thread.viewOriginal': 'Ver o arquivo naquele commit',
'thread.hideOriginal': 'Ocultar o arquivo daquele commit',
'thread.originalLoading': 'Lendo o arquivo naquele commit…',
'thread.originalFailed': 'Não foi possível ler o arquivo naquele commit: {message}',
'thread.openOnHost': 'Ver no GitHub',
'thread.unresolvedCount': '{count} não resolvidas',
'thread.unresolvedAria': '{name} tem {count} discussões não resolvidas; ir para a próxima',
'thread.next': 'Ir para a próxima discussão não resolvida',
'thread.treeCount': '{count} discussões não resolvidas',
'thread.loadFailed': 'Não foi possível ler as discussões do GitHub: {message}',
'thread.inputFailed': 'O campo de entrada não pôde receber esta discussão; tente novamente mais tarde',
'thread.copy': 'Copiar',
'thread.copied': 'Copiado',
'thread.codeBlock': 'Bloco de código',
'thread.wrap': 'Quebrar linhas',
'thread.unwrap': 'Não quebrar linhas',
'thread.footnotes': 'Notas de rodapé',
'review.browserDraft': 'Rascunho do navegador',
'review.browserDrafts': '{count} rascunhos de comentários estão salvos apenas neste navegador, não na sua revisão pendente do GitHub. Adicione-os à revisão ou exclua-os primeiro.',
'review.discard': 'Descartar revisão',
'review.discardConfirm': 'Descartar sua revisão pendente e seus {count} comentários? Esta ação não pode ser desfeita.',
'review.discarding': 'Descartando…',
'review.discarded': 'Revisão descartada',
'thread.reply': 'Responder',
'thread.replyPlaceholder': 'Responder…',
'thread.replyActions': 'Opções de resposta',
'thread.resolve': 'Resolver discussão',
'thread.unresolve': 'Reabrir discussão',
'thread.commentActions': 'Ações do comentário de {author}',
'thread.editAria': 'Editar comentário',
'thread.save': 'Salvar',
'thread.saving': 'Salvando…',
'thread.deleting': 'Excluindo…',
'thread.deleteConfirm': 'Excluir este comentário?',
'thread.deleteLast': 'Excluir este comentário? É o único da discussão, então a discussão também será excluída.',
'thread.writeUnknown': 'Não foi possível confirmar se o GitHub aplicou a alteração. As discussões estão sendo lidas novamente; verifique-as antes de tentar de novo.',
'thread.writeFailed': 'O GitHub não aplicou a alteração: {message}',
'thread.writeStale': 'O PR tem novos commits. As discussões são lidas novamente no novo head; verifique-as e tente de novo.',
'thread.writeUnsupported': 'Este serviço não permite alterar discussões aqui.',
}
@@ -7,19 +7,21 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import { IconBranchOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import { IconBranchOutlineRegular, type QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
import type {} from '@deepseek-ai/dsh-experimental-client-ui-forge/remote'
import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
import type { ForgeChangeRequestListState, ForgeChangeRequestStatesFrame, ForgePanelChangeRequest } from '../types.ts'
import { ReviewQueue } from './review-queue.ts'
import { ViewedFiles } from './viewed-files.ts'
import { formatReviewComment, reviewQuoteSummary, type ReviewSelection } from './review.ts'
import { formatThreadQuote, threadQuoteSummary } from './review-threads.ts'
import { ActionToast } from './ActionToast.tsx'
import { CHANGES_ID, changesDefinition } from './changes-address.ts'
import { createChangesStore } from './changes-store.ts'
@@ -147,16 +149,22 @@ function registerUi(ctx: Context): void {
() => { notices.report('toast.promptFailed') },
)
}
const addReviewToInput = (sessionId: SessionId, selection: ReviewSelection): boolean => {
/** Insert one quote into the Session's main input, numbering it after the quotes of the same heading already there. */
const quoteInInput = (sessionId: SessionId, heading: RegExp, quote: (index: number) => string, summary: QuoteSummary): boolean => {
const scope = ctx.sessions.scope(sessionId)
const conversation = scope?.get('conversation')
if (scope === undefined || conversation === undefined) return false
const input = conversation.input.for(scope)
const numbers = Array.from(input.state.getSnapshot().draft.matchAll(/(?:^|\n)(?:> )?## User Comment (\d+)/g), match => Number(match[1]))
if (!input.insertQuote(formatReviewComment(selection, Math.max(0, ...numbers) + 1), reviewQuoteSummary(selection.comment))) return false
const numbers = Array.from(input.state.getSnapshot().draft.matchAll(heading), match => Number(match[1]))
if (!input.insertQuote(quote(Math.max(0, ...numbers) + 1), summary)) return false
input.focus()
return true
}
const addReviewToInput = (sessionId: SessionId, selection: ReviewSelection): boolean => quoteInInput(sessionId,
/(?:^|\n)(?:> )?## User Comment (\d+)/g, index => formatReviewComment(selection, index), reviewQuoteSummary(selection.comment))
const addThreadToInput = (sessionId: SessionId, thread: ForgeReviewThread, url: string, range: string | null): boolean =>
quoteInInput(sessionId, /(?:^|\n)(?:> )?## Review Thread (\d+)/g, index => formatThreadQuote(thread, url, index),
threadQuoteSummary(thread, range))
/** How toasts name a change request: its number, else its title, else its URL. */
const nameOf = (entry: ForgePanelChangeRequest): string => {
const number = numberOf(entry)
@@ -242,6 +250,10 @@ function registerUi(ctx: Context): void {
viewedFiles: store.viewed,
changeRequestText: (url, commit, path) => ctx.remote.forgePanel.changeRequestText(sessionId, url, commit, path),
addReviewToInput: selection => addReviewToInput(sessionId, selection),
addThreadToInput: (thread, url, range) => addThreadToInput(sessionId, thread, url, range),
changeRequestReview: (url, headSha, fresh, signal) =>
ctx.remote.forgePanel.changeRequestReview(sessionId, url, headSha, fresh, signal),
changeRequestReviewWrite: (url, write) => ctx.remote.forgePanel.changeRequestReviewWrite(sessionId, url, write),
reviewQueue: ({ id, signal }) => {
let queue = store.reviews.get(signal)
if (queue === undefined) {
@@ -265,7 +277,7 @@ function registerUi(ctx: Context): void {
copyPath,
createChangeRequest: () => { createChangeRequest(sessionId) },
report: (key, params) => {
notices.report(key, { tone: key === 'review.published' || key === 'review.submitted' ? 'success' : 'failure',
notices.report(key, { tone: key === 'review.published' || key === 'review.submitted' || key === 'review.discarded' ? 'success' : 'failure',
...params === undefined ? {} : { params } })
},
}
@@ -1,4 +1,7 @@
/** Browser-persisted review drafts and the write whose outcome still needs confirmation. */
/**
* Browser-persisted review records, the review summary, comment drafts an earlier panel kept in the browser, and the
* write whose outcome still needs confirmation. New pull request comments go to the pending review on the code host.
*/
import { z } from 'zod'
import type { ForgeReviewRequest } from '@deepseek-ai/dsh-experimental-forge/types'
@@ -154,16 +157,6 @@ export class ReviewQueue {
return () => { this.listeners.delete(listener) }
}
/**
* Save a frozen PR comment on the whole change request unless a write needs reconciliation.
* @param selection - frozen PR comment.
* @returns whether it was saved; a comment on chosen commits is refused.
*/
add(selection: ReviewSelection): boolean {
if (selection.source.kind !== 'change' || selection.source.commits !== null || this.state.uncertain !== null) return false
return this.save({ ...this.state, comments: [...this.state.comments, selection] })
}
/**
* Edit or remove a pending comment without changing its captured lines.
* @param index - comment position.
@@ -0,0 +1,204 @@
/**
* Where the changes view shows each review thread of a change request, the order a file shows them in, which threads
* each filter of the thread list keeps, and the composer quote of a whole thread.
*/
import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ForgeAnchor, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import type { ForgeCommitRange, ForgeDiffFile, ForgeDiffHunk } from '../types.ts'
import { hunkRows } from './diff-rows.ts'
/** The changes a view shows, which decides where a thread can sit. */
export interface ThreadView {
/** Head commit the threads were read at. */
readonly head: string
/** Commit the shown changes end at: the head, or the last chosen commit. */
readonly end: string
/** Chosen consecutive commits, or null for the whole change request. */
readonly commits: ForgeCommitRange | null
}
/**
* Where a thread shows in the changes view: on lines of one side, at the top of its file, in its file's outdated
* section, or nowhere in the file because the chosen commits do not hold the lines it is on.
*/
export type ThreadPlace =
| { readonly kind: 'line'; readonly side: 'L' | 'R'; readonly startLine: number; readonly endLine: number }
| { readonly kind: 'file' }
| { readonly kind: 'outdated' }
| { readonly kind: 'elsewhere' }
/** One filter of the thread list: the threads by whether they are resolved. */
export type ThreadFilter = 'unresolved' | 'resolved' | 'all'
/** Filters of the thread list in display order. */
export const THREAD_FILTERS: readonly ThreadFilter[] = ['unresolved', 'resolved', 'all']
/**
* Place a thread in a view. The whole change request shows a thread at its position on the head. Chosen commits show
* only a new-side thread whose lines number the file at the last chosen commit: its position on the head when the
* commits end at the head, else the lines it was written on at that commit. The old side of chosen commits starts
* at the parent of the first commit, which no thread position numbers.
* @param thread - the thread.
* @param view - the shown changes.
* @returns where the thread shows.
*/
export function placeThread(thread: ForgeReviewThread, view: ThreadView): ThreadPlace {
if (thread.subject === 'file') return { kind: 'file' }
if (view.commits === null) return thread.current === null ? { kind: 'outdated' } : onLines(thread.side, thread.current)
if (thread.side === 'R' && thread.current !== null && view.end === view.head) return onLines('R', thread.current)
if (thread.side === 'R' && thread.original !== null && thread.original.commit === view.end) return onLines('R', thread.original)
return thread.current === null ? { kind: 'outdated' } : { kind: 'elsewhere' }
}
function onLines(side: 'L' | 'R', anchor: ForgeAnchor): ThreadPlace {
return { kind: 'line', side, startLine: anchor.startLine, endLine: anchor.endLine }
}
/**
* Name a side and lines, such as `R12` or `L3–5`.
* @param side - old or new side.
* @param anchor - the lines.
* @returns the range label.
*/
export function anchorRange(side: 'L' | 'R', anchor: Pick<ForgeAnchor, 'startLine' | 'endLine'>): string {
return `${side}${anchor.startLine}${anchor.endLine === anchor.startLine ? '' : `–${anchor.endLine}`}`
}
/** Where a line of a diff file is: in the collapsed lines before a hunk or after the last one, or in a hunk. */
type LineSpot = { readonly kind: 'gap'; readonly index: number } | { readonly kind: 'hunk'; readonly index: number; readonly hunk: ForgeDiffHunk }
function spotOf(file: ForgeDiffFile, side: 'L' | 'R', line: number): LineSpot {
for (const [index, hunk] of file.hunks.entries()) {
const start = side === 'L' ? hunk.oldStart : hunk.newStart
const count = side === 'L' ? hunk.oldLines : hunk.newLines
if (line < start) return { kind: 'gap', index }
if (line < start + count) return { kind: 'hunk', index, hunk }
}
return { kind: 'gap', index: file.hunks.length }
}
/**
* Find the collapsed unchanged lines that hold a line: the index of the hunk they precede, or the hunk count after the last hunk.
* @param file - the diff file.
* @param side - side the line numbers.
* @param line - the line.
* @returns the gap index, or undefined when a hunk shows the line.
*/
export function gapOf(file: ForgeDiffFile, side: 'L' | 'R', line: number): number | undefined {
const spot = spotOf(file, side, line)
return spot.kind === 'gap' ? spot.index : undefined
}
/**
* Order a file's threads as its section shows them: threads on the whole file, then threads on lines by the row of their
* last line, then outdated threads, then threads the chosen commits do not show. Threads on unchanged lines sort
* by the collapsed lines that hold them.
* @param items - threads of one file with their places.
* @param file - the file's diff, or undefined when the shown changes lack the file.
* @returns the threads in display order.
*/
export function inFileOrder<Item extends { readonly place: ThreadPlace }>(items: readonly Item[], file: ForgeDiffFile | undefined): Item[] {
const rank = ({ place }: Item): readonly [number, number, number] => {
switch (place.kind) {
case 'file': return [0, 0, 0]
case 'line': return [1, ...rowOf(file, place.side, place.endLine)]
case 'outdated': return [2, 0, 0]
case 'elsewhere': return [3, 0, 0]
/* v8 ignore next -- closed ThreadPlace union exhaustiveness guard */
default: return assertNever(place, 'ThreadPlace')
}
}
const keyed = items.map(item => [rank(item), item] as const)
return keyed.toSorted(([a], [b]) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]).map(([, item]) => item)
}
/**
* Where a line draws: twice the index of the collapsed lines that hold it, or twice a hunk's index plus one with the
* line's row in that hunk, so rows of one hunk keep their patch order across both sides.
*/
function rowOf(file: ForgeDiffFile | undefined, side: 'L' | 'R', line: number): readonly [number, number] {
if (file === undefined) return [0, line]
const spot = spotOf(file, side, line)
if (spot.kind === 'gap') return [2 * spot.index, line]
return [2 * spot.index + 1, hunkRows(spot.hunk).findIndex(row => (side === 'L' ? row.old : row.new) === line)]
}
/**
* Whether a thread passes a filter of the thread list.
* @param thread - the thread.
* @param filter - the filter.
* @returns whether the list shows the thread.
*/
export function passesFilter(thread: ForgeReviewThread, filter: ThreadFilter): boolean {
switch (filter) {
case 'unresolved': return !thread.resolved
case 'resolved': return thread.resolved
case 'all': return true
/* v8 ignore next -- closed ThreadFilter union exhaustiveness guard */
default: return assertNever(filter, 'ThreadFilter')
}
}
/** Lines of a recorded diff hunk shown before its last line, beside the lines the thread is on. */
const EXCERPT_CONTEXT = 3
/**
* Cut a recorded diff hunk to its header and the lines that end it: the thread's lines on its side plus a few before.
* GitHub records the hunk up to the thread's last line.
* @param hunk - the recorded hunk, header first.
* @param side - side the thread's lines number.
* @param lines - how many lines the thread covers.
* @returns the header and the kept lines.
*/
export function hunkExcerpt(hunk: string, side: 'L' | 'R', lines: number): { readonly header: string | null; readonly lines: readonly string[] } {
const header = hunk.startsWith('@@') ? hunk.split('\n', 1).join('') : null
const body = (header === null ? hunk : hunk.slice(header.length + 1)).split('\n')
const other = side === 'L' ? '+' : '-'
const kept: string[] = []
let wanted = lines + EXCERPT_CONTEXT
for (const line of body.toReversed()) {
if (wanted === 0) break
kept.push(line)
if (!line.startsWith(other)) wanted -= 1
}
return { header, lines: kept.reverse() }
}
/**
* Describe a composer quote of a thread by its file, range, and first comment.
* @param thread - the quoted thread.
* @param range - the thread's range label, or null for a file thread.
* @returns the composer's display of the quote.
*/
export function threadQuoteSummary(thread: ForgeReviewThread, range: string | null): QuoteSummary {
const name = thread.path.slice(thread.path.lastIndexOf('/') + 1)
return { label: range === null ? name : `${name} ${range}`, title: thread.path, detail: range ?? thread.path, body: thread.comments[0]?.body ?? '' }
}
/**
* Format a whole thread for the ordinary, logged user message. Comment bodies are quoted line by line, so their
* Markdown cannot add headings to the message.
* @param thread - the thread.
* @param url - web page of the change request.
* @param index - one-based thread number in the composer.
* @returns Markdown content for an atomic composer quote.
*/
export function formatThreadQuote(thread: ForgeReviewThread, url: string, index: number): string {
const anchor = thread.current ?? thread.original
const lines = anchor === null ? '' : anchor.startLine === anchor.endLine ? `${anchor.startLine}` : `${anchor.startLine}-${anchor.endLine}`
// Old-side lines number the file at the diff's base, so the quote names the commit only as where that diff ends.
const where = thread.subject === 'file' || anchor === null ? 'Lines: whole file'
: thread.side === 'R' ? `Side: R\nLines: ${lines}\nCommit: ${anchor.commit}`
: `Side: L (old side: the lines number the file before the pull request's changes)\nLines: ${lines}\nDiff head: ${anchor.commit}`
const state = [thread.resolved ? 'resolved' : 'unresolved', ...thread.subject === 'line' && thread.current === null ? ['outdated'] : []].join(', ')
const fence = thread.diffHunk === null ? '' : '`'.repeat(Math.max(3, ...Array.from(thread.diffHunk.matchAll(/`+/g), match => match[0].length + 1)))
const hunk = thread.diffHunk === null ? '' : `Diff hunk:\n${fence}diff\n${thread.diffHunk}\n${fence}\n`
// A blank comment line becomes a bare `>` and comments follow one another without blank lines, since the composer
// quotes every line of the reference again.
const comments = thread.comments.map(comment => `${comment.author === null ? 'Unknown author' : `@${comment.author.login}`} (${comment.createdAt}):\n`
+ comment.body.split('\n').map(line => line.trim() === '' ? '>' : `> ${line}`).join('\n')).join('\n')
const link = thread.comments[0]?.url ?? url
return `## Review Thread ${index}\nFile: ${thread.path}\n${where}\nState: ${state}\nSource: ${link}\n${hunk}Comments:\n${comments}`
}
@@ -0,0 +1,127 @@
/** Reads the review threads of the change request a changes view shows and places them in its files. */
import { useEffect, useMemo, useRef, useState } from 'react'
import type { ForgeReviewData, ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type { LineThread } from './ReviewThreads.tsx'
import { placeThread, type ThreadPlace, type ThreadView } from './review-threads.ts'
/** What the changes view knows about its change request when it reads threads. */
export interface ThreadReadInput {
/** Whether the view is visible; a hidden view reads nothing. */
readonly visible: boolean
/** Binding URL of the change request, or null for local changes. */
readonly url: string | null
/** Head commit of the latest status, or null before one. */
readonly head: string | null
/** Update time of the latest status, or null before one. */
readonly updatedAt: string | null
/** Epoch milliseconds of the latest status, so every status asks the Host again; the Host answers from memory until the threads age. */
readonly statusAt: number | null
/** Changes on each refresh. */
readonly attempt: number
/** Changes after each write that may have changed the threads, which the Host no longer answers from memory. */
readonly revision: number
/** Read the threads at a head commit; `fresh` skips the threads the host keeps. */
readonly read: (url: string, headSha: string, fresh: boolean, signal: AbortSignal) => Promise<RemoteResult<ForgeReviewData>>
}
/** The last threads read and why the latest read failed. */
export interface ThreadReadState {
/** Threads of the last successful read for the URL, at any head, or null. */
readonly review: ForgeReviewData | null
/** Message of the latest failed read, or null, also when the provider cannot read reviews. */
readonly failure: string | null
}
/**
* Read the threads at the head of each status while the view is visible. A read refused because the head moved
* keeps the previous threads; the next status names the new head and reads again. The first read after a refresh
* asks the host to skip the threads it keeps, which a resolved thread leaves unchanged.
* @param input - the change request and the reader.
* @returns the last threads and the latest failure.
*/
export function useThreadRead(input: ThreadReadInput): ThreadReadState {
const { visible, url, head, updatedAt, statusAt, attempt, revision, read } = input
const [state, setState] = useState<ThreadReadState & { readonly url: string | null }>({ url: null, review: null, failure: null })
const readAttempt = useRef(attempt)
useEffect(() => {
if (!visible || url === null || head === null) return
const fresh = readAttempt.current !== attempt
readAttempt.current = attempt
const controller = new AbortController()
void read(url, head, fresh, controller.signal).then((result) => {
if (controller.signal.aborted) return
if (result.ok) {
setState({ url, review: result.value, failure: null })
return
}
const { code, message } = result.error
if (code === 'forgePanel/stale-head') return
setState(previous => ({ url, review: previous.url === url ? previous.review : null,
failure: code === 'forgePanel/review-unsupported' ? null : message }))
})
return () => { controller.abort() }
}, [visible, url, head, updatedAt, statusAt, attempt, revision, read])
return state.url === url ? state : { review: null, failure: null }
}
/** Threads of one file grouped by where they show, and how many of them are unresolved. */
export interface PlacedFileThreads {
readonly lines: readonly LineThread[]
readonly file: readonly ForgeReviewThread[]
readonly outdated: readonly ForgeReviewThread[]
readonly unresolved: number
}
/** One thread and where the shown changes place it. */
export interface PlacedThread {
readonly thread: ForgeReviewThread
readonly place: ThreadPlace
}
/** Every thread with its place and the threads of each file. */
export interface PlacedThreads {
/** Every thread in host order with its place. */
readonly entries: readonly PlacedThread[]
/** Threads of each path. */
readonly files: ReadonlyMap<string, PlacedFileThreads>
/** Unresolved threads by path, for the file tree. */
readonly unresolved: ReadonlyMap<string, number>
}
const NONE: PlacedThreads = { entries: [], files: new Map(), unresolved: new Map() }
/**
* Place the threads of a review in the shown changes.
* @param review - threads read at the head of the latest status, or null.
* @param view - the shown changes, or null before they load.
* @returns places, per-file groups, and unresolved counts.
*/
export function usePlacedThreads(review: ForgeReviewData | null, view: ThreadView | null): PlacedThreads {
const commits = view?.commits ?? null
const end = view?.end ?? null
return useMemo(() => {
if (review === null || end === null) return NONE
const entries: PlacedThread[] = []
const files = new Map<string, { lines: LineThread[]; file: ForgeReviewThread[]; outdated: ForgeReviewThread[]; unresolved: number }>()
const unresolved = new Map<string, number>()
for (const thread of review.threads) {
const place = placeThread(thread, { head: review.headSha, end, commits })
entries.push({ thread, place })
let group = files.get(thread.path)
if (group === undefined) {
group = { lines: [], file: [], outdated: [], unresolved: 0 }
files.set(thread.path, group)
}
if (place.kind === 'line') group.lines.push({ thread, place })
else if (place.kind === 'file') group.file.push(thread)
else if (place.kind === 'outdated') group.outdated.push(thread)
if (!thread.resolved) {
group.unresolved += 1
unresolved.set(thread.path, group.unresolved)
}
}
return { entries, files, unresolved }
}, [review, end, commits])
}
@@ -0,0 +1,70 @@
/** Width-driven folding of the changes toolbar into its More menu. */
/** Fold levels, from none to the deepest: level 1 folds the line totals, expansion, side by side, and wrapping; level 2
* the test switch, with the progress shown as a ring; level 3 refresh. */
export const DEEPEST_FOLD = 3
/**
* Read the fold level a toolbar shows.
* @param inside - an element inside the toolbar, such as its More button.
* @returns the level, or the deepest level outside a measured toolbar.
*/
export function foldOf(inside: Element): number {
const level = Number.parseInt(inside.closest('[data-fold]')?.getAttribute('data-fold') ?? '', 10)
return Number.isInteger(level) ? level : DEEPEST_FOLD
}
/**
* Width the row's displayed items need on one line: each item but the spacer at its own width, and one column gap
* between neighbours, the spacer included.
* @param row - the toolbar row.
* @param gap - its column gap in pixels.
* @returns the width in pixels.
*/
function demand(row: HTMLElement, gap: number): number {
let width = 0
let items = 0
for (const child of row.children) {
const spacer = child.hasAttribute('data-fold-spacer')
const own = spacer ? 0 : child.getBoundingClientRect().width
if (!spacer && own === 0) continue
width += own
items += 1
}
return width + Math.max(0, items - 1) * gap
}
/**
* Keep a toolbar row on one line by setting `data-fold` to the shallowest level whose items fit, measuring each level's
* demand synchronously; the row's styles hide each level's items and show the More button. Content, size, and font
* changes measure again.
* @param row - the toolbar row; its children are the items, and the one with `data-fold-spacer` takes the slack.
* @returns Disconnect the observers and the font listener.
*/
export function observeToolbarFold(row: HTMLElement): () => void {
const resize = new ResizeObserver(() => { measure() })
const measure = (): void => {
// Items React adds after the first measure are observed too; observing an observed element again does nothing.
for (const child of row.children) resize.observe(child)
const style = getComputedStyle(row)
const available = row.getBoundingClientRect().width - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight)
const gap = parseFloat(style.columnGap)
let level = 0
for (; level < DEEPEST_FOLD; level += 1) {
row.setAttribute('data-fold', String(level))
if (demand(row, gap) <= available) break
}
row.setAttribute('data-fold', String(level))
}
resize.observe(row)
const mutation = new MutationObserver(measure)
mutation.observe(row, { subtree: true, childList: true, characterData: true })
const fonts = document.fonts
fonts.addEventListener('loadingdone', measure)
measure()
return () => {
resize.disconnect()
mutation.disconnect()
fonts.removeEventListener('loadingdone', measure)
}
}
@@ -6,8 +6,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-api-remote-access'
import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
import type {
ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewRequest, ForgeReviewResult,
MergeMethod,
ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeLineComment, ForgeReviewData,
ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeMethod,
} from '@deepseek-ai/dsh-experimental-forge'
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
@@ -30,6 +30,7 @@ import { rangeStart } from './commit-range.ts'
import { ATTRIBUTES_PATH, FileLayers } from './layers.ts'
import { missingWorktree, SessionPanel } from './panel.ts'
import { PatchCache } from './patch-cache.ts'
import { ReviewCache } from './review-cache.ts'
import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts'
import type { PanelConfig } from './panel.ts'
import type {
@@ -85,6 +86,8 @@ export class ForgePanelController extends TypertRemoteService {
maxCommits: z.number().default(250),
testPaths: z.array(z.string()).default([]),
interfacePaths: z.array(z.string()).default([]),
maxCachedReviewBytes: z.number().default(16_777_216),
reviewRefreshMs: z.number().default(60_000),
})
private readonly home: Context
@@ -94,6 +97,7 @@ export class ForgePanelController extends TypertRemoteService {
private creations!: WorktreeCreations
private readonly patches: PatchCache
private readonly layers: FileLayers
private readonly reviews: ReviewCache
private states: ChangeRequestStates | undefined
private readonly stopPanels: () => Promise<void>
private readonly stopStates: () => Promise<void>
@@ -102,13 +106,13 @@ export class ForgePanelController extends TypertRemoteService {
super(ctx, 'forgePanel')
const resolved = config as Required<Config>
if (resolved.gitCommand.trim().length === 0) throw new Error('forge-panel: gitCommand must not be empty')
for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs'] as const) {
for (const key of ['gitTimeoutMs', 'graceMs', 'maxOutputBytes', 'readinessTimeoutMs', 'reviewRefreshMs'] as const) {
const value = resolved[key]
if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`)
}
}
for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits'] as const) {
for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits', 'maxCachedReviewBytes'] as const) {
if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`)
}
if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name')
@@ -119,6 +123,7 @@ export class ForgePanelController extends TypertRemoteService {
this.home = ctx
this.config = resolved
this.patches = new PatchCache(resolved.maxCachedDiffBytes)
this.reviews = new ReviewCache(resolved.maxCachedReviewBytes, resolved.reviewRefreshMs)
this.stopPanels = ctx.effect(() => async () => {
const panels = [...this.panels.values()]
this.panels.clear()
@@ -457,7 +462,48 @@ export class ForgePanelController extends TypertRemoteService {
}
/**
* Publish a line comment or completed review for a visible Session binding.
* Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read
* at the same head commit and update time are reused from memory, for any Session, until they are
* `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read
* again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull
* request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param headSha - head commit of the displayed diff.
* @param fresh - whether to read from the host even when threads at this head and update time are kept, as after the
* reader refreshes the view; the result replaces the kept threads.
* @param signal - request cancellation.
* @returns the threads at `headSha`, with `current` positions numbering the files of that diff.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
* `forgePanel/stale-head` when the latest status or the host names another head, which a host answer polls again;
* `forgePanel/review-unsupported` when the provider cannot read reviews; `forgePanel/review-failed` before the
* status was read and when the host does not provide the threads otherwise.
*/
@Remote
async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise<ForgeReviewData> {
signal.throwIfAborted()
const { ref, update } = this.bound(session, url)
if (update === null || !('snapshot' in update)) {
throw new RemoteError('forgePanel/review-failed', 'The change request status has not been read yet', {})
}
if (update.snapshot.headSha !== headSha) {
throw new RemoteError('forgePanel/stale-head', `The change request head moved from ${headSha} to ${update.snapshot.headSha}`, {})
}
const key = changeRequestKey(ref)
const version = JSON.stringify([headSha, update.snapshot.updatedAt])
const readAt = Date.now()
const kept = fresh ? undefined : this.reviews.get(key, version, readAt)
if (kept !== undefined) return kept
const token = this.reviews.token()
const review = await this.home.forge.readReview(ref, headSha, signal)
if ('code' in review) throw reviewError(review)
this.reviews.set(key, version, review, readAt, token)
return review
}
/**
* Publish a line comment or completed review for a visible Session binding. The threads kept for the change request
* are dropped once the host answers, so the next read shows the comments.
* @param session - Session retaining the change request.
* @param url - visible binding URL.
* @param request - reviewed head, ranges, plain text, and explicit review decision.
@@ -468,13 +514,43 @@ export class ForgePanelController extends TypertRemoteService {
async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult> {
signal.throwIfAborted()
const { ref } = this.bound(session, url)
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(request.headSha)) throw new Error('Invalid review commit')
if (!isCommit(request.headSha)) throw new Error('Invalid review commit')
const comments = request.kind === 'comment' ? [request.comment] : request.comments
if (comments.some(comment => comment.path === '' || comment.body.trim() === ''
|| !Number.isSafeInteger(comment.startLine) || comment.startLine < 1
|| !Number.isSafeInteger(comment.endLine) || comment.endLine < comment.startLine)) throw new Error('Invalid review comment')
if (!comments.every(validComment)) throw new Error('Invalid review comment')
if (request.kind === 'review' && request.event !== 'approve' && request.body.trim() === '' && comments.length === 0) throw new Error('Empty review')
return await this.home.forge.submitReview(ref, request, signal)
try {
return await this.home.forge.submitReview(ref, request, signal)
} finally {
this.reviews.drop(changeRequestKey(ref))
}
}
/**
* Write to the review threads or the pending review of a change request of a Session while its head is still the
* head the user saw. The threads kept for the change request are dropped once the host answers, so the next read
* shows the write, which a resolve does not show through a GitHub pull request's update time.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param write - the write and the head commit of the threads the user saw.
* @param signal - request cancellation.
* @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and
* `unknown` when the outcome must be checked on the host before the write is tried again.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error
* for a write without text, a head that is not a commit object name, or an invalid line range.
*/
@Remote
async changeRequestReviewWrite(
session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal,
): Promise<ForgeReviewWriteResult> {
signal.throwIfAborted()
const { ref } = this.bound(session, url)
if (!isCommit(write.headSha)) throw new Error('Invalid review commit')
if (!validWrite(write)) throw new Error('Invalid review write')
try {
return await this.home.forge.writeReview(ref, write, signal)
} finally {
this.reviews.drop(changeRequestKey(ref))
}
}
/**
@@ -836,6 +912,44 @@ export class ForgePanelController extends TypertRemoteService {
}
}
/**
* Whether a value names a full commit object name.
* @param value - the value from the browser.
* @returns whether it is 40 or 64 hexadecimal digits.
*/
function isCommit(value: string): boolean {
return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value)
}
/**
* Whether a line comment from the browser names a path, consecutive positive lines, and text.
* @param comment - the comment.
* @returns whether a provider may write it.
*/
function validComment(comment: ForgeLineComment): boolean {
return comment.path !== '' && comment.body.trim() !== '' && Number.isSafeInteger(comment.startLine) && comment.startLine >= 1
&& Number.isSafeInteger(comment.endLine) && comment.endLine >= comment.startLine
}
/**
* Whether a review write from the browser names its target and carries text where the write needs it.
* @param write - the write.
* @returns whether a provider may perform it.
*/
function validWrite(write: ForgeReviewWrite): boolean {
switch (write.kind) {
case 'reply': return write.thread !== '' && write.body.trim() !== ''
case 'resolve': return write.thread !== ''
case 'edit-comment': return write.comment !== '' && write.body.trim() !== ''
case 'delete-comment': return write.comment !== ''
case 'add-pending': return validComment(write.comment)
case 'submit-pending': return write.review !== '' && (write.event !== 'request-changes' || write.body.trim() !== '')
case 'discard-pending': return write.review !== ''
/* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */
default: return assertNever(write, 'ForgeReviewWrite.kind')
}
}
/**
* Report why the code host did not provide a diff or file.
* @param failure - the provider's failure.
@@ -848,12 +962,32 @@ function readError(failure: ForgeFailure): RemoteError {
case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
case 'not-found':
case 'unauthenticated':
case 'unsupported':
case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {})
/* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
default: return assertNever(failure.code, 'ForgeFailure.code')
}
}
/**
* Report why the code host did not provide review threads.
* @param failure - the provider's failure.
* @returns `forgePanel/stale-head` for a head that moved, `forgePanel/review-unsupported` for a provider without
* review reads, else `forgePanel/review-failed`, with the provider's message.
*/
function reviewError(failure: ForgeFailure): RemoteError {
switch (failure.code) {
case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {})
case 'unsupported': return new RemoteError('forgePanel/review-unsupported', failure.message, {})
case 'not-found':
case 'unauthenticated':
case 'too-large':
case 'unavailable': return new RemoteError('forgePanel/review-failed', failure.message, {})
/* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */
default: return assertNever(failure.code, 'ForgeFailure.code')
}
}
/**
* Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, a missing base branch, and chosen
* commits that are not on the branch as Remote errors.
@@ -0,0 +1,98 @@
/**
* Review threads of change requests kept in memory, so the changes view reads them from the code host again only
* after the change request's head or update time changes, the kept threads reach their age limit, or a review write drops them.
*/
import { Buffer } from 'node:buffer'
import type { ChangeRequestKey, ForgeReviewData } from '@deepseek-ai/dsh-experimental-forge'
interface Entry {
/** Head commit and update time the threads were read at. */
readonly version: string
readonly review: ForgeReviewData
/** Epoch milliseconds of the read. */
readonly readAt: number
/** UTF-8 size of the threads as JSON. */
readonly bytes: number
}
/**
* One read of review threads per change request, bounded by age and by the total UTF-8 size of the kept reads as
* JSON; the least recently read change request leaves first. A read that started before a drop of any change request
* is not kept, so threads read before a write never replace the drop.
*/
export class ReviewCache {
private readonly entries = new Map<ChangeRequestKey, Entry>()
private bytes = 0
/** Number of drops so far. */
private drops = 0
/**
* @param maxBytes - most UTF-8 bytes kept together; a larger read is not kept.
* @param maxAgeMs - age in milliseconds at which a kept read is no longer returned.
*/
constructor(private readonly maxBytes: number, private readonly maxAgeMs: number) {}
/**
* Read the threads kept for a change request at a version while they are younger than the age limit, marking them
* the most recently read.
* @param key - the change request.
* @param version - head commit and update time the reader needs.
* @param now - current epoch milliseconds.
* @returns the threads, or undefined when none are kept at that version or they reached the age limit.
*/
get(key: ChangeRequestKey, version: string, now: number): ForgeReviewData | undefined {
const entry = this.entries.get(key)
if (entry?.version !== version || now - entry.readAt >= this.maxAgeMs) return undefined
this.entries.delete(key)
this.entries.set(key, entry)
return entry.review
}
/**
* Name the cache's state when a read starts, for {@link ReviewCache.set}.
* @returns the token of the read.
*/
token(): number {
return this.drops
}
/**
* Keep a read in place of the change request's earlier one, then drop the least recently read change requests
* until the rest fit within `maxBytes`. A read whose token a drop outdated is not kept.
* @param key - the change request.
* @param version - head commit and update time the threads were read at.
* @param review - the threads.
* @param readAt - epoch milliseconds when the read started.
* @param token - what {@link ReviewCache.token} returned when the read started.
*/
set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number, token: number): void {
if (token !== this.drops) return
this.forget(key)
const bytes = Buffer.byteLength(JSON.stringify(review))
if (bytes > this.maxBytes) return
this.entries.set(key, { version, review, readAt, bytes })
this.bytes += bytes
for (const [oldest, entry] of this.entries) {
if (this.bytes <= this.maxBytes) break
this.entries.delete(oldest)
this.bytes -= entry.bytes
}
}
/**
* Forget the threads kept for a change request, and every read in flight, after a write changed them.
* @param key - the change request.
*/
drop(key: ChangeRequestKey): void {
this.drops += 1
this.forget(key)
}
private forget(key: ChangeRequestKey): void {
const previous = this.entries.get(key)
if (previous === undefined) return
this.entries.delete(key)
this.bytes -= previous.bytes
}
}
@@ -414,6 +414,13 @@ export interface Config {
* `testPaths` and before the built-in rules.
*/
interfacePaths?: string[]
/** Most UTF-8 bytes, as JSON, of change request review threads kept in memory for later reads at the same head commit and update time. */
maxCachedReviewBytes?: number
/**
* Age in milliseconds at which review threads kept in memory are read from the code host again; a GitHub pull
* request's update time does not change when a thread is resolved.
*/
reviewRefreshMs?: number
}
declare module '@deepseek-ai/dsh-typert-protocol' {
@@ -438,8 +445,9 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
'forgePanel/not-bound': Record<string, never>
/**
* The change request's head is no longer the commit the request named: the head the user confirmed for a merge,
* the head displayed for complete checks, or the head of the latest status for a diff. A diff read polls the change
* request again at once, so a later status names the current head.
* the head displayed for complete checks, the head of the latest status for a diff, or the head of the displayed
* diff for review threads. A diff or review read the host refuses polls the change request again at once, so a
* later status names the current head.
*/
'forgePanel/stale-head': Record<string, never>
/** The code host refused the change or could not be reached; the message gives the host's reason. */
@@ -468,6 +476,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
'forgePanel/commits-missing': Record<string, never>
/** A chosen commit after the first lacks the commit listed before it as its first parent, so two ends cannot name the run. */
'forgePanel/commits-not-linear': Record<string, never>
/** The code host's provider cannot read review threads, so the changes view shows none. */
'forgePanel/review-unsupported': Record<string, never>
/** The code host did not provide the change request's review threads, or its status has not been read yet; the message says why. */
'forgePanel/review-failed': Record<string, never>
}
}
@@ -3,6 +3,7 @@
import { useSyncExternalStore } from 'react'
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import './fonts-dom.client.ts'
import type { PaneId, SidebarRightTabActions, SidebarRightTabInfo, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
@@ -23,8 +24,11 @@ import baseCss from '../src/client/BaseMenu.module.css'
import type {
ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelChangeRequest, ForgePanelState,
} from '../src/types.ts'
import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types'
import type {
ChangeRequestKey, ForgeCommitList, ForgeReviewData, ForgeReviewId, ForgeReviewThread, ForgeReviewWriteResult, ForgeThreadId,
} from '@deepseek-ai/dsh-experimental-forge/types'
import { entry, ready, snapshot } from './client-fixtures.client.ts'
import { reviewComment, reviewThread } from './thread-fixtures.client.ts'
const t = makeTranslate(en)
const SESSION = SessionId('s1')
@@ -127,6 +131,22 @@ function ok<T>(value: T): RemoteResult<T> {
return { ok: true, value }
}
/** Threads of #7 at its head, none of them yet, read for `lin`, who may review the change request `octo` opened. */
function reviewData(overrides: Partial<ForgeReviewData> = {}): ForgeReviewData {
return { headSha: HEAD, viewer: 'lin', threads: [], truncated: false, pendingReview: null, viewerCanReview: true, ...overrides }
}
/** The pending review of `octo` on #7. */
const PENDING_REVIEW = { id: 'review-1' as ForgeReviewId, comments: 1 }
/** Store comment drafts the way an earlier panel kept them in the browser. */
function storeDrafts(...bodies: string[]): void {
const drafts = bodies.map(body => ({ source: { kind: 'change', url: URL7, headSha: HEAD, commits: null },
comment: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, body,
hunk: '@@ -3,3 +3,4 @@\n const a3 = 3\n-const x = 4\n+const y = 4\n+const z = 5\n const a5 = 6' } }))
localStorage.setItem('test-review', JSON.stringify({ comments: drafts, records: [], body: '', event: 'comment', uncertain: null }))
}
/** Refused Remote reads, by what the Host said. */
const REFUSED = {
noForkPoint: { ok: false, error: new RemoteError('forgePanel/no-fork-point', 'no fork point', {}) },
@@ -138,6 +158,9 @@ const REFUSED = {
staleHead: { ok: false, error: new RemoteError('forgePanel/stale-head', 'the head moved', {}) },
hostRefused: { ok: false, error: new RemoteError('forgePanel/diff-failed', 'diff too large', {}) },
failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) },
reviewUnsupported: { ok: false, error: new RemoteError('forgePanel/review-unsupported', 'no review reads', {}) },
reviewFailed: { ok: false, error: new RemoteError('forgePanel/review-failed', 'GitHub is down', {}) },
notBound: { ok: false, error: new RemoteError('forgePanel/not-bound', 'not bound', {}) },
} satisfies Record<string, RemoteResult<never>>
/**
@@ -239,6 +262,9 @@ function mount(options: MountOptions = {}) {
reviewQueue: vi.fn<ChangesTabInjected['reviewQueue']>().mockReturnValue(new ReviewQueue('test-review')),
submitReview: vi.fn<ChangesTabInjected['submitReview']>().mockResolvedValue({ ok: true, value: { ok: true, url: URL7 } }),
addReviewToInput: vi.fn<ChangesTabInjected['addReviewToInput']>().mockReturnValue(true),
addThreadToInput: vi.fn<ChangesTabInjected['addThreadToInput']>().mockReturnValue(true),
changeRequestReview: vi.fn<ChangesTabInjected['changeRequestReview']>(async () => REFUSED.reviewUnsupported),
changeRequestReviewWrite: vi.fn<ChangesTabInjected['changeRequestReviewWrite']>(async () => ok<ForgeReviewWriteResult>({ ok: true })),
createChangeRequest: vi.fn<ChangesTabInjected['createChangeRequest']>(),
report: vi.fn<ChangesTabInjected['report']>(),
}
@@ -964,10 +990,11 @@ describe('ChangesTab layout', () => {
expect(m.store.getSnapshot().byTab[TAB]?.navigated).toBe(3)
})
it('says when a scope has no changes', async () => {
const m = mount({ setup: (faces) => { faces.localDiff.mockResolvedValue(ok({ base: null, files: [], omitted: 0 })) } })
it('says when a scope has no changes, where a navigation to a file scrolls nothing', async () => {
const m = mount({ params: { path: 'src/app.ts' }, setup: (faces) => { faces.localDiff.mockResolvedValue(ok({ base: null, files: [], omitted: 0 })) } })
await settle()
expect(m.view.getByText(en['diff.empty'])).toBeTruthy()
expect(scrolled).not.toHaveBeenCalled()
expect(m.view.getByRole('button', { name: 'All 0 files' }).hasAttribute('disabled')).toBe(true)
expect(m.view.getByRole('button', { name: en['diff.expandAll'] }).hasAttribute('disabled')).toBe(true)
expect(m.view.queryByRole('status')).toBeNull()
@@ -1286,7 +1313,10 @@ describe('ChangesTab change requests', () => {
describe('line review actions', () => {
async function comment(options: MountOptions = {}) {
const m = mount({ source: { kind: 'change', url: URL7 }, ...options })
const m = mount({ source: { kind: 'change', url: URL7 }, ...options, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData()))
options.setup?.(faces)
} })
await settle()
const section = within(m.section('src/app.ts'))
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
@@ -1419,42 +1449,249 @@ describe('line review actions', () => {
expect(m.faces.submitReview).not.toHaveBeenCalled()
expect(m.faces.createChangeRequest).not.toHaveBeenCalled()
})
it('queues comments and submits them together with the selected review decision', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, state: ready({ changeRequests: [entry(7, snapshot(7))] }) })
it('adds comments to the pending review on the code host and submits it with the selected review decision', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, state: ready({ changeRequests: [entry(7, snapshot(7))] }),
setup: (faces) => { faces.changeRequestReview.mockResolvedValue(ok(reviewData())) } })
await settle()
const section = within(m.section('src/app.ts'))
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
fireEvent.change(section.getByRole('textbox'), { target: { value: 'Please fix' } })
m.faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
fireEvent.click(section.getByRole('button', { name: 'Start review' }))
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenCalledWith(URL7, { kind: 'add-pending', headSha: HEAD,
comment: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, body: 'Please fix' } })
expect(m.faces.submitReview).not.toHaveBeenCalled()
const pending = within(m.section('src/app.ts').querySelector('[data-forge-review-thread="pending"]')!)
expect(pending.getByText('Please fix')).toBeTruthy()
fireEvent.click(pending.getByRole('button', { name: 'Edit' }))
fireEvent.change(pending.getByRole('textbox'), { target: { value: 'Please fix the guard' } })
fireEvent.click(pending.getByRole('button', { name: 'Done' }))
expect(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }).getSnapshot().comments).toEqual([])
expect(section.queryByRole('textbox')).toBeNull()
// The write drops the Host's kept threads, so the view reads them again and finds the pending review.
expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2)
fireEvent.click(section.getByRole('button', { name: 'Select line R5' }))
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
expect(section.getByRole('button', { name: 'Add to review' })).toBeTruthy()
fireEvent.click(section.getByRole('button', { name: 'Cancel' }))
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const dialog = within(m.view.getByRole('dialog', { name: 'Submit review' }))
expect(dialog.getAllByRole('textbox')).toHaveLength(1)
expect(dialog.queryByText('Please fix the guard')).toBeNull()
fireEvent.change(m.view.getByRole('textbox', { name: 'Review summary…' }), { target: { value: 'Needs a fix' } })
fireEvent.click(m.view.getByRole('radio', { name: 'Request changes' }))
fireEvent.click(m.view.getByRole('button', { name: 'Submit review' }))
fireEvent.change(dialog.getByRole('textbox', { name: 'Review summary…' }), { target: { value: 'Needs a fix' } })
fireEvent.click(dialog.getByRole('radio', { name: 'Request changes' }))
m.faces.changeRequestReview.mockResolvedValue(ok(reviewData()))
fireEvent.click(dialog.getByRole('button', { name: 'Submit review' }))
await settle()
expect(m.faces.submitReview).toHaveBeenCalledWith(URL7, expect.objectContaining({ kind: 'review', event: 'request-changes', body: 'Needs a fix', headSha: HEAD,
comments: [expect.objectContaining({ path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, body: 'Please fix the guard' })] }))
expect(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }).getSnapshot().comments).toEqual([])
expect(m.section('src/app.ts').querySelector('[data-forge-review-thread="published"]')?.textContent).toContain('Please fix the guard')
expect(m.faces.changeRequestReviewWrite).toHaveBeenLastCalledWith(URL7,
{ kind: 'submit-pending', headSha: HEAD, review: 'review-1', event: 'request-changes', body: 'Needs a fix' })
expect(m.faces.report).toHaveBeenCalledWith('review.submitted')
expect(m.view.queryByRole('dialog')).toBeNull()
expect(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }).getSnapshot()).toMatchObject({ body: '', event: 'comment' })
expect(m.view.getByRole('button', { name: 'Submit review' })).toBeTruthy()
})
it('keeps a pending comment editable when its file leaves the diff', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, state: ready({ changeRequests: [entry(7, snapshot(7))] }) })
it('keeps the dialog and says why the code host did not take the submission or the discard', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
faces.changeRequestReviewWrite.mockResolvedValueOnce(ok({ ok: false, code: 'failed', message: 'Review is empty' }))
.mockResolvedValueOnce(ok({ ok: false, code: 'stale', message: 'moved' }))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const dialog = within(m.view.getByRole('dialog', { name: 'Submit review' }))
fireEvent.click(dialog.getByRole('button', { name: 'Submit review' }))
await settle()
expect(dialog.getByRole('alert').textContent).toBe(t('thread.writeFailed', { message: 'Review is empty' }))
fireEvent.click(dialog.getByRole('button', { name: 'Discard review' }))
fireEvent.click(within(dialog.getByRole('group', { name: 'Discard review' })).getByRole('button', { name: 'Discard review' }))
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenLastCalledWith(URL7, { kind: 'discard-pending', headSha: HEAD, review: 'review-1' })
expect(dialog.getByRole('alert').textContent).toBe(en['thread.writeStale'])
expect(m.faces.report).not.toHaveBeenCalled()
fireEvent.click(within(dialog.getByRole('group', { name: 'Discard review' })).getByRole('button', { name: 'Discard review' }))
await settle()
expect(m.faces.report).toHaveBeenCalledWith('review.discarded')
expect(m.view.queryByRole('dialog')).toBeNull()
})
it('submits a pending review once when two activations arrive in the same render batch', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const button = within(m.view.getByRole('dialog')).getByRole('button', { name: 'Submit review' })
act(() => { button.click(); button.click() })
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenCalledOnce()
})
it('refuses a local reference passed to the pending review callback', async () => {
const renderDiff = DiffFileModule.DiffFile.type
let queue: ReviewActions['queue']
vi.spyOn(DiffFileModule.DiffFile, 'type').mockImplementation((props) => {
queue = props.review?.queue
return renderDiff(props)
})
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => { faces.changeRequestReview.mockResolvedValue(ok(reviewData())) } })
await settle()
expect(queue).toBeDefined()
expect(await queue!({ source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null, commits: null }, comment: {
path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, hunk: '', body: 'Local reference',
} })).toBe(en['review.stale'])
expect(m.faces.changeRequestReviewWrite).not.toHaveBeenCalled()
})
it('keeps a pending review submission whose outcome is unknown blocked until the reader checks GitHub', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
faces.changeRequestReviewWrite.mockResolvedValueOnce(ok({ ok: false, code: 'unknown', message: 'timeout' }))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const dialog = within(m.view.getByRole('dialog'))
fireEvent.change(dialog.getByRole('textbox', { name: 'Review summary…' }), { target: { value: 'Looks good' } })
// The submission went through: the pending review no longer reads.
m.faces.changeRequestReview.mockResolvedValue(ok(reviewData()))
fireEvent.click(dialog.getByRole('button', { name: 'Submit review' }))
await settle()
const records = m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal })
expect(records.getSnapshot().uncertain).toEqual({ kind: 'review', headSha: HEAD, event: 'comment', body: 'Looks good', comments: [] })
expect(dialog.getByRole('alert').textContent).toBe(en['thread.writeUnknown'])
expect(dialog.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
expect(m.faces.submitReview).not.toHaveBeenCalled()
fireEvent.click(dialog.getByRole('button', { name: 'Checked; allow resubmission' }))
expect(records.getSnapshot().uncertain).toBeNull()
})
it('refuses to submit the pending review when the browser cannot keep the submission for reconciliation', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
vi.spyOn(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }), 'begin').mockReturnValue(false)
fireEvent.click(within(m.view.getByRole('dialog')).getByRole('button', { name: 'Submit review' }))
await settle()
expect(m.faces.changeRequestReviewWrite).not.toHaveBeenCalled()
expect(within(m.view.getByRole('dialog')).getByRole('alert').textContent).toBe(en['review.saveFailed'])
})
it('reports a summary the browser could not clear after the code host took the submission', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
vi.spyOn(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }), 'finish').mockReturnValue(false)
fireEvent.click(within(m.view.getByRole('dialog')).getByRole('button', { name: 'Submit review' }))
await settle()
expect(m.faces.report.mock.calls.map(call => call[0])).toEqual(['review.saveFailed', 'review.submitted'])
})
it.each([
['an unsupported write', ok<ForgeReviewWriteResult>({ ok: false, code: 'unsupported', message: 'no writes' }), en['thread.writeUnsupported'], 1],
['a refused write', ok<ForgeReviewWriteResult>({ ok: false, code: 'failed', message: 'Locked' }), t('thread.writeFailed', { message: 'Locked' }), 2],
['a stale write', ok<ForgeReviewWriteResult>({ ok: false, code: 'stale', message: 'moved' }), en['thread.writeStale'], 1],
['an unknown write', ok<ForgeReviewWriteResult>({ ok: false, code: 'unknown', message: 'timeout' }), en['thread.writeUnknown'], 2],
['an unbound change request', REFUSED.notBound, t('thread.writeFailed', { message: 'not bound' }), 1],
['a lost connection', REFUSED.failed, en['thread.writeUnknown'], 2],
] as const)('keeps the comment after %s, reading the threads again only when they may have changed', async (_label, answer, message, reads) => {
const m = await comment({ setup: (faces) => { faces.changeRequestReviewWrite.mockResolvedValueOnce(answer) } })
fireEvent.click(m.sectionQueries.getByRole('button', { name: 'Start review' }))
await settle()
expect(m.sectionQueries.getByRole('alert').textContent).toBe(message)
expect(m.sectionQueries.getByRole('textbox')).toHaveProperty('value', 'Check the guard')
expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(reads)
})
it('sends writes one at a time, so a second waits for the pending review the first starts', async () => {
storeDrafts('First', 'Second')
const first = deferred<RemoteResult<ForgeReviewWriteResult>>()
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData()))
faces.changeRequestReviewWrite.mockReturnValueOnce(first.promise)
} })
await settle()
const drafts = [...m.section('src/app.ts').querySelectorAll<HTMLElement>('[data-forge-review-thread="pending"]')]
for (const draft of drafts) fireEvent.click(within(draft).getByRole('button', { name: 'Add to review' }))
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenCalledTimes(1)
first.settle(ok({ ok: false, code: 'failed', message: 'Busy' }))
await settle()
expect(m.faces.changeRequestReviewWrite.mock.calls.map(call => call[1].kind === 'add-pending' ? call[1].comment.body : null))
.toEqual(['First', 'Second'])
expect(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }).getSnapshot().comments.map(item => item.comment.body)).toEqual(['First'])
})
it('offers no single comment while a pending review exists, which GitHub refuses', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ pendingReview: PENDING_REVIEW })))
} })
await settle()
const section = within(m.section('src/app.ts'))
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
fireEvent.change(section.getByRole('textbox'), { target: { value: 'Keep this draft' } })
fireEvent.click(section.getByRole('button', { name: 'Start review' }))
expect(section.getByRole('button', { name: 'Add to review' })).toBeTruthy()
expect(section.queryByRole('button', { name: 'GitHub comment options' })).toBeNull()
})
it('lets the author of the change request only comment in the review dialog', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ viewer: 'OCTO', pendingReview: PENDING_REVIEW })))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const dialog = within(m.view.getByRole('dialog'))
expect(dialog.getByText(en['review.ownChangeRequest'])).toBeTruthy()
expect(dialog.getByRole('radio', { name: 'Approve' })).toHaveProperty('disabled', true)
})
it.each([
['another reviewer', 'reviewer'],
['an unnamed viewer', null],
] as const)('lets %s choose every review decision', async (_label, viewer) => {
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ viewer, pendingReview: PENDING_REVIEW })))
} })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
const dialog = within(m.view.getByRole('dialog'))
expect(dialog.queryByText(en['review.ownChangeRequest'])).toBeNull()
expect(dialog.getByRole('radio', { name: 'Approve' })).toHaveProperty('disabled', false)
})
it('offers no pending review action while the threads are unread, the user may not review, or chosen commits show', async () => {
const unread = mount({ source: { kind: 'change', url: URL7 } })
await settle()
const section = within(unread.section('src/app.ts'))
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
fireEvent.click(section.getByRole('button', { name: 'Add comment' }))
expect(section.queryByRole('button', { name: 'Start review' })).toBeNull()
expect(section.getByRole('button', { name: 'Publish single comment' })).toBeTruthy()
unread.view.unmount()
const barred = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => {
faces.changeRequestReview.mockResolvedValue(ok(reviewData({ viewerCanReview: false })))
} })
await settle()
const barredSection = within(barred.section('src/app.ts'))
fireEvent.click(barredSection.getByRole('button', { name: 'Select line R4' }))
fireEvent.click(barredSection.getByRole('button', { name: 'Add comment' }))
expect(barredSection.queryByRole('button', { name: 'Start review' })).toBeNull()
})
it('moves a browser draft into the pending review at the head it was written on', async () => {
storeDrafts('Kept from before')
const m = mount({ source: { kind: 'change', url: URL7 }, setup: (faces) => { faces.changeRequestReview.mockResolvedValue(ok(reviewData())) } })
await settle()
const draft = within(m.section('src/app.ts').querySelector('[data-forge-review-thread="pending"]')!)
expect(draft.getByText(en['review.browserDraft'])).toBeTruthy()
expect(m.view.getByRole('button', { name: 'Submit review (1)' })).toBeTruthy()
fireEvent.click(draft.getByRole('button', { name: 'Add to review' }))
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenCalledWith(URL7, { kind: 'add-pending', headSha: HEAD,
comment: { path: 'src/app.ts', side: 'R', startLine: 4, endLine: 4, body: 'Kept from before' } })
expect(m.faces.reviewQueue({ id: TAB, signal: m.aborter.signal }).getSnapshot().comments).toEqual([])
})
it('publishes browser drafts as one review while the user has no pending review', async () => {
storeDrafts('Kept from before')
const m = mount({ source: { kind: 'change', url: URL7 } })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Submit review (1)' }))
fireEvent.click(within(m.view.getByRole('dialog')).getByRole('button', { name: 'Submit review' }))
await settle()
expect(m.faces.submitReview).toHaveBeenCalledWith(URL7, expect.objectContaining({ kind: 'review', event: 'comment', body: '',
comments: [expect.objectContaining({ body: 'Kept from before' })] }))
expect(m.section('src/app.ts').querySelector('[data-forge-review-thread="published"]')?.textContent).toContain('Kept from before')
})
it('keeps a browser draft editable when its file leaves the diff', async () => {
storeDrafts('Keep this draft')
const m = mount({ source: { kind: 'change', url: URL7 }, state: ready({ changeRequests: [entry(7, snapshot(7))] }) })
await settle()
m.faces.changeRequestDiff.mockResolvedValue(ok({ ...CHANGE, files: [] }))
fireEvent.click(m.view.getByRole('button', { name: 'Refresh changes' }))
await settle()
@@ -1465,7 +1702,10 @@ describe('line review actions', () => {
})
it('retains an uncertain write across tab remount and requires explicit reconciliation', async () => {
const m = mount({ source: { kind: 'change', url: URL7 }, state: ready({ changeRequests: [entry(7, snapshot(7))] }),
setup: (faces) => { faces.submitReview.mockResolvedValue({ ok: true, value: { ok: false, code: 'unknown', message: 'timeout' } }) } })
setup: (faces) => {
faces.submitReview.mockResolvedValue({ ok: true, value: { ok: false, code: 'unknown', message: 'timeout' } })
faces.changeRequestReview.mockResolvedValue(ok(reviewData()))
} })
await settle()
const section = within(m.section('src/app.ts'))
fireEvent.click(section.getByRole('button', { name: 'Select line R4' }))
@@ -1692,3 +1932,324 @@ describe('ChangesTab commits', () => {
expect(m.view.queryByRole('button', { name: /^Commits shown/ })).toBeNull()
})
})
describe('ChangesTab review threads', () => {
const source: ChangesSource = { kind: 'change', url: URL7 }
const OLD = 'b'.repeat(40)
const LARGE = file('logs/large.txt', { status: 'added', additions: 1001,
hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 1001, lines: Array.from({ length: 1001 }, (_, index) => `+${index}`) }] })
const FILES = [APP, NOTES, GONE, LOGO, BIG, MOVED, LARGE]
const line = (id: string, path: string, side: 'L' | 'R', at: number, overrides: Partial<ForgeReviewThread> = {}): ForgeReviewThread => reviewThread({
id: id as ForgeThreadId, path, side,
current: { commit: HEAD, startLine: at, endLine: at }, original: { commit: HEAD, startLine: at, endLine: at },
comments: [reviewComment({ body: `Comment ${id}` })], ...overrides,
})
const THREADS: ForgeReviewThread[] = [
line('on-row', 'src/app.ts', 'R', 4, { comments: [reviewComment({ body: 'Comment on-row', author: { login: 'octo', avatarUrl: null, bot: false } }),
reviewComment({ body: 'Reply', author: { login: 'lin', avatarUrl: null, bot: false } })] }),
line('old-side', 'src/app.ts', 'L', 11),
line('in-gap', 'src/app.ts', 'R', 8),
line('resolved', 'src/app.ts', 'R', 5, { resolved: true }),
line('outdated', 'src/app.ts', 'R', 0, { current: null, original: { commit: OLD, startLine: 9, endLine: 9 } }),
reviewThread({ id: 'file-thread' as ForgeThreadId, path: 'docs/notes.txt', subject: 'file', current: null, original: null, diffHunk: null,
comments: [reviewComment({ body: 'Comment file-thread' })] }),
line('beyond', 'docs/gone.txt', 'L', 3),
line('binary', 'assets/logo.png', 'R', 1),
line('oversized', 'logs/big.log', 'R', 1),
line('renamed', 'lib/b.txt', 'R', 1),
line('large', 'logs/large.txt', 'R', 1),
line('missing', 'src/missing.ts', 'R', 1),
line('missing-no-url', 'src/missing.ts', 'R', 2, { comments: [reviewComment({ url: null })] }),
]
const REVIEW: ForgeReviewData = { headSha: HEAD, viewer: 'octo', threads: THREADS, truncated: false, pendingReview: null, viewerCanReview: false }
const reviewed = (review: ForgeReviewData = REVIEW) => (faces: Faces): void => {
faces.changeRequestDiff.mockImplementation(async () => ok({ ...CHANGE, files: FILES }))
faces.changeRequestReview.mockImplementation(async () => ok(review))
}
/** Binding of #7 at the head whose latest status settled at `fetchedAt`. */
const polledAt = (fetchedAt: number): ForgePanelChangeRequest => {
const bound = entry(7, snapshot(7))
return { ...bound, update: { key: 'github:github.com/octo/demo#7' as ChangeRequestKey, fetchedAt, snapshot: snapshot(7) } }
}
const card = (m: ReturnType<typeof mount>, id: string): HTMLElement | null => m.view.container.querySelector(`[data-forge-thread="${id}"]`)
/** The element a thread places among the rows: its card, or side by side, the row of comment cells that holds it. */
const placed = (m: ReturnType<typeof mount>, id: string): Element | null => {
const found = card(m, id)
return found?.closest('[data-forge-notes]') ?? found
}
/** Code of the row a thread follows, on the side its lines number. */
const following = (m: ReturnType<typeof mount>, id: string, side: 'L' | 'R' = 'R'): string | null =>
placed(m, id)?.previousElementSibling?.querySelector(side === 'L' ? '[data-old-line]' : '[data-new-line]')?.textContent ?? null
/** The column of a side-by-side row that holds a thread: 0 for the left side, 1 for the right. */
const column = (m: ReturnType<typeof mount>, id: string): number => {
const found = card(m, id)!
return Array.from(found.closest('[data-forge-notes]')!.children).findIndex(cell => cell.contains(found))
}
it('writes to a thread at the head of its read and reads the threads again', async () => {
const writable = line('on-row', 'src/app.ts', 'R', 4, { viewerCanResolve: true })
const m = mount({ source, setup: reviewed({ ...REVIEW, threads: [writable], pendingReview: { id: 'review-1' as ForgeReviewId, comments: 2 } }) })
await settle()
expect(m.view.getByRole('button', { name: 'Submit review (2)' })).toBeTruthy()
fireEvent.click(within(card(m, 'on-row')!).getByRole('button', { name: 'Resolve thread' }))
await settle()
expect(m.faces.changeRequestReviewWrite).toHaveBeenCalledWith(URL7, { kind: 'resolve', thread: 'on-row', resolved: true, headSha: HEAD })
expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2)
})
it('reads threads at the head of the latest status and places them on rows, gaps, files, and outdated sections', async () => {
const m = mount({ source, setup: reviewed() })
await settle()
expect(m.faces.changeRequestReview).toHaveBeenCalledWith(URL7, HEAD, false, expect.any(AbortSignal))
const app = m.section('src/app.ts')
expect(following(m, 'on-row')).toBe('const y = 4')
expect(following(m, 'old-side', 'L')).toBe('const w = 12')
// Side by side, each thread sits in the column of the side its lines number.
expect([column(m, 'on-row'), column(m, 'old-side')]).toEqual([1, 0])
expect(card(m, 'in-gap')?.previousElementSibling?.getAttribute('data-forge-diff-gap')).toBe('1')
expect(card(m, 'resolved')?.textContent).toContain('Resolved thread · reviewer')
// The count alone shows below 480px.
expect([...within(app).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' }).children]
.map(text => text.textContent)).toEqual(['4 unresolved', '4'])
expect(app.querySelector('[data-forge-outdated-threads]')?.textContent).toContain('1 outdated threads')
fireEvent.click(within(card(m, 'outdated')!).getByRole('button', { name: en['thread.viewOriginal'] }))
expect(m.faces.changeRequestText).toHaveBeenLastCalledWith(URL7, OLD, 'src/app.ts')
expect(m.section('docs/notes.txt').firstElementChild?.nextElementSibling?.getAttribute('data-forge-thread')).toBe('file-thread')
expect(m.section('docs/gone.txt').querySelector(`.${css.code}`)?.lastElementChild?.getAttribute('data-forge-thread')).toBe('beyond')
for (const id of ['binary', 'oversized', 'renamed', 'large']) expect(card(m, id)).not.toBeNull()
expect(within(m.view.getByRole('navigation')).getByTitle('4 unresolved threads').textContent).toBe('4')
fireEvent.click(within(app).getByRole('button', { name: '4 unchanged lines' }))
await settle()
expect(following(m, 'in-gap')).toBe('const a7 = 8')
fireEvent.click(within(card(m, 'on-row')!).getByRole('button', { name: en['review.addToInput'] }))
expect(m.faces.addThreadToInput).toHaveBeenCalledWith(THREADS[0], URL7, 'R4')
m.faces.addThreadToInput.mockReturnValue(false)
fireEvent.click(within(card(m, 'on-row')!).getByRole('button', { name: en['review.addToInput'] }))
expect(m.faces.report).toHaveBeenLastCalledWith('thread.inputFailed')
})
it('opens the thread list, filters it by resolution, and opens each thread at its place', async () => {
const m = mount({ source, setup: reviewed({ ...REVIEW, truncated: true }) })
await settle()
const toggle = m.view.getByRole('button', { name: 'Review threads, 13 in total' })
fireEvent.click(toggle)
const list = m.view.getByRole('complementary', { name: 'Review threads, 13 in total' })
expect(within(list).getAllByRole('radio').map(radio => `${radio.textContent} ${radio.getAttribute('aria-checked')}`))
.toEqual(['Unresolved12 true', 'Resolved1 false', 'All13 false'])
expect(within(list).getByText(/^Too many threads; showing the first 13/)).toBeDefined()
expect(within(list).getByRole('heading', { name: 'src/app.ts' })).toBeDefined()
expect([...list.querySelectorAll('[data-forge-thread-group]')].map(group => group.getAttribute('data-forge-thread-group')))
.toEqual(['assets/logo.png', 'docs/gone.txt', 'docs/notes.txt', 'lib/b.txt', 'logs/big.log', 'logs/large.txt', 'src/app.ts', 'src/missing.ts'])
expect(list.querySelector('[data-forge-thread-item="resolved"]')).toBeNull()
scrolled.mockClear()
fireEvent.click(list.querySelector('[data-forge-thread-item="on-row"]')!)
expect(scrolled.mock.contexts).toContain(card(m, 'on-row'))
expect(list.isConnected).toBe(true)
fireEvent.click(within(list).getByRole('radio', { name: /^Resolved/ }))
expect([...list.querySelectorAll('[data-forge-thread-item]')].map(item => item.getAttribute('data-forge-thread-item'))).toEqual(['resolved'])
fireEvent.click(list.querySelector('[data-forge-thread-item="resolved"]')!)
expect(card(m, 'resolved')?.tagName).toBe('SECTION')
fireEvent.click(within(list).getByRole('radio', { name: /^All/ }))
fireEvent.click(list.querySelector('[data-forge-thread-item="missing"]')!)
expect(m.faces.openLink).toHaveBeenLastCalledWith(THREADS[11]?.comments[0]?.url)
m.faces.openLink.mockClear()
fireEvent.click(list.querySelector('[data-forge-thread-item="missing-no-url"]')!)
expect(m.faces.openLink).not.toHaveBeenCalled()
fireEvent.click(within(list).getByRole('button', { name: en['thread.openAll'] }))
expect(m.faces.openLink).toHaveBeenLastCalledWith(URL7)
fireEvent.keyDown(list, { key: 'Enter' })
expect(list.isConnected).toBe(true)
fireEvent.keyDown(list, { key: 'Escape' })
expect(m.view.queryByRole('complementary')).toBeNull()
expect(document.activeElement).toBe(toggle)
fireEvent.click(toggle)
fireEvent.click(within(m.view.getByRole('complementary')).getByRole('button', { name: en['thread.close'] }))
expect(m.view.queryByRole('complementary')).toBeNull()
fireEvent.click(toggle)
fireEvent.click(within(m.view.getByRole('complementary')).getByRole('button', { name: en['thread.back'] }))
expect(m.view.queryByRole('complementary')).toBeNull()
fireEvent.click(toggle)
fireEvent.click(m.view.getByRole('complementary').previousElementSibling!)
expect(m.view.queryByRole('complementary')).toBeNull()
})
it('steps through a file\'s unresolved threads in display order from the count in its header', async () => {
const m = mount({ source, setup: reviewed() })
await settle()
const shown: (string | undefined)[] = []
for (let step = 0; step < 5; step += 1) {
scrolled.mockClear()
fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' }))
await settle()
shown.push((scrolled.mock.contexts as HTMLElement[]).find(element => element.dataset.forgeThread !== undefined)?.dataset.forgeThread)
}
// R4 in the first hunk, R8 in the unchanged lines after it, L11 in the second hunk, then the outdated thread, then R4 again.
expect(shown).toEqual(['on-row', 'in-gap', 'old-side', 'outdated', 'on-row'])
expect(m.view.queryByRole('complementary')).toBeNull()
})
it('takes the focus where the thread list covers the files, and closes it before opening a thread', async () => {
// The narrow-view styles float the list; jsdom computes this rule in their place.
const style = document.createElement('style')
style.textContent = '[data-forge-thread-list] { position: absolute; }'
document.head.append(style)
try {
const m = mount({ source, setup: reviewed() })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 13 in total' }))
const list = m.view.getByRole('complementary')
expect(document.activeElement).toBe(list)
scrolled.mockClear()
fireEvent.click(list.querySelector('[data-forge-thread-item="on-row"]')!)
expect(m.view.queryByRole('complementary')).toBeNull()
expect(scrolled.mock.contexts).toContain(card(m, 'on-row'))
expect(document.activeElement).toBe(card(m, 'on-row'))
} finally {
style.remove()
}
})
it('places only the threads whose lines number the last chosen commit, and shows the others after choosing all commits', async () => {
const two = '2'.repeat(40)
const threads = [line('at-head', 'src/app.ts', 'R', 4), line('written-on-two', 'src/app.ts', 'R', 3, { current: null, original: { commit: two, startLine: 3, endLine: 3 } })]
const m = mount({ source, setup: (faces) => {
faces.changeRequestDiff.mockImplementation(async (_url, commits) => ok({ ...CHANGE, headSha: commits?.to ?? HEAD }))
faces.changeRequestReview.mockImplementation(async () => ok({ ...REVIEW, threads }))
} })
await settle()
m.store.actions.committed(TAB, { from: two, to: two })
await settle()
expect(card(m, 'at-head')).toBeNull()
expect(following(m, 'written-on-two')).toBe('const a3 = 3')
fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 2 in total' }))
const list = m.view.getByRole('complementary')
expect(list.querySelector('[data-forge-thread-item="at-head"]')?.textContent).toContain(en['thread.elsewhereTag'])
fireEvent.click(list.querySelector('[data-forge-thread-item="at-head"]')!)
expect(m.store.getSnapshot().byTab[TAB]?.commits).toBeNull()
await settle()
expect(following(m, 'at-head')).toBe('const y = 4')
})
it('chooses all commits for a thread on a file the chosen commits do not change, rather than opening it on the host', async () => {
const two = '2'.repeat(40)
const m = mount({ source, setup: (faces) => {
faces.changeRequestDiff.mockImplementation(async (_url, commits) =>
ok(commits === null ? CHANGE : { ...CHANGE, headSha: commits.to, files: [APP] }))
faces.changeRequestReview.mockImplementation(async () => ok({ ...REVIEW, threads: [line('notes', 'docs/notes.txt', 'R', 2)] }))
} })
await settle()
m.store.actions.committed(TAB, { from: two, to: two })
await settle()
expect(m.view.container.querySelector('[data-forge-diff-file="docs/notes.txt"]')).toBeNull()
fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 1 in total' }))
fireEvent.click(m.view.getByRole('complementary').querySelector('[data-forge-thread-item="notes"]')!)
expect(m.store.getSnapshot().byTab[TAB]?.commits).toBeNull()
expect(m.faces.openLink).not.toHaveBeenCalled()
scrolled.mockClear()
await settle()
expect(scrolled.mock.contexts).toContain(card(m, 'notes'))
})
it('draws a file a thread jump targets before its section comes within reach, and keeps it drawn', async () => {
// A double that never reports a section as reached, as for files far below the scrollport.
vi.stubGlobal('IntersectionObserver', class {
observe(): void {}
unobserve(): void {}
disconnect(): void {}
})
try {
const m = mount({ source, setup: reviewed() })
await settle()
expect(m.section('src/app.ts').querySelector('[data-forge-diff-unreached]')).not.toBeNull()
scrolled.mockClear()
fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' }))
await settle()
expect(m.section('src/app.ts').querySelector('[data-forge-diff-unreached]')).toBeNull()
expect(scrolled.mock.contexts).toContain(card(m, 'on-row'))
expect(m.section('docs/notes.txt').querySelector('[data-forge-diff-unreached]')).not.toBeNull()
} finally {
vi.unstubAllGlobals()
}
})
it('stops a later jump to a file at its header once a thread jump there has ended', async () => {
const m = mount({ source, setup: reviewed() })
await settle()
fireEvent.click(within(m.section('src/app.ts')).getByRole('button', { name: 'app.ts has 4 unresolved threads; go to the next one' }))
await settle()
scrolled.mockClear()
fireEvent.click(within(m.view.getByRole('navigation')).getByRole('button', { name: 'src/app.ts' }))
await settle()
expect(scrolled.mock.contexts).toEqual([m.section('src/app.ts')])
})
it('keeps the thread list for a truncated read that kept no thread, so its note stays reachable', async () => {
const m = mount({ source, setup: reviewed({ ...REVIEW, threads: [], truncated: true }) })
await settle()
fireEvent.click(m.view.getByRole('button', { name: 'Review threads, 0 in total' }))
expect(within(m.view.getByRole('complementary')).getByText(/^Too many threads; showing the first 0/)).toBeDefined()
})
it('shows threads only at the head the diff and the latest status name, and reports a failed read with a retry', async () => {
const m = mount({ source, setup: (faces) => { faces.changeRequestReview.mockResolvedValue(REFUSED.reviewFailed) } })
await settle()
expect(m.view.getByText('Could not read GitHub threads: GitHub is down')).toBeDefined()
m.faces.changeRequestReview.mockResolvedValue(ok({ ...REVIEW, threads: [line('on-row', 'src/app.ts', 'R', 4)] }))
fireEvent.click(within(m.view.getByText('Could not read GitHub threads: GitHub is down').closest('[role="status"]')!).getByRole('button', { name: en.retry }))
await settle()
// A refresh asks the host to read past the threads it keeps; the next status does not.
expect(m.faces.changeRequestReview).toHaveBeenLastCalledWith(URL7, HEAD, true, expect.any(AbortSignal))
expect(card(m, 'on-row')).not.toBeNull()
m.faces.changeRequestReview.mockResolvedValue(REFUSED.staleHead)
act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(2)] }), disconnected: false }) })
await settle()
expect(m.faces.changeRequestReview).toHaveBeenLastCalledWith(URL7, HEAD, false, expect.any(AbortSignal))
expect(card(m, 'on-row')).not.toBeNull()
m.faces.changeRequestReview.mockResolvedValue(REFUSED.reviewFailed)
act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(3)] }), disconnected: false }) })
await settle()
expect(card(m, 'on-row')).not.toBeNull()
expect(m.view.getByText('Could not read GitHub threads: GitHub is down')).toBeDefined()
act(() => { m.panel.set({ state: ready({ changeRequests: [entry(7, snapshot(7, { headSha: OLD }))] }), disconnected: false }) })
await settle()
expect(card(m, 'on-row')).toBeNull()
})
it('offers no thread list for a change request without threads', async () => {
const m = mount({ source, setup: reviewed({ ...REVIEW, threads: [] }) })
await settle()
expect(m.faces.changeRequestReview).toHaveBeenCalledOnce()
expect(m.view.queryByRole('button', { name: /^Review threads/ })).toBeNull()
})
it('names no author when the host hides the change request\'s author', async () => {
const m = mount({ source, state: ready({ changeRequests: [entry(7, snapshot(7, { author: null }))] }), setup: reviewed({ ...REVIEW,
threads: [line('on-row', 'src/app.ts', 'R', 4, { comments: [reviewComment({ author: { login: 'octo', avatarUrl: null, bot: false } })] })] }) })
await settle()
expect(within(card(m, 'on-row')!).queryByText(en['thread.author'])).toBeNull()
})
it('reads no threads for local changes or a hidden view, and shows none for a provider without review reads', async () => {
const local = mount()
await settle()
expect(local.faces.changeRequestReview).not.toHaveBeenCalled()
cleanup()
const m = mount({ source })
await settle()
expect(m.faces.changeRequestReview).toHaveBeenCalledOnce()
expect(m.view.queryByRole('button', { name: /^Review threads/ })).toBeNull()
expect(m.view.queryByText(/^Could not read GitHub threads/)).toBeNull()
let answer: (value: RemoteResult<ForgeReviewData>) => void = () => {}
m.faces.changeRequestReview.mockImplementation(() => new Promise((resolve) => { answer = resolve }))
act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(2)] }), disconnected: false }) })
expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2)
act(() => { m.visibility.set(false) })
await act(async () => { answer(ok(REVIEW)) })
act(() => { m.panel.set({ state: ready({ changeRequests: [polledAt(3)] }), disconnected: false }) })
await settle()
expect(m.faces.changeRequestReview).toHaveBeenCalledTimes(2)
act(() => { m.visibility.set(true) })
await settle()
expect(card(m, 'on-row')).toBeNull()
})
})
@@ -22,7 +22,8 @@ function mount(overrides: Partial<DiffFileProps> = {}) {
const records = new ReviewQueue('diff-review')
const review: ReviewActions = { source, addToInput, records, onQuoted: (item) => { records.recordAgent(item) } }
const handlers = {
toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), reach: new SectionReach(),
toggle: vi.fn(), reveal: vi.fn(), expand: vi.fn(), view: vi.fn(), actions: () => [], section: vi.fn(), nextThread: vi.fn(),
reach: new SectionReach(),
}
const props: DiffFileProps = { file, visible: true, expanded: true, large: false, revealed: false,
text: undefined, open: new Set(), split: true, wrap: true, badge: '', tooltip: 'a.txt',
@@ -162,7 +163,10 @@ it('opens the editor from a hover plus in one press, extending the range on its
expect(m.line('R5').getAttribute('aria-pressed')).toBe('false')
fireEvent.pointerUp(window)
expect(m.getByRole('region', { name: 'Comment on R3–4' })).toBeTruthy()
expect(m.container.querySelector('[data-review-add]')).toBeNull()
// The open editor leaves every hover plus for the next comment, and the range it froze keeps the highlight.
expect(m.container.querySelectorAll('[data-review-add]').length).toBeGreaterThan(0)
expect(m.line('R3').getAttribute('aria-pressed')).toBe('false')
expect(m.code('R', 3).closest('[data-diff-side]')!.className).toContain('selected')
fireEvent.click(m.getByRole('button', { name: 'Cancel' }))
fireEvent.pointerDown(plus('L2'), { button: 0 })
fireEvent.pointerCancel(window)
@@ -277,3 +281,64 @@ it('keeps a text selection across a render that leaves the file unchanged', () =
expect(m.code('R', 3).firstChild).toBe(node)
expect(document.getSelection()?.toString()).toBe(selected)
})
it('writes a left and a right comment at once, each under its own column of the row, and focuses an open range again', () => {
const m = mount()
const open = (name: string) => {
fireEvent.click(m.line(name))
fireEvent.click(m.getByRole('button', { name: 'Add comment' }))
return m.getByRole('region', { name: `Comment on ${name}` })
}
const left = open('L3')
const right = open('R3')
const row = left.closest<HTMLElement>('[data-forge-notes]')!
expect(right.closest('[data-forge-notes]')).toBe(row)
const [leftCell, rightCell] = Array.from(row.children)
expect(leftCell!.contains(left)).toBe(true)
expect(rightCell!.contains(right)).toBe(true)
// Each cell continues the background of its side's line.
expect(leftCell!.className).toContain('del')
expect(rightCell!.className).toContain('add')
expect(m.line('L3').getAttribute('aria-pressed')).toBe('false')
fireEvent.change(within(right).getByRole('textbox'), { target: { value: 'Draft' } })
open('R3')
expect(m.getAllByRole('region', { name: 'Comment on R3' })).toHaveLength(1)
expect(document.activeElement).toBe(within(right).getByRole('textbox'))
expect(within(right).getByRole<HTMLTextAreaElement>('textbox').value).toBe('Draft')
fireEvent.click(within(left).getByRole('button', { name: 'Cancel' }))
expect(m.queryByRole('region', { name: 'Comment on L3' })).toBeNull()
expect(m.getByRole('region', { name: 'Comment on R3' })).toBe(right)
})
it('places side-by-side records in their columns and keeps an editor whose line stops drawing after the lines', () => {
const m = mount()
act(() => {
for (const side of ['L', 'R'] as const) m.records.recordAgent({ source, comment: { ...selectReviewLines(file, side, 3, 4)!, body: side } })
})
const threads = Array.from(m.container.querySelectorAll<HTMLElement>('[data-forge-review-thread]'))
expect(threads.map(thread => thread.closest('[data-forge-notes]'))).toEqual([threads[0]!.closest('[data-forge-notes]'), threads[0]!.closest('[data-forge-notes]')])
const cells = Array.from(threads[0]!.closest('[data-forge-notes]')!.children)
expect(threads.map(thread => cells.findIndex(cell => cell.contains(thread)))).toEqual([0, 1])
// The added blank line has no old line, so the left cell of its row is empty.
fireEvent.click(m.line('R5'))
fireEvent.click(m.getByRole('button', { name: 'Add comment' }))
const editor = m.getByRole('region', { name: 'Comment on R5' })
const [emptyCell] = Array.from(editor.closest('[data-forge-notes]')!.children)
expect(emptyCell!.className).toContain('empty')
expect(emptyCell!.querySelector('[data-forge-comments]')!.childElementCount).toBe(0)
const shorter = { ...file.hunks[0]!, newLines: 3, lines: file.hunks[0]!.lines.slice(0, -1) }
m.rerender(<DiffFile {...m.props} file={{ ...file, hunks: [shorter] }} />)
const code = m.container.querySelector('[data-review]')!
const rows = Array.from(code.children)
const moved = m.getByRole('region', { name: 'Comment on R5' })
expect(moved.parentElement).toBe(code)
expect(rows.indexOf(moved)).toBeGreaterThan(rows.findLastIndex(row => row.hasAttribute('data-diff-pair')))
})
it('labels the plus on the unified row that ends a right-side range', () => {
const m = mount({ split: false })
fireEvent.click(m.line('R4'))
expect(m.getByRole('button', { name: 'Add comment' })).toBeTruthy()
expect(m.container.querySelector('[data-review-add="R4"]')).toBeNull()
expect(m.container.querySelector('[data-review-add="R3"]')).not.toBeNull()
})
@@ -0,0 +1,11 @@
/** jsdom font-loading events for specs that mount the changes toolbar, which measures again when fonts load. */
import { afterEach, beforeEach } from 'vitest'
const fonts = Object.getOwnPropertyDescriptor(document, 'fonts')
beforeEach(() => {
Object.defineProperty(document, 'fonts', { configurable: true, value: new EventTarget() })
})
afterEach(() => {
if (fonts === undefined) Reflect.deleteProperty(document, 'fonts')
else Object.defineProperty(document, 'fonts', fonts)
})
@@ -12,7 +12,8 @@ import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import type { SidebarRightTabDefinition, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
import type {
ChangeRequestSnapshot, ForgeCommitList, ForgeReviewRequest, ForgeReviewResult,
ChangeRequestSnapshot, ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult,
ForgeThreadId,
} from '@deepseek-ai/dsh-experimental-forge/types'
import { SessionId } from '@deepseek-ai/dsh-session/types'
import { RemoteError, type RemoteResult, type TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
@@ -31,6 +32,7 @@ import { SessionHoverForge } from '../src/client/SessionHoverForge.tsx'
import { SessionRowForge } from '../src/client/SessionRowForge.tsx'
import type { NoticeSource } from '../src/client/source.ts'
import type { ReviewSelection } from '../src/client/review.ts'
import { reviewThread } from './thread-fixtures.client.ts'
import { WorktreeProgress, type WorktreeProgressInjected } from '../src/client/WorktreeProgress.tsx'
import { WorktreeSettings } from '../src/client/WorktreeSettings.tsx'
import type { WorktreeSettingsInjected, WorktreeSettings as WorktreeSettingsFields } from '../src/client/worktree-settings-form.ts'
@@ -183,6 +185,11 @@ async function base() {
changeRequestCommits: vi.fn(async (_sessionId: SessionId, _url: string, _signal?: AbortSignal): Read<ForgeCommitList | null> =>
({ ok: true, value: COMMITS })),
changeRequestText: vi.fn(async (_sessionId: SessionId, _url: string, _commit: string, _path: string): Read<string> => ({ ok: true, value: 'b\n' })),
changeRequestReview: vi.fn(async (
_sessionId: SessionId, _url: string, headSha: string, _fresh: boolean, _signal?: AbortSignal,
): Read<ForgeReviewData> => ({ ok: true, value: { headSha, viewer: 'octo', threads: [], truncated: false, pendingReview: null, viewerCanReview: true } })),
changeRequestReviewWrite: vi.fn(async (_sessionId: SessionId, _url: string, _write: ForgeReviewWrite): Read<ForgeReviewWriteResult> =>
({ ok: true, value: { ok: true } })),
submitReview: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeReviewRequest): Read<ForgeReviewResult> => ({ ok: true, value: { ok: true, url: 'https://github.com/review' } })),
}
ctx.provide('remote.forgePanel', forgePanel)
@@ -750,9 +757,16 @@ describe('mountForgePanel changes view', () => {
expect(insertQuote.mock.calls[0]?.[1]).toEqual({ label: 'a.ts R1', title: 'a.ts', detail: 'R1', body: 'Check this' })
expect(resolve).toHaveBeenCalledWith(scope)
expect(focus).toHaveBeenCalledTimes(2)
const thread = reviewThread({ path: 'src/a.ts' })
expect(view.addThreadToInput(thread, 'https://github.com/octo/demo/pull/7', 'R3')).toBe(true)
expect(view.addThreadToInput(thread, 'https://github.com/octo/demo/pull/7', 'R3')).toBe(true)
expect(insertQuote.mock.calls.slice(2).map(([text, summary]) => [text.split('\n')[0], summary?.label]))
.toEqual([['## Review Thread 1', 'a.ts R3'], ['## Review Thread 2', 'a.ts R3']])
insertQuote.mockClear()
focus.mockClear()
insertQuote.mockReturnValueOnce(false)
expect(view.addReviewToInput(selection)).toBe(false)
expect(focus).toHaveBeenCalledTimes(2)
expect(focus).not.toHaveBeenCalled()
expect(send).not.toHaveBeenCalled()
const request: ForgeReviewRequest = { kind: 'review', headSha: 'a', event: 'comment', body: 'Summary', comments: [] }
expect(await view.submitReview('https://github.com/pr', request)).toMatchObject({ ok: true, value: { ok: true } })
@@ -786,7 +800,6 @@ describe('mountForgePanel changes view', () => {
comment: { path: 'a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Check this', hunk: '@@ -1 +1 @@\n-old\n+new' } }
const queue = f.changes(S1).reviewQueue(tab)
queue.recordAgent(selection)
if (kind === 'change') queue.add(selection)
queue.summarize('Summary', 'comment')
const otherTab = { id: 'other-tab' as TabId, signal: new AbortController().signal }
const other = f.changes(S1).reviewQueue(otherTab)
@@ -823,6 +836,12 @@ describe('mountForgePanel changes view', () => {
expect(f.forgePanel.localCommits).toHaveBeenCalledWith(S1, 'refs/heads/topic', signal)
expect(await view.changeRequestCommits('https://github.com/octo/demo/pull/7', signal)).toEqual({ ok: true, value: COMMITS })
expect(f.forgePanel.changeRequestCommits).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', signal)
expect(await view.changeRequestReview('https://github.com/octo/demo/pull/7', 'a'.repeat(40), true, signal))
.toEqual({ ok: true, value: { headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false, pendingReview: null, viewerCanReview: true } })
expect(f.forgePanel.changeRequestReview).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', 'a'.repeat(40), true, signal)
const write = { kind: 'resolve', headSha: 'a'.repeat(40), thread: 'thread-1' as ForgeThreadId, resolved: true } as const
expect(await view.changeRequestReviewWrite('https://github.com/octo/demo/pull/7', write)).toEqual({ ok: true, value: { ok: true } })
expect(f.forgePanel.changeRequestReviewWrite).toHaveBeenCalledWith(S1, 'https://github.com/octo/demo/pull/7', write)
expect(view.viewedFiles).toBe(f.changes(S1).viewedFiles)
expect(view.viewedFiles).not.toBe(f.changes(S2).viewedFiles)
view.reconnect()
@@ -844,6 +863,8 @@ describe('mountForgePanel changes view', () => {
expect(f.notice()).toMatchObject({ key: 'review.submitted', tone: 'success' })
f.changes(S1).report('review.published')
expect(f.notice()).toMatchObject({ key: 'review.published', tone: 'success' })
f.changes(S1).report('review.discarded')
expect(f.notice()).toMatchObject({ key: 'review.discarded', tone: 'success' })
const writeText = vi.fn(async (_text: string) => {})
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest'
import { Buffer } from 'node:buffer'
import type { ChangeRequestKey, ForgeReviewData } from '@deepseek-ai/dsh-experimental-forge'
import { ReviewCache } from '../src/review-cache.ts'
const a = 'fake:a#1' as ChangeRequestKey
const b = 'fake:b#2' as ChangeRequestKey
const c = 'fake:c#3' as ChangeRequestKey
/** A read with no threads, told apart by its head, whose length sets its size. */
function review(head: string): ForgeReviewData {
return { headSha: head, viewer: null, threads: [], truncated: false, pendingReview: null, viewerCanReview: false }
}
const size = Buffer.byteLength(JSON.stringify(review('x')))
describe('ReviewCache', () => {
it('returns threads kept at the same version until they reach the age limit', () => {
const cache = new ReviewCache(size * 4, 100)
cache.set(a, 'v1', review('x'), 1_000, cache.token())
expect(cache.get(a, 'v1', 1_099)).toEqual(review('x'))
expect(cache.get(a, 'v2', 1_050)).toBeUndefined()
expect(cache.get(b, 'v1', 1_050)).toBeUndefined()
expect(cache.get(a, 'v1', 1_100)).toBeUndefined()
})
it('replaces a change request\'s earlier read and drops the least recently read reads past the byte limit', () => {
const cache = new ReviewCache(size * 2, 100)
cache.set(a, 'v1', review('x'), 0, cache.token())
cache.set(a, 'v2', review('y'), 0, cache.token())
cache.set(b, 'v1', review('z'), 0, cache.token())
expect(cache.get(a, 'v1', 0)).toBeUndefined()
expect(cache.get(a, 'v2', 0)).toEqual(review('y'))
cache.set(c, 'v1', review('w'), 0, cache.token())
expect(cache.get(b, 'v1', 0)).toBeUndefined()
expect(cache.get(a, 'v2', 0)).toEqual(review('y'))
expect(cache.get(c, 'v1', 0)).toEqual(review('w'))
})
it('forgets a dropped change request and keeps no read that started before any drop', () => {
const cache = new ReviewCache(size * 4, 100)
const early = cache.token()
cache.set(a, 'v1', review('x'), 0, early)
cache.set(b, 'v1', review('y'), 0, early)
cache.drop(a)
cache.drop(c)
expect(cache.get(a, 'v1', 0)).toBeUndefined()
expect(cache.get(b, 'v1', 0)).toEqual(review('y'))
cache.set(a, 'v1', review('z'), 0, early)
expect(cache.get(a, 'v1', 0)).toBeUndefined()
cache.set(a, 'v1', review('z'), 0, cache.token())
expect(cache.get(a, 'v1', 0)).toEqual(review('z'))
cache.set(a, 'v2', review('much longer than the others'), 0, cache.token())
cache.set(c, 'v1', review('w'), 0, cache.token())
expect(cache.get(c, 'v1', 0)).toEqual(review('w'))
})
it('keeps no read larger than the byte limit and forgets the read it replaced', () => {
const cache = new ReviewCache(size, 100)
cache.set(a, 'v1', review('x'), 0, cache.token())
cache.set(a, 'v2', review('longer'), 0, cache.token())
expect(cache.get(a, 'v1', 0)).toBeUndefined()
expect(cache.get(a, 'v2', 0)).toBeUndefined()
cache.set(b, 'v1', review('x'), 0, cache.token())
expect(cache.get(b, 'v1', 0)).toEqual(review('x'))
})
})
@@ -115,6 +115,11 @@ describe('HideTestsSwitch and ViewedProgress', () => {
const bar = view.getByRole('progressbar', { name: en['viewed.progressAria'] })
expect([bar.getAttribute('aria-valuenow'), bar.getAttribute('aria-valuemax'), bar.getAttribute('aria-valuetext')]).toEqual(['2', '4', '2 / 4 viewed'])
expect(bar.querySelector<HTMLElement>('[style]')?.style.width).toBe('50%')
// The compact form a narrow toolbar shows: a ring filled to the same share, and the bare count.
const compact = bar.querySelector<HTMLElement>('[data-forge-progress="compact"]')!
expect(compact.textContent).toBe('2/4')
const [length, gap] = compact.querySelectorAll('circle')[1]!.getAttribute('stroke-dasharray')!.split(' ').map(Number)
expect(length! / gap!).toBeCloseTo(0.5)
view.rerender(<ViewedProgress viewed={0} total={0} t={t} />)
expect(view.queryByRole('progressbar')).toBeNull()
})
@@ -0,0 +1,412 @@
// @vitest-environment jsdom
/** Host review thread cards, the outdated section, and the thread list rendered on their own. */
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types'
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { en } from '../src/client/locales.ts'
import { Avatar, OutdatedThreads, ThreadCard, type ThreadActions, type ThreadWrites } from '../src/client/ReviewThreads.tsx'
import { ThreadList, type ThreadListProps } from '../src/client/ThreadList.tsx'
import { diffFile, reviewComment, reviewThread } from './thread-fixtures.client.ts'
const t = makeTranslate(en)
const OLD = 'b'.repeat(40)
const scrolled = vi.fn()
beforeEach(() => {
Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, value: scrolled })
})
afterEach(() => {
cleanup()
scrolled.mockReset()
Reflect.deleteProperty(Element.prototype, 'scrollIntoView')
})
function actions(overrides: Partial<ThreadActions> = {}): ThreadActions {
return {
author: 'octo', focused: null,
addToInput: vi.fn(() => true), openLink: vi.fn(), readText: vi.fn(async (): Promise<RemoteResult<string>> => ({ ok: true, value: 'a\nb\nc' })),
inputFailed: vi.fn(),
writes: null,
...overrides,
}
}
/** Writes that the code host takes, for a user without a pending review who may start one. */
function writes(overrides: Partial<ThreadWrites> = {}): ThreadWrites {
return { write: vi.fn<ThreadWrites['write']>(async () => undefined), reviewStarted: false, canReview: true, ...overrides }
}
const LINE = { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const
const outdated = (overrides: Partial<ForgeReviewThread> = {}): ForgeReviewThread => reviewThread({
id: 'old' as ForgeThreadId, current: null, original: { commit: OLD, startLine: 2, endLine: 3 }, diffHunk: '@@ -1 +1,3 @@\n a\n+b\n+c', ...overrides,
})
describe('Avatar', () => {
it('shows the image, or the login\'s first letter when there is none or it fails, or a mark for a deleted account', () => {
const view = render(<><Avatar author={{ login: 'octo', avatarUrl: 'https://avatars.example/u/1', bot: false }} />
<Avatar author={{ login: 'lin', avatarUrl: null, bot: false }} /><Avatar author={null} size={24} /></>)
const image = view.container.querySelector('img')!
expect(image.getAttribute('referrerpolicy')).toBe('no-referrer')
fireEvent.error(image)
expect([...view.container.querySelectorAll('span')].map(span => span.textContent)).toEqual(['O', 'L', '?'])
})
})
describe('ThreadCard writes', () => {
it('offers no write without writes or permissions', () => {
const permitted = reviewThread({ viewerCanReply: true, viewerCanResolve: true,
comments: [reviewComment({ viewerCanEdit: true, viewerCanDelete: true })] })
const silent = render(<ThreadCard thread={permitted} place={LINE} actions={actions()} t={t} />)
expect(silent.queryByRole('button', { name: en['thread.replyPlaceholder'] })).toBeNull()
expect(silent.queryByRole('button', { name: 'Resolve thread' })).toBeNull()
expect(silent.queryByRole('button', { name: /^Actions for the comment/ })).toBeNull()
silent.unmount()
const barred = render(<ThreadCard thread={reviewThread()} place={LINE} actions={actions({ writes: writes() })} t={t} />)
expect(barred.queryByRole('button', { name: en['thread.replyPlaceholder'] })).toBeNull()
expect(barred.queryByRole('button', { name: 'Resolve thread' })).toBeNull()
expect(barred.queryByRole('button', { name: /^Actions for the comment/ })).toBeNull()
})
it('replies at once by default, or starts a pending review from the menu, keeping the text after a refusal', async () => {
const write = vi.fn<ThreadWrites['write']>().mockResolvedValueOnce('GitHub did not apply this: Locked').mockResolvedValue(undefined)
const thread = reviewThread({ id: 't1' as ForgeThreadId, viewerCanReply: true })
const view = render(<ThreadCard thread={thread} place={LINE} actions={actions({ writes: writes({ write }) })} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['thread.replyPlaceholder'] }))
const field = view.getByRole('textbox', { name: en['thread.replyPlaceholder'] })
expect(view.getByRole('button', { name: 'Reply' })).toHaveProperty('disabled', true)
fireEvent.change(field, { target: { value: ' ' } })
expect(view.getByRole('button', { name: 'Reply' })).toHaveProperty('disabled', true)
fireEvent.change(field, { target: { value: 'Fixed in the next commit' } })
fireEvent.click(view.getByRole('button', { name: 'Reply' }))
expect(view.getByRole('button', { name: en['review.publishing'] })).toHaveProperty('disabled', true)
expect(await view.findByRole('alert')).toHaveProperty('textContent', 'GitHub did not apply this: Locked')
expect(field).toHaveProperty('value', 'Fixed in the next commit')
fireEvent.click(view.getByRole('button', { name: 'Reply options' }))
fireEvent.click(within(view.getByRole('menu')).getByRole('menuitem', { name: 'Start review' }))
await vi.waitFor(() => { expect(view.queryByRole('textbox')).toBeNull() })
expect(write.mock.calls).toEqual([
[{ kind: 'reply', thread: 't1', body: 'Fixed in the next commit', pending: false }],
[{ kind: 'reply', thread: 't1', body: 'Fixed in the next commit', pending: true }],
])
fireEvent.click(view.getByRole('button', { name: en['thread.replyPlaceholder'] }))
fireEvent.click(view.getByRole('button', { name: 'Cancel' }))
expect(view.queryByRole('textbox')).toBeNull()
})
it('adds every reply to the pending review once one exists, offering no reply at once', async () => {
const write = vi.fn<ThreadWrites['write']>(async () => undefined)
const thread = reviewThread({ id: 't1' as ForgeThreadId, viewerCanReply: true })
const view = render(<ThreadCard thread={thread} place={LINE}
actions={actions({ writes: writes({ write, reviewStarted: true }) })} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['thread.replyPlaceholder'] }))
expect(view.getByRole('button', { name: 'Add to review' })).toHaveProperty('disabled', true)
expect(view.queryByRole('button', { name: 'Reply options' })).toBeNull()
fireEvent.change(view.getByRole('textbox'), { target: { value: 'Later' } })
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
expect(view.getByRole('button', { name: en['review.publishing'] })).toHaveProperty('disabled', true)
await vi.waitFor(() => { expect(view.queryByRole('textbox')).toBeNull() })
expect(write).toHaveBeenLastCalledWith({ kind: 'reply', thread: 't1', body: 'Later', pending: true })
})
it('replies only at once when the user may not review', () => {
const thread = reviewThread({ viewerCanReply: true })
const view = render(<ThreadCard thread={thread} place={LINE}
actions={actions({ writes: writes({ canReview: false }) })} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['thread.replyPlaceholder'] }))
expect(view.getByRole('button', { name: 'Reply' })).toBeTruthy()
expect(view.queryByRole('button', { name: 'Reply options' })).toBeNull()
})
it('resolves an unresolved thread and unresolves a resolved one, showing a refusal and a thrown write as the outcome', async () => {
const write = vi.fn<ThreadWrites['write']>().mockResolvedValueOnce('Refused').mockRejectedValueOnce(new Error('lost')).mockResolvedValue(undefined)
const open = render(<ThreadCard thread={reviewThread({ id: 't1' as ForgeThreadId, viewerCanResolve: true })} place={LINE}
actions={actions({ writes: writes({ write }) })} t={t} />)
fireEvent.click(open.getByRole('button', { name: 'Resolve thread' }))
expect(open.getByRole('button', { name: 'Resolve thread' })).toHaveProperty('disabled', true)
expect(await open.findByRole('alert')).toHaveProperty('textContent', 'Refused')
fireEvent.click(open.getByRole('button', { name: 'Resolve thread' }))
await vi.waitFor(() => { expect(open.getByRole('alert').textContent).toBe(en['thread.writeUnknown']) })
open.unmount()
const settled = render(<ThreadCard thread={reviewThread({ id: 't2' as ForgeThreadId, resolved: true, viewerCanResolve: true })} place={LINE}
actions={actions({ writes: writes({ write }), focused: { id: 't2' as ForgeThreadId, revision: 1 } })} t={t} />)
fireEvent.click(settled.getByRole('button', { name: 'Unresolve thread' }))
await vi.waitFor(() => { expect(write).toHaveBeenLastCalledWith({ kind: 'resolve', thread: 't2', resolved: false }) })
expect(settled.queryByRole('alert')).toBeNull()
expect(write).toHaveBeenNthCalledWith(1, { kind: 'resolve', thread: 't1', resolved: true })
})
it('edits the user\'s comment in place and keeps the editor after a refusal', async () => {
const write = vi.fn<ThreadWrites['write']>().mockResolvedValueOnce('Refused').mockResolvedValue(undefined)
const comment = reviewComment({ body: 'Old text', viewerCanEdit: true, author: { login: 'octo', avatarUrl: null, bot: false } })
const view = render(<ThreadCard thread={reviewThread({ comments: [comment] })} place={LINE}
actions={actions({ writes: writes({ write }) })} t={t} />)
const menuButton = view.getByRole('button', { name: 'Actions for the comment by octo' })
fireEvent.click(menuButton)
expect(menuButton.getAttribute('aria-expanded')).toBe('true')
const menu = within(view.getByRole('menu'))
expect(menu.queryByRole('menuitem', { name: 'Delete' })).toBeNull()
fireEvent.click(menu.getByRole('menuitem', { name: 'Edit' }))
const field = view.getByRole('textbox', { name: 'Edit comment' })
expect(field).toHaveProperty('value', 'Old text')
expect(view.getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true)
fireEvent.change(field, { target: { value: 'New text' } })
fireEvent.click(view.getByRole('button', { name: 'Save' }))
expect(view.getByRole('button', { name: 'Saving…' })).toHaveProperty('disabled', true)
expect(await view.findByRole('alert')).toHaveProperty('textContent', 'Refused')
fireEvent.click(view.getByRole('button', { name: 'Save' }))
await vi.waitFor(() => { expect(view.queryByRole('textbox')).toBeNull() })
expect(write).toHaveBeenLastCalledWith({ kind: 'edit-comment', comment: comment.id, body: 'New text' })
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by octo' }))
fireEvent.click(within(view.getByRole('menu')).getByRole('menuitem', { name: 'Edit' }))
fireEvent.click(view.getByRole('button', { name: 'Cancel' }))
expect(view.getByText('Old text')).toBeTruthy()
})
it('asks before deleting a comment, warning when it is the thread\'s only one, and keeps the question after a refusal', async () => {
const write = vi.fn<ThreadWrites['write']>().mockResolvedValueOnce('Refused').mockResolvedValue(undefined)
const only = reviewComment({ viewerCanDelete: true, author: null })
const view = render(<ThreadCard thread={reviewThread({ comments: [only] })} place={LINE}
actions={actions({ writes: writes({ write }) })} t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by Deleted account' }))
expect(within(view.getByRole('menu')).queryByRole('menuitem', { name: 'Edit' })).toBeNull()
fireEvent.click(within(view.getByRole('menu')).getByRole('menuitem', { name: 'Delete' }))
const question = within(view.getByRole('group', { name: en['thread.deleteLast'] }))
expect(view.queryByRole('button', { name: /^Actions for the comment/ })).toBeNull()
fireEvent.click(question.getByRole('button', { name: 'Delete' }))
expect(question.getByRole('button', { name: 'Deleting…' })).toHaveProperty('disabled', true)
expect(await question.findByRole('alert')).toHaveProperty('textContent', 'Refused')
fireEvent.click(question.getByRole('button', { name: 'Cancel' }))
expect(view.queryByRole('group')).toBeNull()
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by Deleted account' }))
fireEvent.click(within(view.getByRole('menu')).getByRole('menuitem', { name: 'Delete' }))
fireEvent.click(view.getByRole('button', { name: 'Delete' }))
await vi.waitFor(() => { expect(view.queryByRole('group')).toBeNull() })
expect(write).toHaveBeenLastCalledWith({ kind: 'delete-comment', comment: only.id })
view.unmount()
const two = render(<ThreadCard thread={reviewThread({ comments: [reviewComment(), reviewComment({ viewerCanDelete: true })] })}
place={LINE} actions={actions({ writes: writes({ write }) })} t={t} />)
fireEvent.click(two.getByRole('button', { name: 'Actions for the comment by reviewer' }))
fireEvent.click(within(two.getByRole('menu')).getByRole('menuitem', { name: 'Delete' }))
expect(two.getByRole('group', { name: en['thread.deleteConfirm'] })).toBeTruthy()
})
it('keeps a thread resolved elsewhere open while the reader writes a reply or an edit in it, then folds it', () => {
const open = reviewThread({ id: 't1' as ForgeThreadId, viewerCanReply: true, comments: [reviewComment({ viewerCanEdit: true })] })
const resolved = { ...open, resolved: true }
const view = render(<ThreadCard thread={open} place={LINE} actions={actions({ writes: writes() })} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['thread.replyPlaceholder'] }))
fireEvent.change(view.getByRole('textbox'), { target: { value: 'Half written' } })
view.rerender(<ThreadCard thread={resolved} place={LINE} actions={actions({ writes: writes() })} t={t} />)
expect(view.getByRole('textbox')).toHaveProperty('value', 'Half written')
fireEvent.click(view.getByRole('button', { name: 'Cancel' }))
expect(view.getByText('Resolved thread · reviewer')).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: 'Expand' }))
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by reviewer' }))
fireEvent.click(within(view.getByRole('menu')).getByRole('menuitem', { name: 'Edit' }))
fireEvent.change(view.getByRole('textbox', { name: 'Edit comment' }), { target: { value: 'Reworded' } })
fireEvent.click(view.getByRole('button', { name: 'Collapse' }))
expect(view.getByRole('textbox', { name: 'Edit comment' })).toHaveProperty('value', 'Reworded')
})
it('closes the comment menu without acting', () => {
const write = vi.fn<ThreadWrites['write']>()
const view = render(<ThreadCard thread={reviewThread({ comments: [reviewComment({ viewerCanEdit: true })] })} place={LINE}
actions={actions({ writes: writes({ write }) })} t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by reviewer' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(view.queryByRole('menu')).toBeNull()
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by reviewer' }))
fireEvent.click(view.getByRole('button', { name: 'Actions for the comment by reviewer' }))
expect(view.queryByRole('menu')).toBeNull()
expect(write).not.toHaveBeenCalled()
})
it('ignores a second send while a write runs', async () => {
let finish: (value: string | undefined) => void = () => {}
const write = vi.fn<ThreadWrites['write']>(() => new Promise((resolve) => { finish = resolve }))
const view = render(<ThreadCard thread={reviewThread({ viewerCanResolve: true })} place={LINE}
actions={actions({ writes: writes({ write }) })} t={t} />)
const button = view.getByRole('button', { name: 'Resolve thread' })
act(() => { button.click(); button.click() })
expect(write).toHaveBeenCalledOnce()
await act(async () => { finish(undefined) })
})
})
describe('ThreadCard', () => {
it('shows each comment with its author, time, role tags, and Markdown without raw HTML', () => {
const thread = reviewThread({ comments: [
reviewComment({ author: { login: 'octo', avatarUrl: null, bot: false }, body: '**bold** <b>raw</b><!-- hidden -->', createdAt: 'not a time' }),
reviewComment({ author: { login: 'ci', avatarUrl: null, bot: true }, pending: true }),
reviewComment({ author: null }),
] })
const view = render(<ThreadCard thread={thread} place={{ kind: 'line', side: 'R', startLine: 3, endLine: 3 }} actions={actions()} t={t} />)
const card = view.container.querySelector('[data-forge-thread]')!
expect(card.getAttribute('data-side')).toBe('R')
expect(card.querySelector('strong')?.textContent).toBe('bold')
expect(card.textContent).not.toContain('<b>')
expect(card.textContent).not.toContain('hidden')
expect(within(card as HTMLElement).getByText('not a time')).toBeDefined()
expect(card.querySelectorAll('[data-forge-thread-comment]')).toHaveLength(3)
expect(within(card as HTMLElement).getAllByText(en['thread.author'])).toHaveLength(1)
expect(within(card as HTMLElement).getByText(en['thread.bot'])).toBeDefined()
expect(within(card as HTMLElement).getByText(en['review.pending'])).toBeDefined()
expect(within(card as HTMLElement).getByText(en['thread.deletedAuthor'])).toBeDefined()
})
it('quotes the thread, reports a refused quote, and opens its page', () => {
const shared = actions({ addToInput: vi.fn(() => false) })
const thread = reviewThread()
const view = render(<ThreadCard thread={thread} place={{ kind: 'line', side: 'R', startLine: 3, endLine: 3 }} actions={shared} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['review.addToInput'] }))
expect(shared.addToInput).toHaveBeenCalledWith(thread, 'R3')
expect(shared.inputFailed).toHaveBeenCalledOnce()
fireEvent.click(view.getByRole('button', { name: en['thread.openOnHost'] }))
expect(shared.openLink).toHaveBeenCalledWith(thread.comments[0]?.url)
})
it('names a file thread and offers no page without one', () => {
const view = render(<ThreadCard thread={reviewThread({ subject: 'file', current: null, original: null, comments: [reviewComment({ url: null })] })}
place={{ kind: 'file' }} actions={actions()} t={t} />)
expect(view.getByRole('region', { name: en['thread.fileLevel'] }).textContent).toContain(en['thread.fileLevel'])
expect(view.queryByRole('button', { name: en['thread.openOnHost'] })).toBeNull()
})
it('folds a resolved thread into one row until unfolded or jumped to, and folds it again after a jump', () => {
const thread = reviewThread({ resolved: true, comments: [] })
const place = { kind: 'line', side: 'R', startLine: 3, endLine: 3 } as const
const view = render(<ThreadCard thread={thread} place={place} actions={actions()} t={t} />)
expect(view.container.textContent).toContain('Resolved thread · Deleted account')
fireEvent.click(view.getByRole('button', { name: en['thread.expand'] }))
expect(view.getByRole('region', { name: 'R3' })).toBeDefined()
fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] }))
expect(view.queryByRole('region')).toBeNull()
view.rerender(<ThreadCard thread={thread} place={place} actions={actions({ focused: { id: thread.id, revision: 1 } })} t={t} />)
expect(view.getByRole('region', { name: 'R3' })).toBeDefined()
fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] }))
expect(view.queryByRole('region')).toBeNull()
view.rerender(<ThreadCard thread={thread} place={place} actions={actions({ focused: { id: thread.id, revision: 2 } })} t={t} />)
expect(view.getByRole('region', { name: 'R3' })).toBeDefined()
})
it('shows an outdated thread at its original lines with the end of its hunk and the file at that commit', async () => {
let answer: (value: RemoteResult<string>) => void = () => {}
const shared = actions({ readText: vi.fn(() => new Promise<RemoteResult<string>>((resolve) => { answer = resolve })) })
const view = render(<ThreadCard thread={outdated()} place={{ kind: 'outdated' }} actions={shared} t={t} />)
const card = view.getByRole('region', { name: 'Originally R2–3' })
expect(card.textContent).toContain(`Originally R2–3 · on ${OLD.slice(0, 7)}`)
expect([...card.querySelectorAll('[class*="excerptLine"]')].map(line => line.textContent)).toEqual(['@@ -1 +1,3 @@', ' a', '+b', '+c'])
// The quote names the lines the thread was written on, as the card does.
fireEvent.click(view.getByRole('button', { name: en['review.addToInput'] }))
expect(shared.addToInput).toHaveBeenCalledWith(expect.objectContaining({ id: 'old' }), 'R2–3')
fireEvent.click(view.getByRole('button', { name: en['thread.viewOriginal'] }))
expect(shared.readText).toHaveBeenCalledWith(OLD, 'src/a.ts')
expect(view.getByText(en['thread.originalLoading'])).toBeDefined()
await act(async () => { answer({ ok: true, value: 'one\ntwo\nthree\nfour' }) })
const file = view.getByRole('region', { name: en['thread.viewOriginal'] })
expect([...file.querySelectorAll('[class*="marked"]')].map(line => line.textContent)).toEqual(['2two', '3three'])
expect(scrolled.mock.contexts).toContain(file.querySelectorAll('[class*="marked"]')[0])
fireEvent.click(view.getByRole('button', { name: en['thread.hideOriginal'] }))
expect(view.queryByRole('region', { name: en['thread.viewOriginal'] })).toBeNull()
const failing = { ...shared, readText: vi.fn(async (): Promise<RemoteResult<string>> => ({ ok: false, error: new RemoteError('forgePanel/diff-failed', 'gone', {}) })) }
view.rerender(<ThreadCard thread={outdated()} place={{ kind: 'outdated' }} actions={failing} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['thread.viewOriginal'] }))
await act(async () => { await Promise.resolve() })
expect(view.getByRole('alert').textContent).toBe('Could not read the file at that commit: gone')
})
it('offers no file at that commit for an old-side thread and no excerpt without a recorded hunk', () => {
const view = render(<ThreadCard thread={outdated({ side: 'L', diffHunk: null })} place={{ kind: 'outdated' }} actions={actions()} t={t} />)
expect(view.queryByRole('button', { name: en['thread.viewOriginal'] })).toBeNull()
expect(view.container.querySelector('[class*="excerpt"]')).toBeNull()
})
})
describe('OutdatedThreads', () => {
it('renders nothing without threads, folds on request, and opens again for a later jump to one of its threads', () => {
const empty = render(<OutdatedThreads threads={[]} actions={actions()} t={t} />)
expect(empty.container.textContent).toBe('')
cleanup()
const view = render(<OutdatedThreads threads={[outdated()]} actions={actions()} t={t} />)
expect(view.container.textContent).toContain('1 outdated threads')
fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] }))
expect(view.container.querySelector('[data-forge-thread]')).toBeNull()
view.rerender(<OutdatedThreads threads={[outdated()]} actions={actions({ focused: { id: 'elsewhere' as ForgeThreadId, revision: 1 } })} t={t} />)
expect(view.container.querySelector('[data-forge-thread]')).toBeNull()
view.rerender(<OutdatedThreads threads={[outdated()]} actions={actions({ focused: { id: 'old' as ForgeThreadId, revision: 2 } })} t={t} />)
expect(view.container.querySelector('[data-forge-thread]')).not.toBeNull()
fireEvent.click(view.getByRole('button', { name: en['thread.collapse'] }))
expect(view.container.querySelector('[data-forge-thread]')).toBeNull()
fireEvent.click(view.getByRole('button', { name: en['thread.expand'] }))
expect(view.container.querySelector('[data-forge-thread]')).not.toBeNull()
})
})
describe('ThreadList', () => {
function list(overrides: Partial<ThreadListProps> = {}) {
const props: ThreadListProps = {
entries: [], files: [], truncated: false, url: 'https://github.com/octo/demo/pull/7', filter: 'all', claim: false,
claimed: vi.fn(), choose: vi.fn(), open: vi.fn(), openLink: vi.fn(), close: vi.fn(), t, ...overrides,
}
return { props, view: render(<ThreadList {...props} />) }
}
it('says when there are no threads and when none pass the filter, with only the host link below them', () => {
expect(list().view.getByText(en['thread.empty'])).toBeDefined()
cleanup()
const { view } = list({ entries: [{ thread: reviewThread(), place: { kind: 'line', side: 'R', startLine: 3, endLine: 3 } }], filter: 'resolved' })
expect(view.getByText(en['thread.none'])).toBeDefined()
expect(view.getByRole('button', { name: en['thread.openAll'] }).parentElement?.textContent).toBe(en['thread.openAll'])
})
it('orders each file\'s threads from file threads to lines to outdated ones and describes each', () => {
const entries = [
{ thread: outdated({ id: 'gone' as ForgeThreadId, comments: [reviewComment(), reviewComment()] }), place: { kind: 'outdated' } as const },
{ thread: reviewThread({ id: 'late' as ForgeThreadId }), place: { kind: 'line', side: 'R', startLine: 9, endLine: 9 } as const },
{ thread: reviewThread({ id: 'away' as ForgeThreadId, current: null, original: null }), place: { kind: 'elsewhere' } as const },
{ thread: reviewThread({ id: 'whole' as ForgeThreadId, subject: 'file', current: null, original: null }), place: { kind: 'file' } as const },
{ thread: reviewThread({ id: 'early' as ForgeThreadId, comments: [reviewComment({
body: '# Title\n> **Note** `code` [link](https://example.test) <sub>x</sub>', author: { login: 'ci', avatarUrl: null, bot: true } })] }),
place: { kind: 'line', side: 'L', startLine: 2, endLine: 4 } as const },
]
const { view, props } = list({ entries })
const items = [...view.container.querySelectorAll('[data-forge-thread-item]')]
expect(items.map(item => item.getAttribute('data-forge-thread-item'))).toEqual(['whole', 'early', 'late', 'gone', 'away'])
expect(items.map(item => item.querySelector('[class*="meta"]')?.textContent)).toEqual([
en['thread.fileLevel'], 'L2–4', 'R9', `Originally R2–3 · on ${OLD.slice(0, 7)} · 1 replies`, '',
])
expect(items[1]?.querySelector('[class*="excerpt"]')?.textContent).toBe('Title Note code link x')
expect(items[1]?.textContent).toContain(en['thread.bot'])
expect(items[3]?.textContent).toContain(en['thread.outdatedTag'])
expect(items[4]?.textContent).toContain(en['thread.elsewhereTag'])
fireEvent.click(items[3]!)
expect(props.open).toHaveBeenCalledWith(entries[0], false)
fireEvent.click(view.getByRole('radio', { name: /^Unresolved/ }))
expect(props.choose).toHaveBeenCalledWith('unresolved')
fireEvent.click(view.getByRole('button', { name: en['thread.close'] }))
expect(props.close).toHaveBeenCalledOnce()
})
it('groups threads by file in file order, orders them by row, and moves the filter with arrow keys', () => {
const at = (id: string, path: string, side: 'L' | 'R', line: number) => ({ thread: reviewThread({ id: id as ForgeThreadId, path }),
place: { kind: 'line', side, startLine: line, endLine: line } as const })
const empty = { thread: reviewThread({ path: 'c.ts', comments: [] }), place: { kind: 'file' } as const }
// In b.ts the added R2 row follows the deleted L2 row, and L9 sits in the unchanged lines after the hunk.
const files = [diffFile('b.ts', [{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 2, lines: [' a', '-b', '+B'] }])]
const { view, props } = list({ entries: [empty, at('late', 'b.ts', 'L', 9), at('added', 'b.ts', 'R', 2), at('other', 'a.ts', 'R', 3),
at('deleted', 'b.ts', 'L', 2)], files, filter: 'unresolved' })
expect([...view.container.querySelectorAll('[data-forge-thread-group]')].map(group => group.getAttribute('data-forge-thread-group')))
.toEqual(['b.ts', 'a.ts', 'c.ts'])
expect([...view.container.querySelectorAll('[data-forge-thread-group="b.ts"] [data-forge-thread-item]')].map(item => item.getAttribute('data-forge-thread-item')))
.toEqual(['deleted', 'added', 'late'])
expect(view.container.querySelector('[data-forge-thread-group="c.ts"] [class*="excerpt"]')?.textContent).toBe('')
fireEvent.keyDown(view.getByRole('radio', { name: /^Unresolved/ }), { key: 'ArrowRight' })
expect(props.choose).toHaveBeenCalledWith('resolved')
})
})
@@ -0,0 +1,138 @@
/** Placement, filters, excerpts, and composer quotes of host review threads. */
import { describe, expect, it } from 'vitest'
import type { ForgeReviewThread } from '@deepseek-ai/dsh-experimental-forge/types'
import {
anchorRange, formatThreadQuote, gapOf, inFileOrder, hunkExcerpt, passesFilter, placeThread, threadQuoteSummary, THREAD_FILTERS,
} from '../src/client/review-threads.ts'
import { diffFile, reviewComment, reviewThread } from './thread-fixtures.client.ts'
const HEAD = 'a'.repeat(40)
const OLD = 'b'.repeat(40)
const MIDDLE = 'c'.repeat(40)
describe('placeThread', () => {
const current = reviewThread({ current: { commit: HEAD, startLine: 3, endLine: 5 }, original: { commit: OLD, startLine: 2, endLine: 4 } })
it('places a thread on the whole change request at its position on the head, else in the outdated section', () => {
const whole = { head: HEAD, end: HEAD, commits: null }
expect(placeThread(current, whole)).toEqual({ kind: 'line', side: 'R', startLine: 3, endLine: 5 })
expect(placeThread(reviewThread({ side: 'L', current: { commit: HEAD, startLine: 1, endLine: 1 } }), whole))
.toEqual({ kind: 'line', side: 'L', startLine: 1, endLine: 1 })
expect(placeThread(reviewThread({ current: null }), whole)).toEqual({ kind: 'outdated' })
expect(placeThread(reviewThread({ subject: 'file', current: null, original: null }), whole)).toEqual({ kind: 'file' })
})
it('places a new-side thread in chosen commits only where its lines number the last chosen commit', () => {
expect(placeThread(current, { head: HEAD, end: HEAD, commits: { from: MIDDLE, to: HEAD } }))
.toEqual({ kind: 'line', side: 'R', startLine: 3, endLine: 5 })
expect(placeThread(current, { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } }))
.toEqual({ kind: 'line', side: 'R', startLine: 2, endLine: 4 })
expect(placeThread(current, { head: HEAD, end: MIDDLE, commits: { from: MIDDLE, to: MIDDLE } })).toEqual({ kind: 'elsewhere' })
expect(placeThread(reviewThread({ side: 'L', current: { commit: HEAD, startLine: 1, endLine: 1 } }),
{ head: HEAD, end: HEAD, commits: { from: HEAD, to: HEAD } })).toEqual({ kind: 'elsewhere' })
expect(placeThread(reviewThread({ current: null, original: null }), { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } }))
.toEqual({ kind: 'outdated' })
expect(placeThread(reviewThread({ subject: 'file', current: null, original: null }), { head: HEAD, end: OLD, commits: { from: OLD, to: OLD } }))
.toEqual({ kind: 'file' })
})
})
it('names a side and its lines', () => {
expect(anchorRange('R', { startLine: 12, endLine: 12 })).toBe('R12')
expect(anchorRange('L', { startLine: 3, endLine: 5 })).toBe('L3–5')
})
it('finds the collapsed unchanged lines that hold a line on either side', () => {
const file = diffFile('a.ts', [
{ oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] },
{ oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] },
])
expect(gapOf(file, 'R', 2)).toBe(0)
expect(gapOf(file, 'R', 6)).toBeUndefined()
expect(gapOf(file, 'R', 10)).toBe(1)
expect(gapOf(file, 'L', 21)).toBeUndefined()
expect(gapOf(file, 'R', 21)).toBe(1)
expect(gapOf(file, 'R', 40)).toBe(2)
})
it('orders a file\'s threads as its section shows them', () => {
const file = diffFile('a.ts', [
{ oldStart: 5, oldLines: 3, newStart: 5, newLines: 3, lines: [' a', '-b', '+b', ' c'] },
{ oldStart: 20, oldLines: 2, newStart: 22, newLines: 2, lines: ['-x', '+x', ' y'] },
])
const line = (id: string, side: 'L' | 'R', at: number) => ({ id, place: { kind: 'line', side, startLine: at, endLine: at } as const })
const items = [
{ id: 'away', place: { kind: 'elsewhere' } as const }, { id: 'gone', place: { kind: 'outdated' } as const },
line('tail', 'R', 40), line('added', 'R', 6), line('second-hunk', 'L', 20), line('before', 'R', 2), line('deleted', 'L', 6),
{ id: 'whole', place: { kind: 'file' } as const }, line('between', 'L', 10),
]
expect(inFileOrder(items, file).map(item => item.id))
.toEqual(['whole', 'before', 'deleted', 'added', 'between', 'second-hunk', 'tail', 'gone', 'away'])
// Without the file's diff, lines sort by their number.
expect(inFileOrder([line('b', 'R', 9), line('a', 'L', 2)], undefined).map(item => item.id)).toEqual(['a', 'b'])
})
describe('thread filters', () => {
it('keeps the threads each filter names', () => {
const outdated = reviewThread({ current: null })
const resolved = reviewThread({ resolved: true })
const file = reviewThread({ subject: 'file', current: null, original: null })
expect(THREAD_FILTERS).toEqual(['unresolved', 'resolved', 'all'])
expect([outdated, resolved, file].map(thread => passesFilter(thread, 'unresolved'))).toEqual([true, false, true])
expect([outdated, resolved, file].map(thread => passesFilter(thread, 'resolved'))).toEqual([false, true, false])
expect([outdated, resolved, file].map(thread => passesFilter(thread, 'all'))).toEqual([true, true, true])
})
})
describe('hunkExcerpt', () => {
const hunk = '@@ -1,8 +1,9 @@\n a\n b\n-c\n+C\n+D\n d\n e'
it('keeps the header and the thread\'s lines on its side with three before them', () => {
expect(hunkExcerpt(hunk, 'R', 1)).toEqual({ header: '@@ -1,8 +1,9 @@', lines: ['+C', '+D', ' d', ' e'] })
expect(hunkExcerpt(hunk, 'L', 2)).toEqual({ header: '@@ -1,8 +1,9 @@', lines: [' a', ' b', '-c', '+C', '+D', ' d', ' e'] })
})
it('keeps every line of a short hunk without a header', () => {
expect(hunkExcerpt(' a\n+b', 'R', 1)).toEqual({ header: null, lines: [' a', '+b'] })
})
})
describe('thread quotes', () => {
it('summarizes a quote by file name, range, and first comment', () => {
expect(threadQuoteSummary(reviewThread({ path: 'src/a.ts' }), 'R3')).toEqual({ label: 'a.ts R3', title: 'src/a.ts', detail: 'R3', body: 'First comment' })
expect(threadQuoteSummary(reviewThread({ path: 'a.ts', comments: [] }), null)).toEqual({ label: 'a.ts', title: 'a.ts', detail: 'a.ts', body: '' })
})
it('formats a line thread with its hunk, state, and every comment quoted line by line', () => {
const thread: ForgeReviewThread = reviewThread({
current: { commit: HEAD, startLine: 3, endLine: 5 }, diffHunk: '@@ -1 +1 @@\n-```\n+````',
comments: [reviewComment({ body: '# Heading\n\nsecond line', url: 'https://github.com/octo/demo/pull/7#discussion_r1' }),
reviewComment({ author: null, body: 'reply' })],
})
expect(formatThreadQuote(thread, 'https://github.com/octo/demo/pull/7', 2)).toBe([
'## Review Thread 2', 'File: src/a.ts', 'Side: R', 'Lines: 3-5', `Commit: ${HEAD}`, 'State: unresolved',
'Source: https://github.com/octo/demo/pull/7#discussion_r1', 'Diff hunk:', '`````diff', '@@ -1 +1 @@\n-```\n+````', '`````',
'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> # Heading', '>', '> second line', 'Unknown author (2026-11-05T08:00:00Z):', '> reply',
].join('\n'))
})
it('names an old-side thread\'s lines as the file before the change and its commit as where the diff ends', () => {
const old = reviewThread({ side: 'L', current: { commit: HEAD, startLine: 15, endLine: 15 }, diffHunk: null })
expect(formatThreadQuote(old, 'https://github.com/octo/demo/pull/7', 1)).toBe([
'## Review Thread 1', 'File: src/a.ts', 'Side: L (old side: the lines number the file before the pull request\'s changes)', 'Lines: 15',
`Diff head: ${HEAD}`, 'State: unresolved', `Source: ${old.comments[0]?.url}`,
'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> First comment',
].join('\n'))
})
it('formats an outdated single line at the lines it was written on, and a file thread without lines or hunk', () => {
const outdated = reviewThread({ current: null, resolved: true, original: { commit: OLD, startLine: 9, endLine: 9 }, diffHunk: null,
comments: [reviewComment({ url: null })] })
expect(formatThreadQuote(outdated, 'https://github.com/octo/demo/pull/7', 1)).toBe([
'## Review Thread 1', 'File: src/a.ts', 'Side: R', 'Lines: 9', `Commit: ${OLD}`, 'State: resolved, outdated',
'Source: https://github.com/octo/demo/pull/7', 'Comments:', '@reviewer (2026-11-05T08:00:00Z):', '> First comment',
].join('\n'))
const file = reviewThread({ subject: 'file', current: null, original: null, diffHunk: null })
expect(formatThreadQuote(file, 'https://github.com/octo/demo/pull/7', 1)).toContain('File: src/a.ts\nLines: whole file\nState: unresolved\n')
})
})
@@ -4,12 +4,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { Profiler } from 'react'
import { act, cleanup, fireEvent, render, within } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { ForgeReviewId } from '@deepseek-ai/dsh-experimental-forge/types'
import type { ForgeDiffFile } from '../src/types.ts'
import { formatReviewComment, reviewQuoteSummary, selectReviewLines, reviewMatches, type ReviewSelection } from '../src/client/review.ts'
import { ReviewQueue } from '../src/client/review-queue.ts'
import { ReviewThread } from '../src/client/ReviewThread.tsx'
import { SubmitReview } from '../src/client/SubmitReview.tsx'
import { ReviewComposer } from '../src/client/ReviewComposer.tsx'
import { ReviewComposer, type ReviewActions } from '../src/client/ReviewComposer.tsx'
import { en } from '../src/client/locales.ts'
const t = makeTranslate(en)
@@ -23,6 +24,14 @@ const selection: ReviewSelection = { source: { kind: 'change', url: 'https://git
comment: { ...selectReviewLines(file, 'R', 3, 4)!, body: '为什么新增这两行?' } }
afterEach(() => { cleanup(); localStorage.clear(); vi.restoreAllMocks() })
/** Store comment drafts the way an earlier panel kept them in the browser, then open the queue over them. */
function drafted(...drafts: ReviewSelection[]): ReviewQueue {
localStorage.setItem('review-test', JSON.stringify({ comments: drafts, records: [], body: '', event: 'comment', uncertain: null }))
return new ReviewQueue('review-test')
}
const PENDING = { id: 'review-1' as ForgeReviewId, comments: 2 }
describe('review references', () => {
it('anchors added and deleted files and detects changed source or hunk content', () => {
const added = { ...file, hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 1, lines: ['+new'] }] }
@@ -34,17 +43,18 @@ describe('review references', () => {
expect(reviewMatches(selection, selection.source, added)).toBe(false)
expect(reviewMatches(selection, selection.source, file)).toBe(true)
})
it('keeps a failed draft editable and lets the user queue it without publishing', () => {
const queue = vi.fn().mockReturnValue(false), close = vi.fn(), onQuoted = vi.fn()
it('keeps a refused comment editable and lets the user add it to the pending review without publishing', async () => {
const queue = vi.fn<NonNullable<ReviewActions['queue']>>().mockResolvedValue('GitHub refused'), close = vi.fn(), onQuoted = vi.fn()
const actions = { source: selection.source, addToInput: () => true, queue, reviewStarted: true, onQuoted }
const view = render(<ReviewComposer selection={selection} actions={actions} close={close} t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
expect(view.getByRole('alert')).toHaveProperty('textContent', en['review.saveFailed'])
expect(await view.findByRole('alert')).toHaveProperty('textContent', 'GitHub refused')
fireEvent.change(view.getByRole('textbox'), { target: { value: 'Updated' } })
expect(view.queryByRole('alert')).toBeNull()
queue.mockReturnValue(true)
queue.mockResolvedValue(undefined)
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
expect(close).toHaveBeenCalledOnce()
await vi.waitFor(() => { expect(close).toHaveBeenCalledOnce() })
expect(queue).toHaveBeenLastCalledWith({ ...selection, comment: { ...selection.comment, body: 'Updated' } })
fireEvent.click(view.getByRole('button', { name: 'Add to input' }))
expect(onQuoted).toHaveBeenCalledWith({ ...selection, comment: { ...selection.comment, body: 'Updated' } })
})
@@ -52,7 +62,7 @@ describe('review references', () => {
let reject: (error: Error) => void = () => {}
const publish = vi.fn(() => new Promise<string | undefined>((_resolve, fail) => { reject = fail }))
const view = render(<ReviewComposer selection={selection}
actions={{ source: selection.source, addToInput: () => true, queue: () => true, publish }} close={vi.fn()} t={t} />)
actions={{ source: selection.source, addToInput: () => true, queue: async () => undefined, publish }} close={vi.fn()} t={t} />)
fireEvent.click(view.getByRole('button', { name: 'GitHub comment options' }))
fireEvent.click(view.getByRole('menuitem', { name: 'Publish single comment' }))
expect(view.getByRole('button', { name: en['review.publishing'] })).toHaveProperty('disabled', true)
@@ -135,7 +145,7 @@ describe('review references', () => {
})
it('keeps the single-comment publish action inside the GitHub split menu', async () => {
const publish = vi.fn().mockResolvedValue(undefined)
const queue = vi.fn().mockReturnValue(true)
const queue = vi.fn<NonNullable<ReviewActions['queue']>>().mockResolvedValue(undefined)
const close = vi.fn()
const view = render(<ReviewComposer selection={selection}
actions={{ source: selection.source, addToInput: () => true, publish, queue }} close={close} t={t} />)
@@ -165,10 +175,7 @@ describe('review references', () => {
describe('pending reviews', () => {
it('edits only the chosen occurrence and refuses edits after publication or during dispatch', () => {
const queue = new ReviewQueue('review-test')
expect(queue.add({ ...selection, source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null, commits: null } })).toBe(false)
queue.add(selection)
queue.add({ ...selection, comment: { ...selection.comment, body: 'Second' } })
const queue = drafted(selection, { ...selection, comment: { ...selection.comment, body: 'Second' } })
const first = queue.fileComments('a.ts', selection.source).threads[0]!
queue.editThread(first.key, null)
expect(queue.getSnapshot().comments.map(item => item.comment.body)).toEqual(['Second'])
@@ -181,8 +188,7 @@ describe('pending reviews', () => {
expect(queue.fileComments('a.ts', selection.source).threads[0]?.kind).toBe('published')
})
it('clears every record on close and rejects a publication receipt arriving afterwards', () => {
const queue = new ReviewQueue('review-test')
queue.add(selection)
const queue = drafted(selection)
queue.recordAgent(selection)
queue.summarize('Summary', 'request-changes')
queue.begin({ kind: 'comment', headSha: 'a'.repeat(40), comment: selection.comment })
@@ -194,24 +200,21 @@ describe('pending reviews', () => {
expect(new ReviewQueue('review-test').getSnapshot()).toMatchObject({ comments: [], records: [], body: '', uncertain: null })
})
it('closes in memory and reports a storage removal failure', () => {
const queue = new ReviewQueue('review-test')
queue.add(selection)
const queue = drafted(selection)
vi.spyOn(Storage.prototype, 'removeItem').mockImplementationOnce(() => { throw new DOMException('Denied', 'SecurityError') })
expect(queue.close()).toBe(false)
expect(queue.getSnapshot().comments).toEqual([])
expect(queue.add(selection)).toBe(false)
expect(queue.recordAgent(selection)).toBe(false)
})
it('restores frozen comments and summary, persisting uncertainty before dispatch', () => {
const queue = new ReviewQueue('review-test')
const queue = drafted(selection)
const listener = vi.fn()
const release = queue.subscribe(listener)
expect(queue.add(selection)).toBe(true)
queue.summarize('Check the logic', 'request-changes')
const write = { kind: 'review' as const, headSha: 'a'.repeat(40), event: 'request-changes' as const, body: 'Check the logic', comments: [{ path: selection.comment.path, side: selection.comment.side, startLine: selection.comment.startLine, endLine: selection.comment.endLine, body: selection.comment.body }] }
expect(queue.begin(write)).toBe(true)
expect(new ReviewQueue('review-test').getSnapshot()).toMatchObject({ comments: [selection], uncertain: write })
expect(queue.begin(write)).toBe(false)
expect(queue.add(selection)).toBe(false)
expect(queue.edit(0, 'different')).toBe(false)
queue.finish(false)
queue.edit(0, 'updated')
@@ -245,11 +248,10 @@ describe('pending reviews', () => {
expect(queue.fileComments('a.ts', based.source).threads).toHaveLength(1)
expect(queue.fileComments('a.ts', { ...based.source, baseRef: null, commits: null }).threads).toHaveLength(0)
})
it('keeps records of chosen commits apart from the whole comparison and refuses to queue them for a review', () => {
it('keeps records of chosen commits apart from the whole comparison', () => {
const queue = new ReviewQueue('review-test')
const commits = { from: '1'.repeat(40), to: '2'.repeat(40) }
const chosen = { ...selection, source: { ...selection.source, commits } }
expect(queue.add(chosen)).toBe(false)
expect(queue.recordAgent(chosen)).toBe(true)
expect(queue.fileComments('a.ts', chosen.source).threads).toHaveLength(1)
expect(queue.fileComments('a.ts', selection.source).threads).toHaveLength(0)
@@ -261,7 +263,7 @@ describe('pending reviews', () => {
localStorage.setItem('review-test', 'broken')
const queue = new ReviewQueue('review-test')
expect(queue.getSnapshot().error).toBe('load')
expect(queue.add(selection)).toBe(false)
expect(queue.recordAgent(selection)).toBe(false)
expect(localStorage.getItem('review-test')).toBe('broken')
})
it.each([
@@ -295,22 +297,21 @@ describe('pending reviews', () => {
it('keeps the previous queue on quota failure and allows retry after recovery', () => {
const queue = new ReviewQueue('review-test')
const setter = vi.spyOn(Storage.prototype, 'setItem').mockImplementationOnce(() => { throw new DOMException('quota', 'QuotaExceededError') })
expect(queue.add(selection)).toBe(false)
expect(queue.getSnapshot()).toMatchObject({ error: 'save', comments: [] })
expect(queue.recordAgent(selection)).toBe(false)
expect(queue.getSnapshot()).toMatchObject({ error: 'save', records: [] })
setter.mockRestore()
expect(queue.add(selection)).toBe(true)
expect(queue.recordAgent(selection)).toBe(true)
expect(queue.getSnapshot().error).toBeNull()
})
})
describe('inline records', () => {
it('keeps pending edits at their code location and quotes the edited text', () => {
const records = new ReviewQueue('review-test')
records.add(selection)
const records = drafted(selection)
const thread = records.fileComments('a.ts', selection.source).threads[0]!
const addToInput = vi.fn().mockReturnValue(false)
const actions = { records, source: selection.source, addToInput }
const view = render(<ReviewThread thread={thread} actions={actions} locked={false} outdated={false} split t={t} />)
const view = render(<ReviewThread thread={thread} actions={actions} locked={false} outdated={false} t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Add to input' }))
expect(view.getByRole('alert')).toHaveProperty('textContent', en['review.inputFailed'])
fireEvent.click(view.getByRole('button', { name: 'Edit' }))
@@ -325,11 +326,10 @@ describe('inline records', () => {
expect(records.getSnapshot().comments).toEqual([])
})
it('preserves unsaved edits and reports failed editing, finishing, and deletion', () => {
const records = new ReviewQueue('review-test')
records.add(selection)
const records = drafted(selection)
const thread = records.fileComments('a.ts', selection.source).threads[0]!
const view = render(<ReviewThread thread={thread} actions={{ source: selection.source, addToInput: () => true, records }}
locked={false} outdated split={false} t={t} />)
locked={false} outdated t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Edit' }))
records.close()
fireEvent.change(view.getByRole('textbox'), { target: { value: 'Not saved' } })
@@ -339,10 +339,50 @@ describe('inline records', () => {
fireEvent.click(view.getByRole('button', { name: 'Delete' }))
expect(view.getByRole('alert')).toBeTruthy()
})
it('labels a browser draft and moves it into the pending review, deleting it from the browser only once the host took it', async () => {
const records = drafted(selection)
const thread = records.fileComments('a.ts', selection.source).threads[0]!
const queue = vi.fn<NonNullable<ReviewActions['queue']>>().mockResolvedValueOnce('GitHub refused')
const view = render(<ReviewThread thread={thread} actions={{ source: selection.source, addToInput: () => true, records, queue }}
locked={false} outdated={false} t={t} />)
expect(view.getByText(en['review.browserDraft'])).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
expect(view.getByRole('button', { name: en['review.publishing'] })).toHaveProperty('disabled', true)
expect(await view.findByRole('alert')).toHaveProperty('textContent', 'GitHub refused')
expect(records.getSnapshot().comments).toHaveLength(1)
queue.mockRejectedValueOnce(new Error('transport lost'))
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
await vi.waitFor(() => { expect(view.getByRole('alert').textContent).toBe(en['review.unknown']) })
queue.mockResolvedValueOnce(undefined)
vi.spyOn(records, 'editThread').mockReturnValueOnce(false)
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
await vi.waitFor(() => { expect(view.getByRole('alert').textContent).toBe(en['review.saveFailed']) })
queue.mockResolvedValueOnce(undefined)
fireEvent.click(view.getByRole('button', { name: 'Add to review' }))
await vi.waitFor(() => { expect(records.getSnapshot().comments).toEqual([]) })
expect(queue).toHaveBeenCalledWith(selection)
})
it('offers no move for an outdated browser draft, one being edited, or without a pending review destination', () => {
const records = drafted(selection)
const thread = records.fileComments('a.ts', selection.source).threads[0]!
const queue = vi.fn<NonNullable<ReviewActions['queue']>>()
const outdated = render(<ReviewThread thread={thread} actions={{ source: selection.source, addToInput: () => true, records, queue }}
locked={false} outdated t={t} />)
expect(outdated.queryByRole('button', { name: 'Add to review' })).toBeNull()
outdated.unmount()
const current = render(<ReviewThread thread={thread} actions={{ source: selection.source, addToInput: () => true, records, queue }}
locked={false} outdated={false} t={t} />)
fireEvent.click(current.getByRole('button', { name: 'Edit' }))
expect(current.queryByRole('button', { name: 'Add to review' })).toBeNull()
current.unmount()
const without = render(<ReviewThread thread={thread} actions={{ source: selection.source, addToInput: () => true, records }}
locked={false} outdated={false} t={t} />)
expect(without.queryByRole('button', { name: 'Add to review' })).toBeNull()
})
it('opens a published receipt and omits editing on immutable records', () => {
const openLink = vi.fn()
const view = render(<ReviewThread thread={{ key: 1, kind: 'published', selection, url: 'https://github.com/review' }}
actions={{ source: selection.source, addToInput: () => true, openLink }} locked={false} outdated={false} split={false} t={t} />)
actions={{ source: selection.source, addToInput: () => true, openLink }} locked={false} outdated={false} t={t} />)
fireEvent.click(view.getByRole('button', { name: en['review.recheck'] }))
expect(openLink).toHaveBeenCalledWith('https://github.com/review')
expect(view.queryByRole('button', { name: 'Edit' })).toBeNull()
@@ -352,8 +392,8 @@ describe('inline records', () => {
describe('submission availability', () => {
it('explains why requesting changes needs a summary and enables submission when one is entered', () => {
const queue = new ReviewQueue('review-test')
const view = render(<SubmitReview queue={queue} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)} busy={false} error={null}
submit={vi.fn()} close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
const view = render(<SubmitReview queue={queue} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)} pending={null} own={false} busy={false} error={null}
submit={vi.fn()} discard={undefined} close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
const button = view.getByRole('button', { name: 'Submit review' })
const summary = view.getByRole('textbox')
const announcement = view.getByRole('status')
@@ -376,18 +416,94 @@ describe('submission availability', () => {
})
it.each(['local', 'different-pr', 'different-head', 'empty-comment', 'load', 'save'] as const)('blocks %s and retains the review in the modal', (kind) => {
if (kind === 'load') localStorage.setItem('review-test', 'invalid')
const queue = new ReviewQueue('review-test')
const source = kind === 'different-pr' ? { kind: 'change' as const, url: 'other', headSha: 'a'.repeat(40), commits: null }
: kind === 'different-head' ? { kind: 'change' as const, url: 'https://github.com/octo/demo/pull/7', headSha: 'b', commits: null } : selection.source
if (kind !== 'load') queue.add({ ...selection, source, comment: { ...selection.comment, body: kind === 'empty-comment' ? '' : 'Text' } })
const queue = drafted({ ...selection, source, comment: { ...selection.comment, body: kind === 'empty-comment' ? '' : 'Text' } })
if (kind === 'load') localStorage.setItem('review-test', 'invalid')
const opened = kind === 'load' ? new ReviewQueue('review-test') : queue
if (kind === 'save') {
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') })
queue.summarize('Summary', 'comment')
}
if (kind === 'local') vi.spyOn(queue, 'getSnapshot').mockReturnValue({ ...queue.getSnapshot(), comments: [{ ...selection, source: { kind: 'local', scope: 'branch', base: 'origin/main', baseRef: null, commits: null } }] })
const view = render(<SubmitReview queue={queue} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)} busy={false} error={null}
submit={vi.fn()} close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
const view = render(<SubmitReview queue={opened} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)} pending={null} own={false} busy={false} error={null}
submit={vi.fn()} discard={undefined} close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
})
})
describe('pending review submission', () => {
function dialog(
queue: ReviewQueue, props: { readonly busy?: boolean; readonly discard?: () => void; readonly submit?: () => void } = {},
) {
return render(<SubmitReview queue={queue} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)} pending={PENDING} own={false}
busy={props.busy ?? false} error={null} submit={props.submit ?? vi.fn()} discard={props.discard ?? vi.fn()}
close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
}
it('counts the comments of the pending review and submits it with only a summary-free comment decision', () => {
const submit = vi.fn()
const view = dialog(new ReviewQueue('review-test'), { submit })
expect(view.getByText('Pending comments (2)')).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: 'Submit review' }))
expect(submit).toHaveBeenCalledOnce()
})
it('refuses an empty comment review when the pending review holds no comments', () => {
const view = render(<SubmitReview queue={new ReviewQueue('review-test')} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)}
pending={{ ...PENDING, comments: 0 }} own={false} busy={false} error={null} submit={vi.fn()} discard={vi.fn()}
close={vi.fn()} check={vi.fn()}
reconcile={vi.fn()} t={t} />)
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
fireEvent.click(view.getByRole('radio', { name: 'Approve' }))
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', false)
})
it('blocks submission while browser drafts exist beside the pending review, even drafts from another head', () => {
const view = dialog(drafted({ ...selection, source: { kind: 'change', url: 'https://github.com/octo/demo/pull/7', headSha: 'b'.repeat(40), commits: null } }))
expect(view.getByRole('alert').textContent).toBe(t('review.browserDrafts', { count: '1' }))
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
})
it('asks before discarding the pending review and lets the reader keep it', () => {
const discard = vi.fn()
const view = dialog(new ReviewQueue('review-test'), { discard })
fireEvent.click(view.getByRole('button', { name: 'Discard review' }))
const confirm = within(view.getByRole('group', { name: 'Discard review' }))
expect(confirm.getByText(t('review.discardConfirm', { count: '2' }))).toBeTruthy()
expect(view.getAllByRole('button', { name: 'Discard review' }).at(-1)).toHaveProperty('disabled', true)
expect(view.getAllByRole('button', { name: 'Submit review' }).at(-1)).toHaveProperty('disabled', true)
fireEvent.click(confirm.getByRole('button', { name: 'Cancel' }))
expect(view.queryByRole('group', { name: 'Discard review' })).toBeNull()
fireEvent.click(view.getByRole('button', { name: 'Discard review' }))
fireEvent.click(within(view.getByRole('group', { name: 'Discard review' })).getByRole('button', { name: 'Discard review' }))
expect(discard).toHaveBeenCalledOnce()
})
it('names a running discard and keeps its confirmation locked', () => {
const view = dialog(new ReviewQueue('review-test'), { busy: true })
expect(view.getByRole('button', { name: 'Submitting…' })).toHaveProperty('disabled', true)
const discard = view.getByRole('button', { name: 'Discard review' })
expect(discard).toHaveProperty('disabled', true)
view.rerender(<SubmitReview queue={new ReviewQueue('review-test')} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)}
pending={PENDING} own={false} busy={false} error={null} submit={vi.fn()} discard={vi.fn()}
close={vi.fn()} check={vi.fn()} reconcile={vi.fn()}
t={t} />)
fireEvent.click(view.getByRole('button', { name: 'Discard review' }))
view.rerender(<SubmitReview queue={new ReviewQueue('review-test')} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)}
pending={PENDING} own={false} busy error={null} submit={vi.fn()} discard={vi.fn()}
close={vi.fn()} check={vi.fn()} reconcile={vi.fn()} t={t} />)
const confirm = within(view.getByRole('group', { name: 'Discard review' }))
expect(confirm.getByRole('button', { name: 'Discarding…' })).toHaveProperty('disabled', true)
expect(confirm.getByRole('button', { name: 'Cancel' })).toHaveProperty('disabled', true)
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
})
it('lets the author only comment on their own change request, keeping a stored decision until Comment is chosen', () => {
const queue = new ReviewQueue('review-test')
queue.summarize('Looks done', 'approve')
const view = render(<SubmitReview queue={queue} url="https://github.com/octo/demo/pull/7" headSha={'a'.repeat(40)}
pending={PENDING} own busy={false} error={null} submit={vi.fn()} discard={vi.fn()} close={vi.fn()} check={vi.fn()}
reconcile={vi.fn()} t={t} />)
expect(view.getByText(en['review.ownChangeRequest'])).toBeTruthy()
expect(view.getByRole('radio', { name: 'Approve' })).toHaveProperty('disabled', true)
expect(view.getByRole('radio', { name: 'Request changes' })).toHaveProperty('disabled', true)
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', true)
fireEvent.click(view.getByRole('radio', { name: 'Comment' }))
expect(view.getByRole('button', { name: 'Submit review' })).toHaveProperty('disabled', false)
})
})
@@ -0,0 +1,257 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
ChangeRequestRef, ForgeCommentId, ForgeFailure, ForgeReviewData, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId,
} from '@deepseek-ai/dsh-experimental-forge'
import { SessionId } from '@deepseek-ai/dsh-session'
import ForgePanelController from '../src/index.ts'
import type { ForgePanelState } from '../src/index.ts'
import { bench, follow, git, pullUrl, repository, scratch, shellTurn } from './harness.ts'
import type { Bench, Follower } from './harness.ts'
const cleanups: (() => Promise<void>)[] = []
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
const signal = new AbortController().signal
const HEAD = 'a'.repeat(40)
async function opened(config: Parameters<typeof bench>[1] = {}): Promise<{ opened: Bench; follower: Follower; repo: string }> {
const { path, remove } = await scratch('dsh-forge-review-')
cleanups.push(remove)
const repo = await repository(path)
await git(repo, 'remote', 'add', 'origin', 'https://fake.test/octo/demo.git')
const result = await bench(repo, config)
cleanups.push(() => result.ctx.fiber.dispose())
const follower = follow(result.ctx, result.session)
cleanups.push(follower.stop)
return { opened: result, follower, repo }
}
function review(headSha: string, path = 'src/a.ts'): ForgeReviewData {
return {
headSha, viewer: 'octo', truncated: false, pendingReview: null, viewerCanReview: true,
threads: [{
id: 'thread-1' as ForgeThreadId, path, side: 'R', subject: 'line', resolved: false, diffHunk: '@@ -1 +1 @@\n-old\n+new',
current: { commit: headSha, startLine: 1, endLine: 1 }, original: { commit: headSha, startLine: 1, endLine: 1 }, comments: [],
viewerCanReply: true, viewerCanResolve: true,
}],
}
}
/** Whether the change request at `url` holds a snapshot with the given head and update time. */
function polledAt(state: ForgePanelState, url: string, headSha = HEAD, updatedAt?: string): boolean {
const snapshot = state.changeRequests.find(entry => entry.url === url)?.snapshot ?? null
return snapshot !== null && snapshot.headSha === headSha && (updatedAt === undefined || snapshot.updatedAt === updatedAt)
}
describe('forgePanel change request reviews', () => {
it('reads threads at the displayed head and reuses them for every Session until the update time changes', async () => {
const { opened: panel, follower, repo } = await opened()
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
Object.assign(panel.provider, { readReview })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)).resolves.toEqual(review(HEAD))
const other = panel.ctx.sessions.create(SessionId('forge-review-other'), { meta: { cwd: repo } })
panel.ctx.forgeSession.track(other, pullUrl(7))
await expect(panel.ctx.forgePanel.changeRequestReview(other, pullUrl(7), HEAD, false, signal)).resolves.toEqual(review(HEAD))
expect(readReview).toHaveBeenCalledTimes(1)
panel.provider.overrides.set(7, { updatedAt: '2026-11-07T05:00:00Z' })
await panel.ctx.forgePanel.refresh(panel.session, signal)
await follower.until(state => polledAt(state, pullUrl(7), HEAD, '2026-11-07T05:00:00Z'))
readReview.mockResolvedValueOnce(review(HEAD, 'src/b.ts'))
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal))
.resolves.toMatchObject({ threads: [{ path: 'src/b.ts' }] })
expect(readReview).toHaveBeenCalledTimes(2)
})
it('reads from the host for a fresh read and keeps its result for later reads', async () => {
const { opened: panel, follower } = await opened()
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
Object.assign(panel.provider, { readReview })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
readReview.mockResolvedValueOnce(review(HEAD, 'src/b.ts'))
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, true, signal))
.resolves.toMatchObject({ threads: [{ path: 'src/b.ts' }] })
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal))
.resolves.toMatchObject({ threads: [{ path: 'src/b.ts' }] })
expect(readReview).toHaveBeenCalledTimes(2)
})
it('reads again once the kept threads reach reviewRefreshMs', async () => {
const { opened: panel, follower } = await opened({ reviewRefreshMs: 1 })
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
Object.assign(panel.provider, { readReview })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
await new Promise(resolve => setTimeout(resolve, 5))
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
expect(readReview).toHaveBeenCalledTimes(2)
})
it('refuses a head other than the latest status without reading, and polls again when the host names another head', async () => {
const { opened: panel, follower } = await opened()
const pushed = 'b'.repeat(40)
const readReview = vi.fn(async (): Promise<ForgeReviewData | ForgeFailure> => ({ code: 'stale', message: `head moved to ${pushed}` }))
Object.assign(panel.provider, { readReview })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), pushed, false, signal))
.rejects.toMatchObject({ code: 'forgePanel/stale-head', message: `The change request head moved from ${pushed} to ${HEAD}` })
expect(readReview).not.toHaveBeenCalled()
panel.provider.overrides.set(7, { headSha: pushed })
const fetches = panel.provider.fetches.length
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal))
.rejects.toMatchObject({ code: 'forgePanel/stale-head', message: `head moved to ${pushed}` })
await follower.until(state => polledAt(state, pullUrl(7), pushed))
expect(panel.provider.fetches.length).toBe(fetches + 1)
})
it('reports an unbound change request, one not read yet, a provider without review reads, and a failed read, keeping no failure', async () => {
const { opened: panel, follower } = await opened()
panel.provider.failures.set(8, { code: 'unavailable', message: 'down' })
shellTurn(panel.session, 1, [
{ callId: 'seven', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` },
{ callId: 'eight', command: 'gh pr create --fill', output: `${pullUrl(8)}\n` },
])
await follower.until(state => polledAt(state, pullUrl(7))
&& state.changeRequests.some(entry => entry.url === pullUrl(8) && entry.update !== null && 'failure' in entry.update))
const read = (url: string): Promise<ForgeReviewData> =>
panel.ctx.forgePanel.changeRequestReview(panel.session, url, HEAD, false, signal)
await expect(read(pullUrl(9))).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
await expect(read(pullUrl(8))).rejects.toMatchObject({ code: 'forgePanel/review-failed', message: 'The change request status has not been read yet' })
await expect(read(pullUrl(7)))
.rejects.toMatchObject({ code: 'forgePanel/review-unsupported', message: 'This provider does not support review reads' })
const codes = ['too-large', 'not-found', 'unauthenticated', 'unavailable'] as const
const readReview = vi.fn(async (): Promise<ForgeReviewData | ForgeFailure> => ({ code: 'unavailable', message: 'down' }))
Object.assign(panel.provider, { readReview })
for (const code of codes) {
readReview.mockResolvedValueOnce({ code, message: `threads ${code}` })
await expect(read(pullUrl(7))).rejects.toMatchObject({ code: 'forgePanel/review-failed', message: `threads ${code}` })
}
expect(readReview).toHaveBeenCalledTimes(codes.length)
})
it('writes through the provider, then drops the kept threads so the next read goes to the host', async () => {
const { opened: panel, follower } = await opened()
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
const writeReview = vi.fn(async (): Promise<ForgeReviewWriteResult> => ({ ok: true }))
Object.assign(panel.provider, { readReview, writeReview })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
const write: ForgeReviewWrite = { kind: 'resolve', headSha: HEAD, thread: 'thread-1' as ForgeThreadId, resolved: true }
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).resolves.toEqual({ ok: true })
expect(writeReview).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), write, expect.any(AbortSignal))
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
expect(readReview).toHaveBeenCalledTimes(2)
writeReview.mockRejectedValueOnce(new Error('gh crashed'))
await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).rejects.toThrow('gh crashed')
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
expect(readReview).toHaveBeenCalledTimes(3)
})
it('keeps no threads read before a write that settled during the read', async () => {
const { opened: panel, follower } = await opened()
const reading = Promise.withResolvers<ForgeReviewData>()
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
readReview.mockReturnValueOnce(reading.promise)
Object.assign(panel.provider, { readReview, writeReview: async (): Promise<ForgeReviewWriteResult> => ({ ok: true }) })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
const first = panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
await vi.waitFor(() => { expect(readReview).toHaveBeenCalledTimes(1) })
await panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7),
{ kind: 'delete-comment', headSha: HEAD, comment: 'comment-1' as ForgeCommentId }, signal)
reading.resolve(review(HEAD, 'src/before.ts'))
await expect(first).resolves.toMatchObject({ threads: [{ path: 'src/before.ts' }] })
await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal))
.resolves.toMatchObject({ threads: [{ path: 'src/a.ts' }] })
expect(readReview).toHaveBeenCalledTimes(2)
})
it('reports a provider without review writes as unsupported and refuses an unbound change request and invalid writes', async () => {
const { opened: panel, follower } = await opened()
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
const write = (url: string, value: ForgeReviewWrite): Promise<ForgeReviewWriteResult> =>
panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, url, value, signal)
const thread = 'thread-1' as ForgeThreadId
const comment = 'comment-1' as ForgeCommentId
const reviewId = 'review-1' as ForgeReviewId
const line = { path: 'src/a.ts', side: 'R' as const, startLine: 2, endLine: 3, body: 'Check' }
await expect(write(pullUrl(7), { kind: 'resolve', headSha: HEAD, thread, resolved: false }))
.resolves.toEqual({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' })
await expect(write(pullUrl(9), { kind: 'resolve', headSha: HEAD, thread, resolved: false })).rejects.toMatchObject({ code: 'forgePanel/not-bound' })
await expect(write(pullUrl(7), { kind: 'resolve', headSha: 'main', thread, resolved: false })).rejects.toThrow('Invalid review commit')
const invalid: ForgeReviewWrite[] = [
{ kind: 'reply', headSha: HEAD, thread, body: ' ', pending: false },
{ kind: 'reply', headSha: HEAD, thread: '' as ForgeThreadId, body: 'Done', pending: false },
{ kind: 'resolve', headSha: HEAD, thread: '' as ForgeThreadId, resolved: true },
{ kind: 'edit-comment', headSha: HEAD, comment, body: '' },
{ kind: 'edit-comment', headSha: HEAD, comment: '' as ForgeCommentId, body: 'Text' },
{ kind: 'delete-comment', headSha: HEAD, comment: '' as ForgeCommentId },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, path: '' } },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, body: '\n' } },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 0 } },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 1.5 } },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: 1 } },
{ kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: Number.POSITIVE_INFINITY } },
{ kind: 'submit-pending', headSha: HEAD, review: '' as ForgeReviewId, event: 'comment', body: '' },
{ kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: ' ' },
{ kind: 'discard-pending', headSha: HEAD, review: '' as ForgeReviewId },
]
for (const value of invalid) await expect(write(pullUrl(7), value)).rejects.toThrow('Invalid review write')
const valid: ForgeReviewWrite[] = [
{ kind: 'reply', headSha: HEAD, thread, body: 'Done', pending: true },
{ kind: 'edit-comment', headSha: HEAD, comment, body: 'Text' },
{ kind: 'delete-comment', headSha: HEAD, comment },
{ kind: 'add-pending', headSha: HEAD, comment: line },
{ kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'approve', body: '' },
{ kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: 'Fix it' },
{ kind: 'discard-pending', headSha: HEAD, review: reviewId },
]
for (const value of valid) await expect(write(pullUrl(7), value)).resolves.toMatchObject({ ok: false, code: 'unsupported' })
})
it('drops the kept threads after publishing a comment so the next read shows it', async () => {
const { opened: panel, follower } = await opened()
const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise<ForgeReviewData | ForgeFailure> => review(headSha))
Object.assign(panel.provider, { readReview, submitReview: async () => ({ ok: true as const, url: `${pullUrl(7)}#discussion_r1` }) })
shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }])
await follower.until(state => polledAt(state, pullUrl(7)))
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
await panel.ctx.forgePanel.submitReview(panel.session, pullUrl(7),
{ kind: 'comment', headSha: HEAD, comment: { path: 'src/a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Nit' } }, signal)
await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, false, signal)
expect(readReview).toHaveBeenCalledTimes(2)
})
it.each([
[{ reviewRefreshMs: 0 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'],
[{ reviewRefreshMs: 2_147_483_648 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'],
[{ maxCachedReviewBytes: 1.5 }, 'forge-panel: maxCachedReviewBytes must be a positive integer'],
])('rejects %j at load', async (config, message) => {
const { opened: panel } = await opened()
await panel.panel.dispose()
await expect(panel.ctx.plugin(ForgePanelController, config)).rejects.toThrow(message)
})
})
@@ -0,0 +1,60 @@
/** Host review threads, comments, and diff files shared by the browser-side thread tests. */
import type { ForgeCommentId, ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types'
import type { ForgeDiffFile, ForgeDiffHunk } from '../src/types.ts'
let comments = 0
/**
* Build a comment by `reviewer` that has a web page and that the signed-in user may not change.
* @param overrides - fields to replace.
* @returns the comment.
*/
export function reviewComment(overrides: Partial<ForgeReviewComment> = {}): ForgeReviewComment {
comments += 1
return {
id: `comment-${comments}` as ForgeCommentId,
author: { login: 'reviewer', avatarUrl: 'https://avatars.example/u/1', bot: false },
body: 'First comment',
createdAt: '2026-11-05T08:00:00Z',
pending: false,
url: `https://github.com/octo/demo/pull/7#discussion_r${comments}`,
viewerCanEdit: false,
viewerCanDelete: false,
...overrides,
}
}
/**
* Build an unresolved new-side thread on line 3 of `src/a.ts`, written at the head `a…a` and placed there, with one comment,
* that the signed-in user may neither reply to nor resolve.
* @param overrides - fields to replace.
* @returns the thread.
*/
export function reviewThread(overrides: Partial<ForgeReviewThread> = {}): ForgeReviewThread {
return {
id: `thread-${comments + 1}` as ForgeThreadId,
path: 'src/a.ts',
side: 'R',
subject: 'line',
current: { commit: 'a'.repeat(40), startLine: 3, endLine: 3 },
original: { commit: 'a'.repeat(40), startLine: 3, endLine: 3 },
diffHunk: '@@ -1,3 +1,3 @@\n a\n-b\n+B',
resolved: false,
viewerCanReply: false,
viewerCanResolve: false,
comments: [reviewComment()],
...overrides,
}
}
/**
* Build a modified text file with hunks.
* @param path - the file's path.
* @param hunks - its hunks.
* @returns the diff file.
*/
export function diffFile(path: string, hunks: readonly ForgeDiffHunk[]): ForgeDiffFile {
return { path, previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, additions: 1, deletions: 1,
digest: 'digest', layer: 'implementation', hunks }
}
@@ -0,0 +1,91 @@
// @vitest-environment jsdom
/** The changes toolbar's fold measurement: the shallowest level that fits, and every change that measures again. */
import './fonts-dom.client.ts'
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
import { DEEPEST_FOLD, foldOf, observeToolbarFold } from '../src/client/toolbar-fold.ts'
afterEach(() => {
document.body.replaceChildren()
vi.unstubAllGlobals()
})
/** A row whose items take the widths of the level it shows: line totals and view toggles fold first, then the bar, then refresh. */
function fixture() {
const row = document.createElement('div')
row.style.padding = '0 8px'
row.style.columnGap = '4px'
const level = (): number => Number(row.getAttribute('data-fold'))
const item = (width: () => number, spacer = false): HTMLElement => {
const element = document.createElement('span')
if (spacer) element.setAttribute('data-fold-spacer', '')
element.getBoundingClientRect = () => new DOMRect(0, 0, width(), 28)
row.append(element)
return element
}
const sizes = { row: 460, files: 100 }
const files = item(() => sizes.files)
item(() => 999, true)
item(() => level() < 2 ? 150 : 50)
item(() => level() === 0 ? 60 : 0)
item(() => (level() < 3 ? 28 : 0) + (level() === 0 ? 84 : 30))
row.getBoundingClientRect = () => new DOMRect(0, 0, sizes.row, 38)
document.body.append(row)
const observe = vi.fn()
const disconnect = vi.fn()
let resized: () => void = () => {}
vi.stubGlobal('ResizeObserver', class {
constructor(callback: () => void) { resized = callback }
observe = observe
disconnect = disconnect
})
const dispose = observeToolbarFold(row)
onTestFinished(dispose)
return { row, files, sizes, observe, disconnect, dispose, level, resize: (width: number) => { sizes.row = width; resized() } }
}
it('shows the shallowest level whose items fit and the deepest when none does', () => {
const { level, resize, observe } = fixture()
expect(level()).toBe(0)
// Row, then its five items.
expect(observe).toHaveBeenCalledTimes(6)
for (const [width, expected] of [[454, 0], [453, 1], [336, 1], [335, 2], [236, 2], [235, 3], [100, DEEPEST_FOLD], [460, 0]] as const) {
resize(width)
expect([width, level()]).toEqual([width, expected])
}
})
it('measures again when text changes, items arrive, or fonts load, and stops after disposal', async () => {
const { row, files, sizes, level, observe, disconnect, dispose } = fixture()
sizes.files = 140
files.textContent = 'All 1,204 files'
await Promise.resolve()
expect(level()).toBe(1)
const added = document.createElement('span')
added.getBoundingClientRect = () => new DOMRect(0, 0, 150, 28)
row.append(added)
await Promise.resolve()
expect(level()).toBe(2)
expect(observe).toHaveBeenCalledWith(added)
sizes.files = 100
document.fonts.dispatchEvent(new Event('loadingdone'))
expect(level()).toBe(2)
added.remove()
await Promise.resolve()
expect(level()).toBe(0)
dispose()
expect(disconnect).toHaveBeenCalled()
sizes.files = 400
document.fonts.dispatchEvent(new Event('loadingdone'))
files.textContent = 'All files'
await Promise.resolve()
expect(level()).toBe(0)
})
it('reads the level of the toolbar around an element, and the deepest level outside one', () => {
const row = document.createElement('div')
const inside = document.createElement('button')
row.append(inside)
expect(foldOf(inside)).toBe(DEEPEST_FOLD)
row.setAttribute('data-fold', '1')
expect(foldOf(inside)).toBe(1)
})
@@ -0,0 +1,75 @@
// @vitest-environment jsdom
/** The changes toolbar's More menu: the rows of each fold level, their marks, and their actions. */
import { cleanup, fireEvent, render, within } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { en } from '../src/client/locales.ts'
import { ViewOptionsMenu, type ViewOptions } from '../src/client/ViewOptionsMenu.tsx'
const t = makeTranslate(en)
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
function mount(overrides: Partial<ViewOptions> = {}, visible = true, fold?: string) {
const options: ViewOptions = {
anyExpanded: false, hasFiles: true, toggleExpansion: vi.fn(), split: true, toggleSplit: vi.fn(), wrap: false, toggleWrap: vi.fn(),
hideTests: true, toggleTests: vi.fn(), refresh: vi.fn(), ...overrides,
}
const view = render(<div data-fold={fold}><ViewOptionsMenu options={options} visible={visible} t={t} /></div>)
const trigger = within(view.container).getByRole('button', { name: en['diff.moreOptions'] })
const rows = (): string[] => view.queryAllByRole('menuitem').map(row => row.textContent ?? '')
return { view, options, trigger, rows }
}
it('lists every folded control and marks the active toggles outside a measured toolbar', () => {
const m = mount()
fireEvent.click(m.trigger)
expect(m.trigger.getAttribute('aria-expanded')).toBe('true')
expect(m.rows()).toEqual([en['diff.expandAll'], en['diff.splitAria'], en['diff.wrapAria'], en['tests.hide'], en['diff.refresh']])
const marked = m.view.getAllByRole('menuitem').map(row => row.querySelector('svg') !== null)
expect(marked).toEqual([false, true, false, true, false])
fireEvent.click(m.trigger)
expect(m.rows()).toEqual([])
})
it.each([
['1', [en['diff.collapseAll'], en['diff.splitAria'], en['diff.wrapAria']]],
['2', [en['diff.collapseAll'], en['diff.splitAria'], en['diff.wrapAria'], en['tests.hide']]],
['3', [en['diff.collapseAll'], en['diff.splitAria'], en['diff.wrapAria'], en['tests.hide'], en['diff.refresh']]],
])('lists the controls folded at level %s', (level, expected) => {
const m = mount({ anyExpanded: true }, true, level)
fireEvent.click(m.trigger)
expect(m.rows()).toEqual(expected)
})
it('runs the chosen control and closes, omits the test switch without one, and stays closed in a hidden tab', () => {
const m = mount({ hideTests: undefined })
const choose = (name: string): void => {
fireEvent.click(m.trigger)
fireEvent.click(m.view.getByRole('menuitem', { name }))
expect(m.rows()).toEqual([])
}
choose(en['diff.expandAll'])
choose(en['diff.splitAria'])
choose(en['diff.wrapAria'])
choose(en['diff.refresh'])
const actions = [m.options.toggleExpansion, m.options.toggleSplit, m.options.toggleWrap, m.options.refresh]
expect(actions.map(action => vi.mocked(action).mock.calls.length))
.toEqual([1, 1, 1, 1])
fireEvent.click(m.trigger)
expect(m.rows()).not.toContain(en['tests.hide'])
fireEvent.keyDown(document, { key: 'Escape' })
expect(m.rows()).toEqual([])
const hidden = mount({ hasFiles: false }, false)
fireEvent.click(hidden.trigger)
expect(hidden.trigger.getAttribute('aria-expanded')).toBe('false')
})
it('toggles test files from the menu', () => {
const m = mount()
fireEvent.click(m.trigger)
fireEvent.click(m.view.getByRole('menuitem', { name: en['tests.hide'] }))
expect(m.options.toggleTests).toHaveBeenCalledTimes(1)
})
@@ -15,6 +15,7 @@
"src/panel.ts",
"src/parse.ts",
"src/patch-cache.ts",
"src/review-cache.ts",
"src/states.ts",
"src/types.ts",
"src/wildmatch.ts",
@@ -15,11 +15,11 @@
en: 1777e7bf6785f986
zh: e3daac1074ebb74d
/deepseek-ai-dsh-experimental-cua-macos/use-this-package:
en: e51a6c3625873430
zh: 0a6998897532a05f
en: 233423a8675de85d
zh: faf5cecb9999cfa7
/deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment:
en: 652b0ce8892e522c
zh: 101c20aa18b36c05
en: 1bf907f257ef6f90
zh: ed71613b8de260aa
/deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation:
en: 4e82b85a5aa72eee
zh: 4e004b7a205d8688
@@ -39,14 +39,14 @@
en: 2dbc22ffd1f8a717
zh: d4458872e75305d9
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/token-effect:
en: ab52b46d874fa8b9
zh: e87d3620ef77cb06
en: 86b0b7e406627a47
zh: 53ad627fb3521f28
/deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/kv-cache-effect:
en: a2c9acb5a4320dda
zh: e8d1586af60215c4
/deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work:
en: 4fefaf88ea9eefc6
zh: d3d18cfbccf8c20f
en: b362f9357fe79293
zh: a74f0e9cffb647bc
/deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note:
en: b836f01bd0bceb4a
zh: 8122fa08b2aa95fa
+17 -13
View File
@@ -41,7 +41,7 @@ For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugin
pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config
```
The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object reads initial AX silently without activating the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session.
The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object does not read AX or activate the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session.
Source builds default to `sourceSigning: ad-hoc`, without creating certificates or keychains. Changed binaries can require new permission grants. To reduce repeated grants during rebuilds and across worktrees, select an existing certificate and its absolute keychain path in the DSH home’s `cordis.patch.yml`; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`:
@@ -72,7 +72,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates
| `maxClipboardBytes` | `33554432` | Maximum original clipboard bytes preserved during a paste; oversized contents reject before replacement. |
| `pasteReadTimeoutMs` | `1000` | Clipboard read deadline after the Paste command returns; expiry reports `PASTE_NOT_CONSUMED`. |
| `maxAppMatches` | `20` | Maximum installed-app search matches; broader queries reject and require a narrower name. |
| `maxElements` / `maxDepth` | `2000` / `25` | Accessibility traversal limits. |
| `maxElements` / `maxDepth` | `5000` / `50` | Defaults for tree reads. Each read can raise or lower either value. Paste menu discovery always uses the configured limits. [Rationale](../../../.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md) |
| `maxClickHoldMs` | `5000` | Maximum explicit click hold in milliseconds; accepts nonnegative integers. Zero only permits immediate release. |
| `dragDurationMs` / `dragSteps` | `400` / `20` | Duration and movement segments for a drag. |
| `textEventIntervalMs` | `0.25` | Delay after each Unicode down/up event, from 0 to 999 ms. Keystroke timing is independent. |
@@ -89,9 +89,9 @@ Application consent is enforced before AX reads, window-title reads, screenshots
Raw `getState` exposes validated state fields and the complete text for the requested disclosure options. The native helper also returns structured element diagnostics with opaque string `elementId` values for native checks; the tool projection omits that duplicate array from model text and structured tool values.
AX observations show menu-bar entries by default. Use `app.getAccessibilityTree({ includeMenus: true })` to expand menu contents and `app.getAccessibilityTree({ details: true })` for identifiers, global-point bounds and complete action names. These options also apply to raw `getState`. Every read replaces the application's current snapshot; use element IDs from that read. Details do not bypass the configured node and depth limits. Truncation identifies the reached limit.
AX observations show menu-bar entries by default. Use `app.getAccessibilityTree({ includeMenus: true })` to expand menu contents and `app.getAccessibilityTree({ details: true })` for identifiers, global-point bounds and complete action names. These options also apply to raw `getState`. Every read replaces the application's current snapshot; use element IDs from that read. Pass `maxElements` or `maxDepth` to override either configured limit for one read. Truncation identifies the reached limit.
Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`.
Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. During tree observation, an AXValue or AXSelectedTextRange writability probe returning -25200 leaves that field unknown and preserves the remaining nodes. Actual writes remain strict; permission, communication and invalid-element errors still propagate. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`.
Observations emit by default and also return their value. In persistent PTC, use `void await app.getAccessibilityTree()` for one emitted copy, or `emit:false` and one explicit print. Capturing a screenshot after an emitted tree can fail independently; retain the successful AX output.
@@ -113,9 +113,11 @@ const window = await app.getWindow(windows[0].windowId)
void await window.getScreenshot()
```
Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` read their initial trees silently; choose the window by its observed title and bounds.
An independent floating panel has its own window ID. Select it from `app.getWindows()` to capture or click the panel.
`getWindow` reads its initial tree silently. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus.
Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` return without reading AX; choose the window from `getWindows()` by its title and bounds.
`getWindow` sends no native request; screenshots and pointer input reject a closed or foreign window. Read `getAccessibilityTree()` explicitly before element operations. Screenshots do not require a successful AX read. All coordinate input, including relative coordinates, requires a successful AX observation covering the window or a screenshot; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus.
Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemPointer: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemPointer: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input.
@@ -191,9 +193,9 @@ Setup and discovery:
- cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications.
- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid.
- cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation.
- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app.
- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app.
- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input.
- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
@@ -201,8 +203,8 @@ Setup and discovery:
## Accessibility tree
Available at app or window level depending on the platform.
Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.
- listActions(elementId: string) -> string[] — list the actions an element advertises.
- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none.
- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument.
@@ -210,7 +212,7 @@ Element ids are opaque strings from the latest successful tree; the object facad
- selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate.
## Simulated mouse
Use an explicit window for screenshots and pointer input.
Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot.
- getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG.
- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.
@@ -226,14 +228,14 @@ Available at app or window level depending on the platform.
- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
```
#### Token effect
Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Retained objects are not serialized into prompts by this package.
Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Retained objects are not serialized into prompts by this package. A higher default or per-read override can include more AX text in model input when the window has more nodes to visit. Each visible auxiliary window, such as a status item, menu or tooltip, adds one window record to `getWindows()` and raw `getState` output; it does not automatically add a screenshot.
#### KV Cache effect
@@ -241,6 +243,8 @@ Tool results append to Session history. Changing plugin configuration or tool pr
## Known Limitations and Deferred Work
The native operation deadline (`timeoutMs`), per-AX-call timeout (`axTimeoutMs`), and response size limit (`maxResponseBytes`) still apply to larger tree reads.
The queue orders individual native requests. Holding an app object does not reserve its application across a Session; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) grants no cross-call ownership. Capture RPCs that never return occupy the single capture slot; creating new app objects does not reset that system connection.
<a id="known-limitations-and-deferred-work"></a>
+17 -13
View File
@@ -41,7 +41,7 @@ provider 按当前界面语言生成引导和恢复文案,不支持的语言
pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config
```
配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回的对象静默读取初始 AX,不自动激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。
配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回对象时不读取 AX,也不激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。
源码构建默认使用 `sourceSigning: ad-hoc` 临时签名,不创建证书或钥匙串。二进制变化后可能需要重新授权。需要减少开发重建和跨 worktree 的授权次数时,在 DSH home 的 `cordis.patch.yml` 中选择已有证书及其钥匙串绝对路径;`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID:
@@ -72,7 +72,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
| `maxClipboardBytes` | `33554432` | 粘贴时保存原剪贴板内容的字节上限;超限会在替换前拒绝。 |
| `pasteReadTimeoutMs` | `1000` | Paste 命令返回后等待剪贴板读取的上限;到期返回 `PASTE_NOT_CONSUMED`。 |
| `maxAppMatches` | `20` | 已安装应用搜索的结果上限;范围过大的查询会被拒绝,需要缩小名称范围。 |
| `maxElements` / `maxDepth` | `2000` / `25` | 辅助功能树遍历限制。 |
| `maxElements` / `maxDepth` | `5000` / `50` | 读取树时的默认值。每次读取可单独调高或调低任一项。查找粘贴菜单始终使用配置值。[决策理由](../../../.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md) |
| `maxClickHoldMs` | `5000` | 显式点击按住时长的上限,单位为毫秒,接受非负整数。设为 0 时只允许立即松开。 |
| `dragDurationMs` / `dragSteps` | `400` / `20` | 拖动时长和移动分段数。 |
| `textEventIntervalMs` | `0.25` | 每个 Unicode 按下或抬起事件后的间隔,范围为 0 至 1000 毫秒。击键节奏独立。 |
@@ -89,9 +89,9 @@ CUA 工具在读取 AX、窗口标题、截图、激活和输入前检查应用
原始 `getState` 操作返回经过校验的状态字段,以及按本次披露选项生成的完整文本。原生 helper 还返回供原生检查使用的结构化元素诊断数组,其中 `elementId` 是不透明字符串;工具投影会从模型文本和结构化工具值中移除这份重复数组。
AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ includeMenus: true })` 展开菜单内容,使用 `app.getAccessibilityTree({ details: true })` 读取标识符、全局 point 坐标和完整动作名。原始 `getState` 也接受这两个选项。每次读取都会替换应用当前的快照;应使用该次读取返回的元素 ID。详情不会绕过配置的节点数和深度上限;截断提示会指明触发的上限。
AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ includeMenus: true })` 展开菜单内容,使用 `app.getAccessibilityTree({ details: true })` 读取标识符、全局 point 坐标和完整动作名。原始 `getState` 也接受这两个选项。每次读取都会替换应用当前的快照;应使用该次读取返回的元素 ID。传入 `maxElements` 或 `maxDepth` 可调整本次读取的上限。树被截断时会提示触发的上限。
实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。
实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。读树时,AXValue 或 AXSelectedTextRange 的可写性探测返回 -25200,会将该字段保留为未知并继续读取其他节点。实际写入仍严格校验;权限、通信和失效元素错误仍向上传播。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。
观察方法默认自动输出,同时返回结果。在 persistent PTC 中使用 `void await app.getAccessibilityTree()` 输出一次,或指定 `emit:false` 后自行打印一次。AX 输出后的截图可能单独失败,已成功取得的 AX 输出仍保留。
@@ -113,9 +113,11 @@ const window = await app.getWindow(windows[0].windowId)
void await window.getScreenshot()
```
使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 静默读取初始树;根据观察到的标题与位置选择窗口。
独立浮层有自己的窗口 ID。需要截图或点击浮层时,从 `app.getWindows()` 中选中它。
`getWindow` 静默读取初始树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。
使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 返回时不读取 AX;根据 `getWindows()` 中的标题与位置选择窗口。
`getWindow` 不发送原生请求;截图和指针输入会拒绝已关闭或属于其他应用的窗口。元素操作前须显式读取 `getAccessibilityTree()`。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)都要求先成功读取覆盖该窗口的 AX 或取得截图;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。
普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemPointer: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemPointer: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。
@@ -191,9 +193,9 @@ Setup and discovery:
- cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications.
- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid.
- cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation.
- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app.
- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app.
- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input.
- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
@@ -201,8 +203,8 @@ Setup and discovery:
## Accessibility tree
Available at app or window level depending on the platform.
Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.
- listActions(elementId: string) -> string[] — list the actions an element advertises.
- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none.
- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument.
@@ -210,7 +212,7 @@ Element ids are opaque strings from the latest successful tree; the object facad
- selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate.
## Simulated mouse
Use an explicit window for screenshots and pointer input.
Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot.
- getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG.
- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.
@@ -226,14 +228,14 @@ Available at app or window level depending on the platform.
- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
```
#### Token 影响
启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。本包不将保留的对象序列化进提示。
启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。本包不将保留的对象序列化进提示。窗口中有更多节点可读时,调高默认值或单次读取上限可能使进入模型的 AX 文本变长。每个可见辅助窗口(例如状态栏图标、菜单或工具提示)都会给 `getWindows()` 和原始 `getState` 的结果增加一条窗口记录。截图需要单独请求。
#### KV Cache 影响
@@ -241,6 +243,8 @@ Only if the task cannot be completed without moving the user’s pointer, call a
## 已知限制与后续工作
读取较大的树仍受原生操作超时(`timeoutMs`)、单次 AX 调用超时(`axTimeoutMs`)和响应大小限制(`maxResponseBytes`)约束。
队列只排序单次原生请求。持有 app 对象不会为 Session 保留应用,[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不分配跨调用所有权。一直不返回的系统截图 RPC 会占用唯一捕获槽位,重新创建 app 对象不会重置该系统连接。
<a id="known-limitations-and-deferred-work"></a>
@@ -18,14 +18,14 @@
en: 1435672513328c05
zh: 11e7a1e672410c10
/dsh-cua-native-helper/request-protocol:
en: 2a69d89b7fc95998
zh: 084575bb31fb40dd
en: 60db6c41c868f7db
zh: 1de5d504b2d84e61
/dsh-cua-native-helper/observation-and-input:
en: 7e63469ddd8c4e72
zh: dbc87b8d8953c7e7
en: e632562614b20e7b
zh: 254e70199bf151c8
/dsh-cua-native-helper/verification:
en: c87945aeec587bf5
zh: e5d69e4927e2fed3
en: d1c47a2f63350417
zh: 5277d8245529b5a3
/dsh-cua-native-helper/further-exploration:
en: 265e1927952ce6d7
zh: 7c35d9fd98b6e6c8
@@ -74,7 +74,7 @@ Successful `activate` returns `dispatched` and `foregroundChanged`. A known chan
| `findApps` | Installed matches `{id, displayName, path, isRunning, pid?}` from standard application directories or an absolute application path; discovery never launches them. |
| `getApp` | Running selection returns `{appHandle, pid, name, bundleId?, running: true, authorization}`. A stopped selection returns `{appHandle, name, bundleId?, running: false, authorization}` with no `pid`, and waits for Host consent. Ambiguous names fail. |
| `launchApp` | Host-only continuation after consent; starts the selected application without requesting activation, waits for launch completion and binds the handle to its verified process identity. |
| `listWindows` | Owned normal windows with `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. |
| `listWindows` | Owned WindowServer records: `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace, cacheOnly?}`. Space membership can be null. Only auxiliary windows that are offscreen, have zero area or are known to be on another Space carry `cacheOnly: true`. The Host observes their size but omits them from discovery. A scoped read can return its explicitly selected window; the private field never enters tool results. |
| `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include the opaque string `elementId`, role, title, value, description, identifier, bounds, actions, and enabled state. Element bounds are null or [x, y, width, height] in screen points; window input uses local points. These structured element diagnostics are retained by native checks and omitted by the model tool projection. Unavailable optional descriptive properties are null, and an unavailable action list is empty; permission, communication and window-discovery failures still reject the observation. |
| `listActions` | Provider-defined action names for one element as a string array; an element may advertise none. |
| `show` | `{dispatched: boolean, windowId, foregroundChanged}` records restoration dispatch. `windowId` is null when no window was selected; `foregroundChanged` is null when the sampled observation was unavailable. |
@@ -97,6 +97,8 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro
`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes.
Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt.
Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. No implicit fallback sends global desktop input.
`click.holdMs` is an optional nonnegative integer in milliseconds per press; zero adds no hold delay. Each connection supplies `maxClickHoldMs` to bound explicit holds. The diagnostic helper option `--max-click-hold-ms` defaults to 5000. Omission retains ordinary click timing. The complete gesture holds the request scheduler slot; cancellation, timeout and disconnect interrupt the hold and post the pending mouse-up before releasing that slot. Received events remain effective, and forced process termination cannot guarantee cleanup.
@@ -145,6 +147,8 @@ Run `python3 packages/experimental/cua-macos/native/tests/application_consent_e2
Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py` to verify signature-preserving extraction outside an enclosing `.app`, concurrent publication, and service teardown with uniquely signed fixtures.
Run `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py --helper /absolute/path/to/helper` to check independent panel discovery, screenshots, received clicks, hiding, resizing and destruction.
Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element IDs, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings.
Run `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence` to compare complete observations of the same owned AppKit window with 35 and 400 synthetic rows. Each helper receives one warmup and three alternating measured requests. All result fields must match except helper-generated app and snapshot IDs. The report keeps raw timings, byte counts, hashes and replies; it sets no CI speed threshold and makes no memory claim. Fixture startup can activate the application. Run without other desktop automation or compilation jobs.
@@ -74,7 +74,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
| `findApps` | 从标准应用目录或绝对应用路径返回已安装匹配项 `{id, displayName, path, isRunning, pid?}`;发现过程不启动应用。 |
| `getApp` | 运行中的选择返回 `{appHandle, pid, name, bundleId?, running: true, authorization}`。未运行的选择返回 `{appHandle, name, bundleId?, running: false, authorization}`,其中没有 `pid`,并等待 Host 授权。名称歧义会失败。 |
| `launchApp` | 授权后的 Host 专用续接操作;不请求激活,等待应用启动完成后将句柄绑定到已核实的进程身份。 |
| `listWindows` | 应用所属普通窗口,包含 `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 |
| `listWindows` | WindowServer 返回所属窗口的 `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace, cacheOnly?}`,Space 归属可能为 null。只有离屏、面积为零或已确定位于其他 Space 的辅助窗口带有 `cacheOnly: true`。Host 用这些记录更新尺寸,枚举时省略它们。窗口级观察仍可返回显式选中的目标,工具结果不含这个私有字段。 |
| `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含不透明字符串 `elementId`、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 |
| `listActions` | 一个元素由 provider 定义的动作名数组;元素可以不声明任何动作。 |
| `show` | `{dispatched: boolean, windowId, foregroundChanged}` 记录恢复分派。未选中窗口时 `windowId` 为 null;无法取得采样观察时 `foregroundChanged` 为 null。 |
@@ -97,6 +97,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。
窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。
点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。
`click.holdMs` 是可选的每次按住时长,单位为毫秒,接受非负整数;0 表示不额外等待。每个连接通过 `maxClickHoldMs` 限制显式按住时长。诊断 helper 的 `--max-click-hold-ms` 选项默认 5000。省略时保留普通点击时长。整个手势占用请求调度槽位;取消、超时和断开连接会中断等待,在释放槽位前发送对应的松开事件。已接收的事件仍然生效,进程被强制终止时无法保证清理。
@@ -145,6 +147,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 运行 `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py`,用独立签名的测试应用验证 helper 在外层 `.app` 之外保留签名发布、并发发布和服务退出。
运行 `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py --helper /absolute/path/to/helper`,验证独立浮层的发现、截图、实际点击,以及隐藏、调整大小和销毁后的行为。
构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素 ID,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。
运行 `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence`,对比同一自建 AppKit 窗口中 35 行和 400 行合成内容的完整观察。每个 helper 先预热一次,再交替测量三次。除 helper 生成的应用和快照 ID 外,结果字段必须一致。报告保留原始耗时、字节数、哈希和回复,不设置 CI 性能阈值,也不声称内存表现。fixture 启动可能激活应用。运行时避免其他桌面自动化或编译任务。
@@ -208,6 +208,12 @@ final class AXAccess {
guard error == .success else { throw failure(error, "read writability of \(name)") }
return value
}
/// Observation keeps unsupported writability unknown; mutation callers use strict writable checks.
static func observationWritability(role: String, probe: (String, Bool) throws -> Bool?) rethrows -> (value: Bool?, selection: Bool?) {
let value = AXTextNode.valueRoles.contains(role) ? try probe("AXValue", true) : nil
let selection = AXTextNode.textRoles.contains(role) ? try probe("AXSelectedTextRange", true) : nil
return (value, selection)
}
func requireEnabled(_ element: AXUIElement) throws {
if try boolean(element, "AXEnabled") == false { throw NativeFailure(code: "NATIVE_ERROR", message: "Accessibility element is disabled") }
}
@@ -570,12 +576,16 @@ final class AXAccess {
var lines = ["AX scope=\(requested == nil ? "application" : "window") offsets=UTF-16\(details ? " bounds=global-points" : "")"]
var elements: [JSONValue] = []
var indexed: [Int: AXUIElement] = [:]
func walk(_ element: AXUIElement, level: Int, depth: Int) throws {
var pending = roots.reversed().map { (element: $0, level: 0, depth: 0) }
func enqueueChildren(_ children: [AXUIElement], level: Int, depth: Int) {
for child in children.reversed() { pending.append((child, level, depth)) }
}
while let (element, level, depth) = pending.popLast() {
try cancellation.check()
let hash = CFHash(element)
if visited[hash, default: []].contains(where: { CFEqual($0, element) }) { return }
guard count < maxElements else { elementLimitReached = true; return }
guard depth <= maxDepth else { depthLimitReached = true; return }
if visited[hash, default: []].contains(where: { CFEqual($0, element) }) { continue }
guard count < maxElements else { elementLimitReached = true; break }
guard depth <= maxDepth else { depthLimitReached = true; continue }
visited[hash, default: []].append(element)
count += 1
let observation = try nodeObservation(attributes: metadata(element), fallback: { try self.attribute(element, $0) })
@@ -586,10 +596,11 @@ final class AXAccess {
let placeholder = try stringValue(observed("AXPlaceholderValue"), attribute: "AXPlaceholderValue")
let description = try stringValue(observed("AXDescription"), attribute: "AXDescription")
let actionNames = try self.actions(element)
let valueWritable = AXTextNode.valueRoles.contains(role) ? try writable(element, "AXValue") : nil
let writability = try Self.observationWritability(role: role) { try writable(element, $0, forDiscovery: $1) }
let valueWritable = writability.value
let enabled = try booleanValue(observed("AXEnabled"), attribute: "AXEnabled")
let selected = try booleanValue(observed("AXSelected"), attribute: "AXSelected")
let selectionWritable = AXTextNode.textRoles.contains(role) ? try writable(element, "AXSelectedTextRange") : nil
let selectionWritable = writability.selection
let selectedRange = AXTextNode.textRoles.contains(role) ? try textRange(observed("AXSelectedTextRange")) : nil
let selectedText = AXTextNode.textRoles.contains(role) ? try stringValue(observed("AXSelectedText"), attribute: "AXSelectedText") : nil
let identifier = try stringValue(observed("AXIdentifier"), attribute: "AXIdentifier")
@@ -609,8 +620,8 @@ final class AXAccess {
identifier: identifier, url: url, focused: focused, expanded: expanded)
node.validateSelection()
if node.transparent || (!addressable && !node.hasMeaning && role != "AXWindow" && role != "AXSheet") {
for child in try childValues(observed("AXChildren"), attribute: "AXChildren") { try walk(child, level: level, depth: depth + 1) }
return
enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level, depth: depth + 1)
continue
}
let index: Int? = addressable ? indexed.count : nil
if let index { indexed[index] = element }
@@ -633,10 +644,9 @@ final class AXAccess {
"selectedRange": node.selectedRange.map { .array([.number(Double($0.location)), .number(Double($0.length))]) } ?? .null,
]))
}
if role == "AXMenuBarItem" && !includeMenus { menusCollapsed = true; return }
for child in try childValues(observed("AXChildren"), attribute: "AXChildren") { try walk(child, level: level + 1, depth: depth + 1) }
if role == "AXMenuBarItem" && !includeMenus { menusCollapsed = true; continue }
enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level + 1, depth: depth + 1)
}
for root in roots { try walk(root, level: 0, depth: 0) }
if menusCollapsed { lines.append("Menu contents omitted; request includeMenus=true to expand.") }
let truncated = elementLimitReached || depthLimitReached
if truncated { lines.append(AXTextFormatter.truncation(maxElements: elementLimitReached ? maxElements : nil, maxDepth: depthLimitReached ? maxDepth : nil)) }
@@ -157,6 +157,9 @@ actor AXWorker {
return result
}
private func element(_ handle: String, _ params: RequestParameters) throws -> AXUIElement {
if let windowID = try params.optionalWindowID() {
_ = try NativePlatform.ownedWindow(validateIdentity(handle).pid, windowID)
}
let value = try snapshot(handle, params.string("snapshotId"))
let index = try params.elementIdIndex()
guard let element = value.elements[index] else { throw RequestParameters.invalid("elementId is absent from the selected snapshot") }
@@ -267,7 +270,7 @@ actor AXWorker {
}
let identity = try validateIdentity(handle)
if method == "listWindows" {
let windows = NativePlatform.windows().filter { $0.pid == identity.pid }
let windows = NativePlatform.applicationWindows(identity.pid)
// Remove closed window scopes using the current WindowServer identity set.
let ids = Set(windows.map(\.windowID))
snapshots = snapshots.filter { key, _ in key.appHandle != handle || (key.windowID.map { ids.contains($0) } ?? true) }
@@ -304,7 +307,7 @@ actor AXWorker {
let projection: AXProjection
do {
projection = try ax().project(identity: identity, windowID: window,
maxElements: params.integer("maxElements", in: 1...10000), maxDepth: params.integer("maxDepth", in: 1...100),
maxElements: params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: params.integer("maxDepth", in: NativeProtocol.depthRange),
includeMenus: params.optionalBoolean("includeMenus") ?? false, details: params.optionalBoolean("details") ?? false)
} catch let failure as NativeFailure {
throw Self.observationFailure(failure)
@@ -314,7 +317,7 @@ actor AXWorker {
try NativePlatform.requireAccessibility()
if let window { _ = try NativePlatform.ownedWindow(identity.pid, window) }
try cancellation.check()
let observedWindows = NativePlatform.windows().filter { $0.pid == identity.pid }
let observedWindows = NativePlatform.applicationWindows(identity.pid)
let id = try identifier("snapshot")
let scope = SnapshotScope(appHandle: handle, windowID: window)
snapshots[scope] = NativeSnapshot(id: id, scope: scope, elements: projection.indexed)
@@ -340,7 +343,7 @@ actor AXWorker {
return .paste(PastePlan(handle: handle, text: try params.string("text"), format: try params.optionalString("format") ?? "text",
maxBytes: try params.integer("maxClipboardBytes", in: 1024...Int.max),
readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)),
maxElements: try params.integer("maxElements", in: 1...10000), maxDepth: try params.integer("maxDepth", in: 1...100)))
maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange)))
case "sendKeyEvent":
try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId")) {
try ax().keyboardRecipient(identity, catalog: catalog)
@@ -135,12 +135,22 @@ enum NativePlatform {
guard CGPreflightScreenCaptureAccess() else { throw NativeFailure(code: "PERMISSION_DENIED", message: "Screen Recording permission is required for the responsible host/helper") }
}
static func windows(allLayers: Bool = false) -> [WindowInfo] {
guard let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] else { return [] }
let memberships = allLayers ? [:] : WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value })
let rows = windowRows().filter { allLayers || (($0[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0) == 0 }
return windowInfo(rows, includeSpaces: !allLayers)
}
/// App observations include floating panels and menus, with the same Space metadata as normal windows.
static func applicationWindows(_ pid: Int32) -> [WindowInfo] {
let rows = windowRows().filter { ($0[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == pid }
return windowInfo(rows, includeSpaces: true)
}
private static func windowRows() -> [[String: Any]] {
CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? []
}
private static func windowInfo(_ rows: [[String: Any]], includeSpaces: Bool) -> [WindowInfo] {
let memberships = includeSpaces
? WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value }) : [:]
return rows.compactMap { row in
let layer = (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0
guard allLayers || layer == 0,
let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value,
guard let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value,
let pid = (row[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { return nil }
let raw = row[kCGWindowBounds as String] as? [String: NSNumber] ?? [:]
let bounds = WindowBounds(x: raw["X"]?.doubleValue ?? 0, y: raw["Y"]?.doubleValue ?? 0,
@@ -148,7 +158,7 @@ enum NativePlatform {
return WindowInfo(windowID: id, pid: pid, appName: row[kCGWindowOwnerName as String] as? String ?? "",
title: row[kCGWindowName as String] as? String ?? "", bounds: bounds,
isOnScreen: (row[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue ?? false,
onCurrentSpace: memberships[id]?.onCurrentSpace)
onCurrentSpace: memberships[id]?.onCurrentSpace, layer: (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0)
}
}
static func frontPID() -> Int32? { WindowSpaces().frontPID() }
@@ -1,5 +1,7 @@
// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.
enum NativeProtocol {
static let elementRange = 1...100000
static let depthRange = 1...512
static let fields: [String: Set<String>] = [
"activate": ["appHandle"],
"applicationIcons": ["paths"],
@@ -138,12 +138,20 @@ struct WindowInfo: Sendable {
let bounds: WindowBounds
let isOnScreen: Bool
let onCurrentSpace: Bool?
var layer: Int = 0
/// Normal windows remain discoverable for restoration, including when minimized or on another Space.
var isDiscoverable: Bool {
layer == 0 || (isOnScreen && onCurrentSpace != false && bounds.width > 0 && bounds.height > 0)
}
var json: JSONValue {
.object([
var record: [String: JSONValue] = [
"windowId": .number(Double(windowID)),
"appName": .string(appName), "title": .string(title), "bounds": bounds.json,
"isOnScreen": .bool(isOnScreen), "onCurrentSpace": onCurrentSpace.map(JSONValue.bool) ?? .null,
])
]
if !isDiscoverable { record["cacheOnly"] = .bool(true) }
return .object(record)
}
}
@@ -1,6 +1,8 @@
/** Generate macOS admission artifacts from the shared CUA operation definitions. */
import { readFile, writeFile } from 'node:fs/promises'
import { z } from 'zod'
import { AX_TRAVERSAL_MAX } from '../src/ax-limits.ts'
import { NativeResourceParameters } from '@deepseek-ai/dsh-cua/protocol'
import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema'
import { PermissionGuideParameters, PermissionSettingsParameters } from '../src/permission-guide.ts'
@@ -9,7 +11,13 @@ import { PermissionGuideParameters, PermissionSettingsParameters } from '../src/
* @returns Native JSON Schema and Swift field/enum tables, including private continuations.
*/
export function renderNativeProtocol(): { json: string; swift: string } {
const traversal = {
maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements),
maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth),
}
const { fields, enums, json } = nativeProtocol({
getState: NativeResourceParameters.getState.extend(traversal),
paste: NativeResourceParameters.paste.extend(traversal),
sendKeyEvent: z.object({ runId: z.string().min(1) }),
mouseMove: z.object({ useSystemPointer: z.boolean().optional() }),
requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters,
@@ -20,6 +28,8 @@ export function renderNativeProtocol(): { json: string; swift: string } {
const swift = [
'// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.',
'enum NativeProtocol {',
` static let elementRange = 1...${AX_TRAVERSAL_MAX.maxElements}`,
` static let depthRange = 1...${AX_TRAVERSAL_MAX.maxDepth}`,
' static let fields: [String: Set<String>] = [',
...[...fields].sort(([a], [b]) => a.localeCompare(b)).map(([method, names]) => ` ${JSON.stringify(method)}: [${quoted(names)}],`),
' ]',
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$comment": "Generated from the shared CUA operation schema. Do not edit.",
"title": "dsh-cua native request",
"description": "Host resource fields and private continuations are not model tool parameters. App handles and snapshots belong to one helper; coordinates use window-local native units.",
"description": "The Host resolves resource limits before dispatch. Private continuations are available only to the Host. App handles and snapshots belong to one helper; coordinates use window-local native units.",
"oneOf": [
{
"type": "object",
@@ -250,12 +250,12 @@
"maxElements": {
"type": "integer",
"minimum": 1,
"maximum": 10000
"maximum": 100000
},
"maxDepth": {
"type": "integer",
"minimum": 1,
"maximum": 100
"maximum": 512
}
},
"required": [
@@ -944,12 +944,12 @@
"maxElements": {
"type": "integer",
"minimum": 1,
"maximum": 10000
"maximum": 100000
},
"maxDepth": {
"type": "integer",
"minimum": 1,
"maximum": 100
"maximum": 512
}
},
"required": [
@@ -0,0 +1,110 @@
import AppKit
import Darwin
final class FloatingPanel: NSPanel {
override var canBecomeKey: Bool { false }
}
/// Publishes actual window geometry and received actions independently of the helper.
final class FloatingWindowFixture: NSObject, NSApplicationDelegate {
let statePath: String
var main: NSWindow!
var panel: FloatingPanel!
var button: NSButton!
var closeButton: NSButton!
var panelID = 0
var count = 0
var resized = false
var closed = false
var panelSize: [CGFloat] = []
var buttonPoint: [CGFloat] = []
var resizeControl: DispatchSourceSignal?
var visibilityControl: DispatchSourceSignal?
var observer: Timer?
init(statePath: String) { self.statePath = statePath }
func applicationDidFinishLaunching(_ notification: Notification) {
main = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 420, height: 300),
styleMask: [.titled, .closable], backing: .buffered, defer: false)
main.title = "Floating fixture main"
closeButton = NSButton(title: "Close panel", target: self, action: #selector(closePanel))
closeButton.frame = NSRect(x: 280, y: 30, width: 120, height: 35)
main.contentView!.addSubview(closeButton)
panel = FloatingPanel(contentRect: NSRect(x: 220, y: 250, width: 240, height: 140),
styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false)
panel.title = "Floating fixture panel"
panel.level = .floating
panel.hidesOnDeactivate = false
for window in [main!, panel!] {
window.isReleasedWhenClosed = false
window.animationBehavior = .none
window.collectionBehavior = [.canJoinAllApplications, .stationary]
}
button = NSButton(title: "Increment floating panel", target: self, action: #selector(increment))
button.frame = NSRect(x: 20, y: 45, width: 200, height: 40)
panel.contentView!.addSubview(button)
main.makeKeyAndOrderFront(nil)
NSApplication.shared.activate(ignoringOtherApps: true)
panel.orderFrontRegardless()
panelID = panel.windowNumber
signal(SIGUSR1, SIG_IGN)
let visibility = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main)
visibility.setEventHandler { [weak self] in
guard let self, let panel = self.panel else { return }
if panel.isVisible { panel.orderOut(nil) } else { panel.orderFrontRegardless() }
self.persist()
}
visibility.resume()
visibilityControl = visibility
signal(SIGUSR2, SIG_IGN)
let control = DispatchSource.makeSignalSource(signal: SIGUSR2, queue: .main)
control.setEventHandler { [weak self] in
guard let self else { return }
self.panel.setContentSize(NSSize(width: 280, height: 180))
self.resized = true
self.persist()
}
control.resume()
resizeControl = control
// WindowServer visibility and frame updates settle after AppKit requests return.
observer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in self?.persist() }
persist()
print("READY")
fflush(stdout)
}
@objc func increment() { count += 1; persist() }
@objc func closePanel() {
panel.close()
panel = nil
button = nil
closed = true
persist()
}
func persist() {
let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? []
let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID }
if let panel, let button {
let rect = button.convert(button.bounds, to: nil)
panelSize = [panel.frame.width, panel.frame.height]
buttonPoint = [rect.midX, panel.frame.height - rect.midY]
}
let bounds = row?[kCGWindowBounds as String] as? [String: NSNumber]
let closeRect = closeButton.convert(closeButton.bounds, to: nil)
let data = try! JSONSerialization.data(withJSONObject: [
"pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID,
"panelLayer": row?[kCGWindowLayer as String] ?? -1,
"panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false,
"serverSize": [bounds?["Width"]?.doubleValue ?? 0, bounds?["Height"]?.doubleValue ?? 0],
"panelSize": panelSize, "buttonPoint": buttonPoint,
"closePoint": [closeRect.midX, main.frame.height - closeRect.midY],
"count": count, "resized": resized, "closed": closed,
])
try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic)
}
}
let app = NSApplication.shared
app.setActivationPolicy(.regular)
let fixture = FloatingWindowFixture(statePath: CommandLine.arguments[1])
app.delegate = fixture
app.run()
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more