diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index 3e32b6eb92..81912accfe 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index cce266e52b..6d9aea0408 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 5135dc9be8..ceed375ff3 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -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)负责连接生命期。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml new file mode 100644 index 0000000000..0e2260eefc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md new file mode 100644 index 0000000000..37a04b4aa7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md @@ -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. diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md new file mode 100644 index 0000000000..536a6908eb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md @@ -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)。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index f779b7be73..83daa37ac0 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 2b852ad824..32b6fb4edc 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -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 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 660bd81d38..6e8438080c 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -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 diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml new file mode 100644 index 0000000000..eb6f1712fb --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md new file mode 100644 index 0000000000..d0c4cf0d89 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md new file mode 100644 index 0000000000..0dc9c99e2a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md @@ -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 评论只能立即发布或添加到输入框。早期面板留下的评论草稿会一直保留,直到用户把它们加入评审、发布、删除,或关闭所在页签。 diff --git a/apps/web/tests/expected/forge-panel/discard-review.expected.md b/apps/web/tests/expected/forge-panel/discard-review.expected.md new file mode 100644 index 0000000000..a31563daba --- /dev/null +++ b/apps/web/tests/expected/forge-panel/discard-review.expected.md @@ -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] diff --git a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md index e19aec25eb..a3d5433481 100644 --- a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md +++ b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md @@ -16,5 +16,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/panel.expected.md b/apps/web/tests/expected/forge-panel/panel.expected.md index f71db0bd64..d6573ae3a6 100644 --- a/apps/web/tests/expected/forge-panel/panel.expected.md +++ b/apps/web/tests/expected/forge-panel/panel.expected.md @@ -13,5 +13,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/reference.expected.md b/apps/web/tests/expected/forge-panel/reference.expected.md index 4a34c8f7c9..2db6846496 100644 --- a/apps/web/tests/expected/forge-panel/reference.expected.md +++ b/apps/web/tests/expected/forge-panel/reference.expected.md @@ -8,5 +8,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/review-record.expected.md b/apps/web/tests/expected/forge-panel/review-record.expected.md index 3e678d6071..aef059b24e 100644 --- a/apps/web/tests/expected/forge-panel/review-record.expected.md +++ b/apps/web/tests/expected/forge-panel/review-record.expected.md @@ -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 "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/review-summary-required.expected.md b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md index 3e384b28e1..2a56eddd38 100644 --- a/apps/web/tests/expected/forge-panel/review-summary-required.expected.md +++ b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md @@ -10,5 +10,6 @@ - text: 批准 - radio "请求更改" [checked] - text: 请求更改 + - button "丢弃评审" - button "取消" - button "提交评审" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md b/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md new file mode 100644 index 0000000000..0a6b4b489c --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md @@ -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 "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/review-threads.expected.md b/apps/web/tests/expected/forge-panel/review-threads.expected.md index f44d04fb59..ff5dc738a5 100644 --- a/apps/web/tests/expected/forge-panel/review-threads.expected.md +++ b/apps/web/tests/expected/forge-panel/review-threads.expected.md @@ -14,14 +14,17 @@ - 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" @@ -53,9 +56,12 @@ - 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" @@ -77,6 +83,9 @@ - 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 "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/submit-review.expected.md b/apps/web/tests/expected/forge-panel/submit-review.expected.md index 0687f7ba99..8affefb880 100644 --- a/apps/web/tests/expected/forge-panel/submit-review.expected.md +++ b/apps/web/tests/expected/forge-panel/submit-review.expected.md @@ -10,5 +10,6 @@ - text: 批准 - radio "请求更改" [checked] - text: 请求更改 + - button "丢弃评审" - button "取消" - button "提交评审" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 7fdb3e9223..389d5a5d8c 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -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, @@ -50,7 +51,17 @@ const run = promisify(execFile) * 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. The review thread read serves - * `threads.json` as its one page of threads, or no threads without it. Every invocation is appended to `calls.jsonl`. + * `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. `overview.json` replaces fields + * of pull request 7, such as its checks and reviewers, and the viewer's + * permission. Viewed marks start from `viewed.json`, keyed by path; reading + * them fails while `viewed.unreadable` exists. 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, the pending review of `lin` with its new threads, which a + * submission publishes, viewed marks, which fail while `viewed.refused` exists, + * review requests, and branch updates. Each mutation is appended to + * `mutations.jsonl`, each REST rerun to `reruns.jsonl`, and every invocation to `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -127,27 +138,110 @@ if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vn process.stdout.write(text) process.exit(0) } +if (args[0] === 'api' && args[3] === '--method' && args[4] === 'POST' && args[5].startsWith('repos/octo/demo/actions/')) { + appendFileSync(join(here, 'reruns.jsonl'), args[5] + '\\n') + state.reruns = [...state.reruns ?? [], args[5]] + save() + process.exit(0) +} 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 === 'markFileAsViewed' || field === 'unmarkFileAsViewed') { + if (existsSync(join(here, 'viewed.refused'))) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ type: 'FORBIDDEN', message: readFileSync(join(here, 'viewed.refused'), 'utf8') }] })) + process.exit(0) + } + state.viewed = { ...state.viewed, [variables.path]: field === 'unmarkFileAsViewed' ? 'UNVIEWED' : 'VIEWED' } + payload = { clientMutationId: null } + } else if (field === 'requestReviews') { + // The reviewer lookup names each user \`user-\`. + state.requested = [...new Set([...state.requested ?? [], ...(variables.input.userIds ?? []).map(id => id.slice('user-'.length))])] + payload = { clientMutationId: null } + } else if (field === 'updatePullRequestBranch') { + if (variables.input.expectedHeadOid !== 'a'.repeat(40)) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ type: 'UNPROCESSABLE', message: 'expected head sha did not match current head ref' }] })) + process.exit(0) + } + state.updated = variables.input.updateMethod + payload = { clientMutationId: null } + } else 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) => ({ __typename: 'CheckRun', id: 'check-' + databaseId, name, status: 'COMPLETED', conclusion, databaseId, detailsUrl: 'https://github.com/octo/demo/actions/runs/1', startedAt: '2026-10-09T00:00:00Z', completedAt, - checkSuite: { app: { id: 'github-actions' }, workflowRun: { event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 1, event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, }) + const overview = existsSync(join(here, 'overview.json')) ? JSON.parse(readFileSync(join(here, 'overview.json'), 'utf8')) : {} + const none = { totalCount: 0, nodes: [] } + const requested = (state.requested ?? []).map(login => ({ asCodeOwner: false, requestedReviewer: { __typename: 'User', login, avatarUrl: null } })) + const requests = overview.reviewRequests ?? none + const reviewing = { totalCount: requests.totalCount + requested.length, nodes: [...requests.nodes, ...requested] } const pulls = { 7: { id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), baseRefOid: BASE, baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] }, - commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: { + commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: overview.checks ?? { pageInfo: { hasNextPage: true, endCursor: 'checks-100' }, nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)), } } } }] }, + viewerCanUpdateBranch: (overview.viewerCanUpdateBranch ?? false) && state.updated === undefined, canBeRebased: overview.canBeRebased ?? false, + reviewRequests: reviewing, latestReviews: overview.latestReviews ?? none, latestOpinionatedReviews: overview.latestOpinionatedReviews ?? none, + closingIssuesReferences: overview.closingIssues ?? none, + ...overview.mergeable === undefined ? {} : { mergeable: overview.mergeable }, }, 9: { id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', @@ -158,6 +252,8 @@ if (args[0] === 'api' && args[1] === 'graphql') { commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], } } } }] }, + viewerCanUpdateBranch: false, canBeRebased: true, reviewRequests: none, latestReviews: none, latestOpinionatedReviews: none, + closingIssuesReferences: none, }, } if (query.includes('commits(first: $first')) { @@ -171,16 +267,74 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } } })) process.exit(0) } - if (query.includes('{ id headRefOid reviewThreads(first: $first)')) { + const number = Number(args.find(arg => arg.startsWith('number='))?.slice('number='.length)) + if (query.includes('files(first: $first')) { + if (existsSync(join(here, 'viewed.unreadable'))) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ message: readFileSync(join(here, 'viewed.unreadable'), 'utf8') }] })) + process.exit(0) + } + const paths = readFileSync(join(here, 'pr-' + number + '.diff'), 'utf8').split('\\n') + .filter(line => line.startsWith('diff --git ')).map(line => line.split(' b/').at(-1)) + const marks = { ...existsSync(join(here, 'viewed.json')) ? JSON.parse(readFileSync(join(here, 'viewed.json'), 'utf8')) : {}, ...state.viewed } + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, files: { + totalCount: paths.length, pageInfo: { hasNextPage: false, endCursor: null }, + nodes: paths.map(path => ({ path, viewerViewedState: marks[path] ?? 'UNVIEWED' })), + } } } } })) + process.exit(0) + } + if (query.includes('user(login: $u0)')) { + const users = Object.fromEntries(args.flatMap(arg => /^u\\d+=/.test(arg) ? [[arg.split('=')[0], { id: 'user-' + arg.slice(arg.indexOf('=') + 1) }]] : [])) + process.stdout.write(JSON.stringify({ data: users })) + process.exit(0) + } + if (query.includes('assignableUsers')) { + const people = [['mona', 'Mona Lisa'], ['hubot', null], ['lin-reviewer', 'Lin']].map(([login, name]) => ({ login, name, avatarUrl: null })) + const search = args.find(arg => arg.startsWith('search=')).slice('search='.length) + process.stdout.write(JSON.stringify({ data: { repository: { + assignableUsers: { nodes: people.filter(person => person.login.includes(search)) }, + pullRequest: { author: { login: 'octo' }, suggestedReviewers: [{ reviewer: people[2] }] }, + } } })) + process.exit(0) + } + if (query.includes('viewer { login }')) { const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) - const threads = existsSync(join(here, 'threads.json')) ? JSON.parse(readFileSync(join(here, 'threads.json'), 'utf8')) : [] - process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { id: 'pull-' + number, - headRefOid: pulls[number].headRefOid, reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: threads } } } } })) + 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 } } } })) + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { + id: 'pull-' + number, headRefOid: pulls[number].headRefOid, baseRefOid: BASE, + } } } })) process.exit(0) } if (query.includes('node(id: $id)')) { @@ -191,7 +345,8 @@ if (args[0] === 'api' && args[1] === 'graphql') { process.exit(0) } const settings = { - squashMergeAllowed: true, mergeCommitAllowed: true, rebaseMergeAllowed: true, viewerPermission: 'WRITE', viewerDefaultMergeMethod: 'SQUASH', + squashMergeAllowed: true, mergeCommitAllowed: true, rebaseMergeAllowed: true, viewerPermission: overview.viewerPermission ?? 'WRITE', + viewerDefaultMergeMethod: 'SQUASH', } const data = {} let repository @@ -551,7 +706,7 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi await header.click() const change = page.locator(`[data-forge-change="${PULL}"]`) await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 }) - await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() + await change.getByText('等待评审', { exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'), await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE) await expect.poll(async () => { @@ -638,7 +793,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const title = change.getByRole('link', { name: 'Add the pull request panel', exact: true }) await title.waitFor({ timeout: 20_000 }) // The only open change request starts expanded. - await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() + await change.getByText('等待评审', { exact: true }).waitFor() // The random branch suffix can read as a duration, so the branch is replaced before the capture normalizes durations. await compareOrRefreshGolden(join(EXPECTED, 'panel.expected.md'), await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE) @@ -647,7 +802,9 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const checksRow = change.getByRole('button', { name: /^检查/ }) await checksRow.click() const checks = page.getByRole('menu') - await expect.poll(() => checks.getByRole('menuitem').allTextContents()).toEqual([expect.stringMatching(/^test/), expect.stringMatching(/^lint/)]) + // Failed checks are listed with the rerun; passed ones wait behind a toggle. + await expect.poll(() => checks.getByRole('menuitem').allTextContents()) + .toEqual(['重跑失败项', expect.stringMatching(/^test/), '显示其余 1 项(通过、跳过)']) const afterChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) expect(afterChecks.filter(args => args.includes('id=rollup-7'))).toHaveLength(1) await page.keyboard.press('Escape') @@ -1028,7 +1185,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 }) @@ -1059,11 +1219,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 }) @@ -1087,7 +1252,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) @@ -1360,7 +1525,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' }) @@ -1458,7 +1625,7 @@ it.skipIf(MODE === 'record')('keeps tall branch and changed-file menus aligned w expect(tripwire.warnings).toEqual([]) }) -it.skipIf(MODE === 'record')('keeps localized status columns separate and long file lists inside one vertical scroller', async () => { +it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs and keeps long file lists inside one vertical scroller', async () => { const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-layout') await page.locator('[data-forge-current-branch]').waitFor() await compareOrRefreshGolden(join(EXPECTED, 'worktree-option.expected.md'), @@ -1514,38 +1681,36 @@ it.skipIf(MODE === 'record')('keeps localized status columns separate and long f for (const width of [1280, 390]) { await page.setViewportSize({ width, height: 700 }) await expect.poll(() => change.evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(width) - await change.getByText(labels[3], { exact: true }).hover() + // Each row names its fact for assistive technology only; the row starts with its glyph. + const rowOf = (label: string) => change.getByText(label, { exact: true }).locator('xpath=../..') + await rowOf(labels[3]).hover() + const offsets = new Set() for (const label of labels) { - const geometry = await change.getByText(label, { exact: true }).evaluate((element) => { - const value = element.nextElementSibling - if (value === null) throw new Error('Status label must have a value') - const range = document.createRange() - range.selectNodeContents(element) - const name = range.getBoundingClientRect() - const content = value.getBoundingClientRect() - const row = element.parentElement! - const icon = element.previousElementSibling! + const geometry = await rowOf(label).evaluate((row) => { + const icon = row.firstElementChild! + const cell = icon.nextElementSibling! + const value = cell.lastElementChild! + const trailing = cell.nextElementSibling?.matches('[class*="rowTrailing"]') === true ? cell.nextElementSibling : null const rowRect = row.getBoundingClientRect() + const content = value.getBoundingClientRect() return { - gap: content.left - name.right, iconInset: icon.getBoundingClientRect().left - rowRect.left, rowInset: rowRect.left - row.closest('[data-forge-change]')!.getBoundingClientRect().left, - labelWidth: element.getBoundingClientRect().width, valueOffset: content.left - rowRect.left, - right: content.right, + gap: trailing === null ? 8 : trailing.getBoundingClientRect().left - content.right, + right: Math.max(content.right, trailing?.getBoundingClientRect().right ?? 0), width: document.documentElement.clientWidth, } }) - expect(geometry.gap).toBeGreaterThanOrEqual(8) expect(geometry.iconInset).toBe(8) expect(geometry.rowInset).toBeGreaterThanOrEqual(6) expect(geometry.rowInset).toBeLessThanOrEqual(7) - if (locale === 'zh') { - expect(geometry.labelWidth).toBe(32) - expect(geometry.valueOffset).toBe(76) - } + offsets.add(geometry.valueOffset) + expect(geometry.gap).toBeGreaterThanOrEqual(8) expect(geometry.right).toBeLessThanOrEqual(geometry.width) } + // Every value starts in the same column after its glyph. + expect([...offsets]).toEqual([32]) } } expect(tripwire.pageErrors).toEqual([]) @@ -1726,7 +1891,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([]) }) @@ -1785,6 +1950,8 @@ it.skipIf(MODE === 'record')('reviews a change request by layer, hides test file await page.keyboard.press('v') await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed') await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3') + // Each mark stays disabled until GitHub saved it. + await expect.poll(() => view.getByRole('checkbox', { disabled: true }).count()).toBe(0) await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'), await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) @@ -1863,18 +2030,21 @@ 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` then `octo`. */ +/** + * 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, bodies: readonly string[], commit: string = HEAD7, ): Record { return { id, isOutdated: false, isResolved: false, path: 'src/panel.ts', diffSide: 'RIGHT', startDiffSide: null, line: null, startLine: null, - originalLine: null, originalStartLine: null, subjectType: 'LINE', ...fields, + 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, - author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null }, + viewerCanUpdate: index === 0, viewerCanDelete: index === 0, author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null }, })) }, } } @@ -1897,10 +2067,14 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an 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, under the new side. - expect(await onLine.evaluate(card => card.previousElementSibling?.querySelector('[data-new-line]')?.textContent)).toBe('export const n2 = \'two\'') - expect(await panel.locator('[data-forge-thread="old-side"]').evaluate(card => card.previousElementSibling?.querySelector('[data-old-line]')?.textContent)) - .toBe('export const n15 = 15') + // 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() @@ -1955,12 +2129,75 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an 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('{ id headRefOid reviewThreads(first: $first)'))) + 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' @@ -2008,3 +2245,294 @@ 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([]) }) + +/** One GraphQL mutation the GitHub CLI double received: the mutation field and its variables. */ +interface GhMutation { + readonly field: string + readonly variables: Record +} + +/** GraphQL mutations the GitHub CLI double received, in order. */ +async function mutationsOf(root: string): Promise { + const text = await readFile(join(root, 'mutations.jsonl'), 'utf8').catch(() => '') + return text.split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as GhMutation) +} + +/** REST paths of the check reruns the GitHub CLI double received, in order. */ +async function rerunsOf(root: string): Promise { + return (await readFile(join(root, 'reruns.jsonl'), 'utf8').catch(() => '')).split('\n').filter(line => line.length > 0) +} + +it.skipIf(MODE === 'record')('reads and saves the viewed files of a change request on GitHub, keeping chosen commits in the browser', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-viewed-sync') + await writeReviewFixture(root) + await writeFile(join(root, 'viewed.json'), JSON.stringify({ 'docs/panel.md': 'VIEWED', 'src/panel.ts': 'DISMISSED' })) + const { view } = await openReview(page, scaffold) + const docs = view.locator('[data-forge-diff-file="docs/panel.md"]') + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + const manifest = view.locator('[data-forge-diff-file="package.json"]') + const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true }) + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed') + expect(await docs.getAttribute('data-expanded')).toBe(null) + await expect.poll(() => panel.getAttribute('data-viewed')).toBe('changed') + await panel.getByText('有新改动', { exact: true }).waitFor() + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 6') + + await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).check() + await expect.poll(() => manifest.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(async () => (await mutationsOf(root)).map(entry => [entry.field, entry.variables.path])) + .toEqual([['markFileAsViewed', 'package.json']]) + await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).uncheck() + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed') + await expect.poll(async () => (JSON.parse(await readFile(join(root, 'state.json'), 'utf8')) as { readonly viewed?: Record }).viewed) + .toEqual({ 'package.json': 'VIEWED', 'docs/panel.md': 'UNVIEWED' }) + + // A refused mark returns to what GitHub keeps and says why. + await writeFile(join(root, 'viewed.refused'), 'Resource not accessible by integration') + const spec = view.locator('[data-forge-diff-file="src/panel.spec.ts"]') + await spec.getByRole('checkbox', { name: '将 panel.spec.ts 标记为已审阅', exact: true }).check() + await page.getByText('已审阅状态未能保存到 GitHub:Resource not accessible by integration', { exact: true }).waitFor() + await expect.poll(() => spec.getAttribute('data-viewed')).toBe('unviewed') + await rm(join(root, 'viewed.refused')) + + // GitHub keeps the marks, so a reload reads them again. + await page.reload() + await view.locator('[data-forge-diff-file="package.json"]').waitFor({ timeout: 20_000 }) + await expect.poll(() => manifest.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed') + + // Without GitHub's marks no file can be marked, and the notice offers to read them again. + await writeFile(join(root, 'viewed.unreadable'), 'API rate limit exceeded') + await view.getByRole('button', { name: '刷新变更', exact: true }).click() + await view.getByText('未能读取 GitHub 上的已审阅状态,暂时不能标记文件:API rate limit exceeded', { exact: true }).waitFor({ timeout: 20_000 }) + expect(await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).isDisabled()).toBe(true) + await rm(join(root, 'viewed.unreadable')) + await view.getByRole('button', { name: '重试', exact: true }).click() + await expect.poll(() => manifest.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('viewed') + expect(await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).isDisabled()).toBe(false) + + // Chosen commits keep their marks in the browser. + await view.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click() + await page.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts']) + const before = (await mutationsOf(root)).length + await spec.getByRole('checkbox', { name: '将 panel.spec.ts 标记为已审阅', exact: true }).check() + await expect.poll(() => spec.getAttribute('data-viewed')).toBe('viewed') + expect((await mutationsOf(root)).length).toBe(before) + + await page.setViewportSize({ width: 390, height: 844 }) + await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click() + await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6) + expect(tripwire.pageErrors).toEqual([]) +}) + +/** Pull request 7 with failed, running, passed, and skipped checks, five reviewers, a branch behind its base, and two closing issues. */ +const OVERVIEW = { + viewerPermission: 'WRITE', + viewerCanUpdateBranch: true, + canBeRebased: true, + checks: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [ + ...[['node 24 / static', 'FAILURE', 11], ['windows / coverage', 'FAILURE', 12], ['lint', 'SUCCESS', 13], ['typecheck', 'SUCCESS', 14], + ['docs', 'SKIPPED', 15]].map(([name, conclusion, id]) => ({ + __typename: 'CheckRun', id: `check-${String(id)}`, name, status: 'COMPLETED', conclusion, databaseId: id, + detailsUrl: `https://github.com/octo/demo/actions/runs/41/job/${String(id)}`, startedAt: '2026-10-09T00:00:00Z', completedAt: '2026-10-09T00:04:12Z', + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 41, event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, + })), + { + __typename: 'CheckRun', id: 'check-16', name: 'e2e / web', status: 'IN_PROGRESS', conclusion: null, databaseId: 16, + detailsUrl: 'https://github.com/octo/demo/actions/runs/42/job/16', startedAt: '2026-10-09T00:00:00Z', completedAt: null, + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 42, event: 'pull_request', workflow: { id: 'e2e', name: 'E2E' } } }, + }, + { __typename: 'StatusContext', context: 'ci/jenkins', state: 'FAILURE', targetUrl: 'https://ci.example.test/7', createdAt: '2026-10-09T00:01:00Z' }, + ], + }, + reviewRequests: { totalCount: 2, nodes: [ + { asCodeOwner: false, requestedReviewer: { __typename: 'User', login: 'lin-reviewer', avatarUrl: null } }, + { asCodeOwner: true, requestedReviewer: { __typename: 'Team', combinedSlug: 'octo/forge', avatarUrl: null } }, + ] }, + latestReviews: { totalCount: 1, nodes: [{ state: 'COMMENTED', commit: { oid: HEAD7 }, author: { __typename: 'Bot', login: 'review-bot', avatarUrl: null } }] }, + latestOpinionatedReviews: { totalCount: 2, nodes: [ + { state: 'CHANGES_REQUESTED', commit: { oid: '1'.repeat(40) }, author: { __typename: 'User', login: 'zhou-dev', avatarUrl: null } }, + { state: 'APPROVED', commit: { oid: HEAD7 }, author: { __typename: 'User', login: 'qian-dev', avatarUrl: null } }, + ] }, + closingIssues: { totalCount: 2, nodes: [ + { number: 6, title: 'Show review progress in the panel', state: 'OPEN', url: 'https://github.com/octo/demo/issues/6', + repository: { name: 'demo', owner: { login: 'octo' } } }, + { number: 12, title: 'Rerun failed checks from DSH', state: 'OPEN', url: 'https://github.com/octo/tracker/issues/12', + repository: { name: 'tracker', owner: { login: 'octo' } } }, + ] }, +} + +it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state in one line each and acts on them from their menus', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-overview') + await writeFile(join(root, 'overview.json'), JSON.stringify(OVERVIEW)) + const { settled } = await sendPrompt(page, scaffold) + const session = scaffold.ctx.sessions.get(await settled) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + const card = page.locator(`[data-forge-change="${PULL}"]`) + // The card chooses its default expansion once its first status arrives, which names the title. + await card.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 }) + if (await card.getAttribute('data-expanded') === null) await card.getByRole('button', { name: '展开 #7', exact: true }).click() + const checks = card.locator('[data-forge-checks]') + await expect.poll(() => checks.textContent(), { timeout: 20_000 }).toBe('检查3 项失败 · 1 项进行中') + await expect.poll(() => card.locator('[data-forge-threads]').getAttribute('data-forge-threads')).toBe('1') + + // The checks menu lists what needs attention and the rest on request; the external status names no rerun. + await checks.click() + const menu = page.getByRole('menu') + await expect.poll(() => menu.locator('[data-forge-check-group]').evaluateAll(nodes => nodes.map(node => node.getAttribute('data-forge-check-group')))) + .toEqual(['failed', 'running']) + await menu.getByRole('menuitem', { name: '显示其余 3 项(通过、跳过)', exact: true }).waitFor() + await menu.getByRole('menuitem', { name: '重跑失败项', exact: true }).click() + await page.getByText('已请求重跑 #7 的检查', { exact: true }).waitFor() + expect(await rerunsOf(root)).toEqual(['repos/octo/demo/actions/runs/41/rerun-failed-jobs']) + + // The review row shows the first avatars; its menu lists every reviewer and the requests. + const review = card.locator('[data-forge-review]') + await review.click() + await expect.poll(() => menu.locator('[data-forge-reviewer]').evaluateAll(nodes => nodes.map(node => node.getAttribute('data-forge-reviewer')))) + .toEqual(['lin-reviewer', 'octo/forge', 'review-bot', 'zhou-dev', 'qian-dev']) + await menu.getByRole('menuitem', { name: '请求其他人评审…', exact: true }).click() + await menu.getByRole('menuitem', { name: /lin-reviewer/ }).waitFor() + await page.keyboard.type('mon') + await menu.getByRole('menuitem', { name: /^mona/ }).click() + await page.getByText('已请求 mona 评审 #7', { exact: true }).waitFor() + await review.click() + await menu.getByRole('menuitem', { name: '重新请求 zhou-dev 评审', exact: true }).click() + await expect.poll(async () => (await mutationsOf(root)).filter(entry => entry.field === 'requestReviews').map(entry => entry.variables.input)) + .toEqual([ + { pullRequestId: 'pull-7', union: true, userIds: ['user-mona'] }, + { pullRequestId: 'pull-7', union: true, userIds: ['user-zhou-dev'] }, + ]) + + // The linked issues take one row, each a link named by its number with its title in the name. + const issues = card.locator('[data-forge-closing-issues]') + expect(await issues.textContent()).toBe('关联 issue #6、octo/tracker#12') + await issues.getByRole('link', { name: '打开 issue #6:Show review progress in the panel', exact: true }).waitFor() + await issues.getByRole('link', { name: '打开 issue octo/tracker#12:Rerun failed checks from DSH', exact: true }).waitFor() + + const update = card.locator('[data-forge-update-branch]') + await expect.poll(() => update.textContent()).toBe('合并无冲突 · 落后于 main更新分支') + await update.click() + await page.getByRole('menuitem', { name: /^变基更新/ }).click() + await page.getByRole('menuitem', { name: '确认更新', exact: true }).click() + await page.getByText('已开始更新 #7 的分支', { exact: true }).waitFor() + expect((await mutationsOf(root)).at(-1)?.variables.input).toEqual({ pullRequestId: 'pull-7', expectedHeadOid: HEAD7, updateMethod: 'REBASE' }) + await expect.poll(() => update.count(), { timeout: 20_000 }).toBe(0) + + 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 { + 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([]) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6df8c554ae..5219919880 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1163,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. */ @@ -1193,7 +1193,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:366`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1236,6 +1236,8 @@ export interface Config { maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number + /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ + maxViewedFiles?: number } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 74d09245aa..c92923e759 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1165,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. */ @@ -1195,7 +1195,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:366`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1238,6 +1238,8 @@ export interface Config { maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number + /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ + maxViewedFiles?: number } ``` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 8de7ac5d42..6890522876 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -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:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../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` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 3673c996df..f981023fe9 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -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:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../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` | diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 194c6c26dd..9702f4429c 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -12,14 +12,17 @@ en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 /forges/change-request-actions: - en: 87d2c81d9514267f - zh: 1daf31c5b0127a1c + en: ae735fbdbdf2d870 + zh: 9903fcc571104ad8 /forges/review-threads: - en: 351af1e634f70a40 - zh: 2f0bba65d3b01277 + en: af729af6e59e915f + zh: 1b7d7671ec36a5b2 +/forges/overview-and-viewed-marks: + en: fd5928603c9375b1 + zh: 1a3bca55344ff385 /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: e3081af82f42354b - zh: 507eb461be8b81cf + en: 0e0348e9a38215ed + zh: affcc0231e15d682 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index b260ac321f..a84fb124a9 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -53,6 +53,12 @@ interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * 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 /** 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. */ @@ -95,6 +101,38 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are + * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a + * `stale` failure. A provider implements `viewedFiles` and `setViewed` together; omitting either declares that the + * host keeps no viewed marks. + */ + viewedFiles?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Set or clear the signed-in user's viewed mark on one file while the head is still `request.headSha`, resolving to + * undefined once the host saved it. + */ + setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** + * Rerun the failed checks of the head commit that name a `rerun` none of whose checks is pending, while the head is + * still `request.headSha`, resolving to undefined once the host accepted every rerun. Omission declares that the + * provider reruns no checks, and its snapshots then name none. + */ + rerunChecks?(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + /** + * Request reviews from more reviewers, resolving to undefined once the host accepted the request. A provider implements + * `requestReviews` and `reviewerCandidates` together; omitting either declares that it requests no reviews, and its + * snapshots then deny `canRequestReviews`. + */ + requestReviews?(ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal): Promise + /** List accounts whose login or name matches `query`, the host's suggestions first, for a review request. */ + reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise + /** + * Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to + * undefined once the host accepted the update. Omission declares that the provider updates no branches, and its + * snapshots then offer no `branchUpdates`. + */ + updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise } ``` @@ -167,6 +205,11 @@ interface ChangeRequestCheck { readonly startedAt: string | null /** ISO 8601 time the check completed, or null while it runs and when the host reports none. */ readonly completedAt: string | null + /** + * Identity a rerun of this check names, or null when the provider cannot rerun it, as for a commit status. Checks that + * name one identity rerun together, and their failed checks can be rerun once none of them is pending. + */ + readonly rerun: ForgeCheckId | null } ``` @@ -224,18 +267,36 @@ interface ChangeRequestSnapshot { readonly mergeReady: boolean /** Merge methods the repository accepts, the signed-in user's usual one first. */ readonly mergeMethods: readonly MergeMethod[] + /** + * Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is + * up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot, + * so a head behind its base cannot be told apart from a current one for a user without the right to update it. + */ + readonly branchUpdates: readonly BranchUpdateMethod[] /** Aggregate review outcome. */ readonly reviewDecision: ReviewDecision + /** Reviewers whose review is requested, in host order, then other accounts that reviewed, each once; the author is never listed. */ + readonly reviewers: readonly ChangeRequestReviewer[] + /** Whether the host reported more review requests or reviews than the provider read, so `reviewers` may be incomplete. */ + readonly reviewersTruncated: boolean + /** Whether the signed-in user may request reviews of the change request through its provider. */ + readonly canRequestReviews: boolean /** Checks on the head commit in host order. */ readonly checks: readonly ChangeRequestCheck[] /** Combined check outcome. */ readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean + /** Whether the signed-in user may rerun the failed checks that name a `rerun`. */ + readonly canRerunChecks: boolean /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ readonly threadsTruncated: boolean + /** Issues linked to the change request, which the host closes once it merges, in host order. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -297,19 +358,21 @@ interface MergeRequest { ``` ```ts type-equiv -/** Why a provider could not change a change request. */ +/** Why a provider could not change a change request, or could not confirm that it did. */ interface ForgeActionFailure { /** * `unauthenticated`: credentials are missing or rejected; `stale`: the head - * moved past the confirmed commit; `failed`: the host refused or could not be reached. + * moved past the confirmed commit; `failed`: the host refused or could not be reached, so nothing changed; + * `unknown`: the request reached the host but its answer did not confirm the outcome, so the change may have been + * applied and must be checked on the host before it is tried again. */ - readonly code: 'unauthenticated' | 'stale' | 'failed' + readonly code: 'unauthenticated' | 'stale' | 'failed' | 'unknown' /** Human-readable cause, usually the host's own message. */ readonly message: string } ``` -`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. */ @@ -329,12 +392,12 @@ 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 } @@ -396,6 +459,10 @@ interface ForgeReviewComment { 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 } ``` @@ -422,6 +489,13 @@ interface ForgeReviewThread { 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[] } @@ -432,10 +506,200 @@ interface ForgeReviewThread { 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 } +``` + +## Overview and viewed marks + +A snapshot also carries the overview of a change request: its `reviewers` with each one's latest verdict, the `closingIssues` the host closes once it merges, the `branchUpdates` that would bring a head behind its base up to date, whether the signed-in user may request reviews or rerun checks, and the `rerun` each check names. `ctx.forge.rerunChecks`, `ctx.forge.requestReviews`, and `ctx.forge.updateBranch` act on it and resolve to a `ForgeActionFailure` as the actions above do, `unknown` when the host's answer did not confirm the outcome, polling a watched change request once the provider answered; a rerun and an update name the head commit the user saw and are refused with `stale` once the head moved. A provider implements `requestReviews` together with `reviewerCandidates`, which `ctx.forge.reviewerCandidates` uses to list the accounts a review can be requested from; an action the provider lacks fails with `failed`, and `reviewerCandidates` returns `unsupported`. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub fills and acts on each field. + +```ts type-equiv +/** Opaque host identity of a status check that a rerun names. */ +type ForgeCheckId = Branded<'ForgeCheckId'> +``` + +```ts type-equiv +/** How an update brings the base branch's new commits into the head branch: a merge commit, or a rebase of the head's commits. */ +type BranchUpdateMethod = 'merge' | 'rebase' +``` + +```ts type-equiv +/** Outcome of a reviewer's latest submitted review. */ +type ReviewVerdict = 'approved' | 'changes-requested' | 'commented' | 'dismissed' +``` + +```ts type-equiv +/** An account or team asked to review a change request, or an account that reviewed it. */ +interface ChangeRequestReviewer { + /** Whether the reviewer is a person's account, an app or bot account, or a team. */ + readonly kind: 'user' | 'bot' | 'team' + /** Login, or `organization/slug` for a team. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether a review from the reviewer is requested now. */ + readonly requested: boolean + /** Whether the host requested the review because the reviewer owns changed paths. */ + readonly codeOwner: boolean + /** Outcome of the reviewer's latest submitted review, or null before the first. */ + readonly verdict: ReviewVerdict | null + /** Commit the latest submitted review was on, or null before the first or when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** One issue linked to a change request, which the host closes once the change request merges. */ +interface ChangeRequestIssue { + /** Repository that holds the issue. */ + readonly repository: ForgeRepository + /** Host-assigned issue number. */ + readonly number: number + /** Title as the author wrote it. */ + readonly title: string + /** Whether the issue is still open. */ + readonly state: 'open' | 'closed' + /** Web page of the issue. */ + readonly url: string +} +``` + +```ts type-equiv +/** A rerun of the failed checks of the head commit whose checks the user saw. */ +interface ForgeRerunRequest { + /** Head commit whose checks the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string +} +``` + +```ts type-equiv +/** Reviewers to ask in addition to those whose review is requested now; one who already reviewed is asked again. */ +interface ForgeReviewersRequest { + /** The reviewers by kind and login, a team by `organization/slug`. */ + readonly reviewers: readonly Pick[] +} +``` + +```ts type-equiv +/** An account a review of the change request can be requested from. */ +interface ForgeReviewerCandidate { + /** Login as the host spells it. */ + readonly login: string + /** Display name, or null when the account shows none. */ + readonly name: string | null + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the host suggests the account for this change request, as from the history of its changed files. */ + readonly suggested: boolean +} +``` + +```ts type-equiv +/** A branch update the user confirmed for the head commit they saw. */ +interface BranchUpdateRequest { + /** How the base branch's new commits enter the head branch. */ + readonly method: BranchUpdateMethod + /** Commit object name the head must still have; the update is refused once the head moves. */ + readonly headSha: string +} +``` + +`ctx.forge.viewedFiles` and `ctx.forge.setViewed` read and change the signed-in user's viewed marks on the files of a change request at one head commit. A provider keeps viewed marks only when it implements both methods; otherwise `viewedFiles` returns undefined and `setViewed` fails, so a consumer keeps marks itself. A `stale` answer polls a watched change request as a stale diff read does. + +```ts type-equiv +/** + * The signed-in user's review progress on one changed file: `viewed`, `unviewed`, or `dismissed` once the file + * changed after the user marked it viewed. + */ +type ForgeViewedState = 'viewed' | 'unviewed' | 'dismissed' +``` + +```ts type-equiv +/** The signed-in user's viewed marks on the files of a change request, read at one head commit. */ +interface ForgeViewedFiles { + /** Head commit the marks were read at. */ + readonly headSha: string + /** State of each changed file the host listed, by repository-relative path. */ + readonly files: Readonly> + /** Whether the change request has more files than `files` lists. */ + readonly truncated: boolean +} +``` + +```ts type-equiv +/** A viewed mark the user set or cleared on a file of the head commit they saw. */ +interface ForgeViewedRequest { + /** Repository-relative path of the changed file. */ + readonly path: string + /** Whether the file is viewed. */ + readonly viewed: boolean + /** Head commit whose changes the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string } ``` @@ -730,6 +994,10 @@ The changes view reads through the same Remote. `localDiff` reads one `ForgeLoca `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. +`changeRequestViewed(session, url, headSha)` reads the viewed marks of a bound change request at the head of the diff the view shows, returns null when the provider keeps none, and refuses another head with `forgePanel/stale-head` and any other failure with `forgePanel/viewed-failed`; `setFileViewed` saves one file's mark at that head. `rerunChecks`, `requestReviews`, and `updateBranch` act on a bound change request and refuse an outcome the host did not confirm with `forgePanel/action-unknown`, and `reviewerCandidates` lists accounts for a review request, refusing with `forgePanel/reviewers-failed` when the host lists none. The changes view reads the marks of a whole change request beside its diff and keeps the marks of local changes and chosen commits in the browser; the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes both and the card rows that offer the actions. + +`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 @@ -1006,6 +1274,49 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request's head commit while the head is still `request.headSha`, then poll it + * at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the head commit whose checks the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the rerun, or why it did not; a provider that reruns no checks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request from more reviewers, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the reviewers to ask. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the request, or why it did not; a provider that requests no reviews fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async requestReviews( ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request can be requested from. + * @param ref - change request served by a registered provider. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - cancellation of the read. + * @returns the accounts, the host's suggestions first, or why the host did not list them; a provider that requests no + * reviews returns `unsupported`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSignal, ): Promise + +/** + * Bring the base branch's new commits into a change request's head branch while its head is still + * `request.headSha`, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - update method and the head commit the user confirmed. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the update, or why it did not; a provider that updates no branches fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise + /** * Read complete check details independently of periodic polling. * @param ref - change request served by a registered provider. @@ -1041,6 +1352,42 @@ async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise */ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise +/** + * 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 + +/** + * Read the signed-in user's viewed marks on the files 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 marks must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the marks read at `headSha`, why the host did not provide them, or undefined when the provider keeps no + * viewed marks. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param request - the file, its mark, and the head commit the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1311,11 +1658,39 @@ 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 +/** + * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the + * whole change request. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the shown diff; marks read at another head are refused. + * @param signal - request cancellation. + * @returns the marks at `headSha`, or null when the provider keeps no viewed marks. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed` + * when the host does not provide the marks otherwise. + */ +@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request of a Session. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or keeps no viewed marks; `forgePanel/action-unknown` when the host + * did not confirm whether it saved the mark. + */ +@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * 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 or `maxCachedReviewBytes` evicts them; a read again after that age, or a `fresh` read, - * shows threads resolved since, which do not change a GitHub pull request's update time. + * `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. @@ -1331,7 +1706,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise /** - * Publish a line comment or completed review for a visible Session binding. + * 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. @@ -1340,6 +1716,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 +/** + * 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 + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. @@ -1365,6 +1756,60 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user + * saw; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or reruns no checks; `forgePanel/action-unknown` when the host did + * not confirm whether it started the rerun. + */ +@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request of a Session from more reviewers; the change request is polled again once the + * host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/action-failed` with the host's reason when the host refuses, cannot be reached, or requests no reviews; + * `forgePanel/action-unknown` when the host did not confirm whether it requested the reviews. + */ +@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request of a Session can be requested from. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/reviewers-failed` when the host does not list them. + */ +@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request of a Session while its head is still + * `headSha`; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param method - merge commit or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's reason when + * the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not + * confirm whether it started the update. + */ +@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index c0b5f11fe0..6ef0264108 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -53,6 +53,12 @@ interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * 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 /** 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. */ @@ -95,6 +101,38 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are + * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a + * `stale` failure. A provider implements `viewedFiles` and `setViewed` together; omitting either declares that the + * host keeps no viewed marks. + */ + viewedFiles?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Set or clear the signed-in user's viewed mark on one file while the head is still `request.headSha`, resolving to + * undefined once the host saved it. + */ + setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** + * Rerun the failed checks of the head commit that name a `rerun` none of whose checks is pending, while the head is + * still `request.headSha`, resolving to undefined once the host accepted every rerun. Omission declares that the + * provider reruns no checks, and its snapshots then name none. + */ + rerunChecks?(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + /** + * Request reviews from more reviewers, resolving to undefined once the host accepted the request. A provider implements + * `requestReviews` and `reviewerCandidates` together; omitting either declares that it requests no reviews, and its + * snapshots then deny `canRequestReviews`. + */ + requestReviews?(ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal): Promise + /** List accounts whose login or name matches `query`, the host's suggestions first, for a review request. */ + reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise + /** + * Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to + * undefined once the host accepted the update. Omission declares that the provider updates no branches, and its + * snapshots then offer no `branchUpdates`. + */ + updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise } ``` @@ -167,6 +205,11 @@ interface ChangeRequestCheck { readonly startedAt: string | null /** ISO 8601 time the check completed, or null while it runs and when the host reports none. */ readonly completedAt: string | null + /** + * Identity a rerun of this check names, or null when the provider cannot rerun it, as for a commit status. Checks that + * name one identity rerun together, and their failed checks can be rerun once none of them is pending. + */ + readonly rerun: ForgeCheckId | null } ``` @@ -224,18 +267,36 @@ interface ChangeRequestSnapshot { readonly mergeReady: boolean /** Merge methods the repository accepts, the signed-in user's usual one first. */ readonly mergeMethods: readonly MergeMethod[] + /** + * Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is + * up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot, + * so a head behind its base cannot be told apart from a current one for a user without the right to update it. + */ + readonly branchUpdates: readonly BranchUpdateMethod[] /** Aggregate review outcome. */ readonly reviewDecision: ReviewDecision + /** Reviewers whose review is requested, in host order, then other accounts that reviewed, each once; the author is never listed. */ + readonly reviewers: readonly ChangeRequestReviewer[] + /** Whether the host reported more review requests or reviews than the provider read, so `reviewers` may be incomplete. */ + readonly reviewersTruncated: boolean + /** Whether the signed-in user may request reviews of the change request through its provider. */ + readonly canRequestReviews: boolean /** Checks on the head commit in host order. */ readonly checks: readonly ChangeRequestCheck[] /** Combined check outcome. */ readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean + /** Whether the signed-in user may rerun the failed checks that name a `rerun`. */ + readonly canRerunChecks: boolean /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ readonly threadsTruncated: boolean + /** Issues linked to the change request, which the host closes once it merges, in host order. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -297,19 +358,21 @@ interface MergeRequest { ``` ```ts type-equiv -/** Why a provider could not change a change request. */ +/** Why a provider could not change a change request, or could not confirm that it did. */ interface ForgeActionFailure { /** * `unauthenticated`: credentials are missing or rejected; `stale`: the head - * moved past the confirmed commit; `failed`: the host refused or could not be reached. + * moved past the confirmed commit; `failed`: the host refused or could not be reached, so nothing changed; + * `unknown`: the request reached the host but its answer did not confirm the outcome, so the change may have been + * applied and must be checked on the host before it is tried again. */ - readonly code: 'unauthenticated' | 'stale' | 'failed' + readonly code: 'unauthenticated' | 'stale' | 'failed' | 'unknown' /** Human-readable cause, usually the host's own message. */ readonly message: string } ``` -`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. */ @@ -329,12 +392,12 @@ 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 } @@ -396,6 +459,10 @@ interface ForgeReviewComment { 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 } ``` @@ -422,6 +489,13 @@ interface ForgeReviewThread { 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[] } @@ -432,10 +506,202 @@ interface ForgeReviewThread { 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 } +``` + + + +## 概览与已审阅标记 + +快照还携带变更请求的概览:`reviewers` 及每位评审者最近的结论、合并后托管平台会关闭的 `closingIssues`、能让落后于基线的 head 更新到最新的 `branchUpdates`、当前登录用户能否请求评审或重跑检查,以及每个检查指出的 `rerun`。`ctx.forge.rerunChecks`、`ctx.forge.requestReviews` 与 `ctx.forge.updateBranch` 据此操作,并像上文的操作一样返回 `ForgeActionFailure`,主机的答复无法确认结果时为 `unknown`,提供方答复后立即轮询被监听的变更请求;重跑与更新指明用户看到的 head 提交,head 移动后以 `stale` 拒绝。提供方同时实现 `requestReviews` 与 `reviewerCandidates`,`ctx.forge.reviewerCandidates` 借后者列出可以请求评审的账号;提供方缺少的操作以 `failed` 失败,`reviewerCandidates` 则返回 `unsupported`。GitHub 如何填写各字段并执行这些操作见 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package)。 + +```ts type-equiv +/** Opaque host identity of a status check that a rerun names. */ +type ForgeCheckId = Branded<'ForgeCheckId'> +``` + +```ts type-equiv +/** How an update brings the base branch's new commits into the head branch: a merge commit, or a rebase of the head's commits. */ +type BranchUpdateMethod = 'merge' | 'rebase' +``` + +```ts type-equiv +/** Outcome of a reviewer's latest submitted review. */ +type ReviewVerdict = 'approved' | 'changes-requested' | 'commented' | 'dismissed' +``` + +```ts type-equiv +/** An account or team asked to review a change request, or an account that reviewed it. */ +interface ChangeRequestReviewer { + /** Whether the reviewer is a person's account, an app or bot account, or a team. */ + readonly kind: 'user' | 'bot' | 'team' + /** Login, or `organization/slug` for a team. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether a review from the reviewer is requested now. */ + readonly requested: boolean + /** Whether the host requested the review because the reviewer owns changed paths. */ + readonly codeOwner: boolean + /** Outcome of the reviewer's latest submitted review, or null before the first. */ + readonly verdict: ReviewVerdict | null + /** Commit the latest submitted review was on, or null before the first or when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** One issue linked to a change request, which the host closes once the change request merges. */ +interface ChangeRequestIssue { + /** Repository that holds the issue. */ + readonly repository: ForgeRepository + /** Host-assigned issue number. */ + readonly number: number + /** Title as the author wrote it. */ + readonly title: string + /** Whether the issue is still open. */ + readonly state: 'open' | 'closed' + /** Web page of the issue. */ + readonly url: string +} +``` + +```ts type-equiv +/** A rerun of the failed checks of the head commit whose checks the user saw. */ +interface ForgeRerunRequest { + /** Head commit whose checks the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string +} +``` + +```ts type-equiv +/** Reviewers to ask in addition to those whose review is requested now; one who already reviewed is asked again. */ +interface ForgeReviewersRequest { + /** The reviewers by kind and login, a team by `organization/slug`. */ + readonly reviewers: readonly Pick[] +} +``` + +```ts type-equiv +/** An account a review of the change request can be requested from. */ +interface ForgeReviewerCandidate { + /** Login as the host spells it. */ + readonly login: string + /** Display name, or null when the account shows none. */ + readonly name: string | null + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the host suggests the account for this change request, as from the history of its changed files. */ + readonly suggested: boolean +} +``` + +```ts type-equiv +/** A branch update the user confirmed for the head commit they saw. */ +interface BranchUpdateRequest { + /** How the base branch's new commits enter the head branch. */ + readonly method: BranchUpdateMethod + /** Commit object name the head must still have; the update is refused once the head moves. */ + readonly headSha: string +} +``` + +`ctx.forge.viewedFiles` 与 `ctx.forge.setViewed` 在一个 head 提交上读取和修改当前登录用户对变更请求各文件的已审阅标记。只有同时实现两个方法的提供方保存已审阅标记;否则 `viewedFiles` 返回 undefined,`setViewed` 失败,由使用方自行保存标记。`stale` 答复会像过期的 diff 读取一样立即轮询被监听的变更请求。 + +```ts type-equiv +/** + * The signed-in user's review progress on one changed file: `viewed`, `unviewed`, or `dismissed` once the file + * changed after the user marked it viewed. + */ +type ForgeViewedState = 'viewed' | 'unviewed' | 'dismissed' +``` + +```ts type-equiv +/** The signed-in user's viewed marks on the files of a change request, read at one head commit. */ +interface ForgeViewedFiles { + /** Head commit the marks were read at. */ + readonly headSha: string + /** State of each changed file the host listed, by repository-relative path. */ + readonly files: Readonly> + /** Whether the change request has more files than `files` lists. */ + readonly truncated: boolean +} +``` + +```ts type-equiv +/** A viewed mark the user set or cleared on a file of the head commit they saw. */ +interface ForgeViewedRequest { + /** Repository-relative path of the changed file. */ + readonly path: string + /** Whether the file is viewed. */ + readonly viewed: boolean + /** Head commit whose changes the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string } ``` @@ -730,6 +996,10 @@ type ForgeChangeRequestStatesFrame = `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) 所述把讨论叠加到文件上。 +`changeRequestViewed(session, url, headSha)` 在视图所示 diff 的 head 上读取已绑定变更请求的已审阅标记,提供方不保存标记时返回 null,head 不同时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝;`setFileViewed` 在该 head 上保存一个文件的标记。`rerunChecks`、`requestReviews` 与 `updateBranch` 作用于已绑定的变更请求,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝,`reviewerCandidates` 列出可请求评审的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随 diff 一起读取整个变更请求的标记,本地变更与所选提交的标记保存在浏览器中;两者以及提供这些操作的卡片行见[面板 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 @@ -1006,6 +1276,49 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request's head commit while the head is still `request.headSha`, then poll it + * at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the head commit whose checks the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the rerun, or why it did not; a provider that reruns no checks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request from more reviewers, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the reviewers to ask. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the request, or why it did not; a provider that requests no reviews fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async requestReviews( ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request can be requested from. + * @param ref - change request served by a registered provider. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - cancellation of the read. + * @returns the accounts, the host's suggestions first, or why the host did not list them; a provider that requests no + * reviews returns `unsupported`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSignal, ): Promise + +/** + * Bring the base branch's new commits into a change request's head branch while its head is still + * `request.headSha`, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - update method and the head commit the user confirmed. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the update, or why it did not; a provider that updates no branches fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise + /** * Read complete check details independently of periodic polling. * @param ref - change request served by a registered provider. @@ -1041,6 +1354,42 @@ async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise */ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise +/** + * 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 + +/** + * Read the signed-in user's viewed marks on the files 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 marks must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the marks read at `headSha`, why the host did not provide them, or undefined when the provider keeps no + * viewed marks. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param request - the file, its mark, and the head commit the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1311,11 +1660,39 @@ 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 +/** + * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the + * whole change request. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the shown diff; marks read at another head are refused. + * @param signal - request cancellation. + * @returns the marks at `headSha`, or null when the provider keeps no viewed marks. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed` + * when the host does not provide the marks otherwise. + */ +@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request of a Session. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or keeps no viewed marks; `forgePanel/action-unknown` when the host + * did not confirm whether it saved the mark. + */ +@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * 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 or `maxCachedReviewBytes` evicts them; a read again after that age, or a `fresh` read, - * shows threads resolved since, which do not change a GitHub pull request's update time. + * `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. @@ -1331,7 +1708,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise /** - * Publish a line comment or completed review for a visible Session binding. + * 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. @@ -1340,6 +1718,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 +/** + * 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 + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. @@ -1365,6 +1758,60 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user + * saw; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or reruns no checks; `forgePanel/action-unknown` when the host did + * not confirm whether it started the rerun. + */ +@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request of a Session from more reviewers; the change request is polled again once the + * host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/action-failed` with the host's reason when the host refuses, cannot be reached, or requests no reviews; + * `forgePanel/action-unknown` when the host did not confirm whether it requested the reviews. + */ +@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request of a Session can be requested from. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/reviewers-failed` when the host does not list them. + */ +@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request of a Session while its head is still + * `headSha`; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param method - merge commit or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's reason when + * the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not + * confirm whether it started the update. + */ +@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml new file mode 100644 index 0000000000..aa355c3d62 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-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 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md new file mode 100644 index 0000000000..8eab347bb2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md new file mode 100644 index 0000000000..e6f392c7aa --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md @@ -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()` 的调用处显式传入这两个参数。一次调用的覆盖值不会影响后续读取。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index a017e7f82b..acdb30680e 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: a63e88dce467d6ee - zh: fc25bb283ca0eaff + en: 071b67613c512b84 + zh: 7ee32d8dbcf7a0f2 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 2675699a71..12d949e8b5 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -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. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index b4551f624b..c74b879337 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -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()` 返回的运行中应用记录。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml new file mode 100644 index 0000000000..932fdd9720 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md +/: + en: 5788ee9fab8253cf + zh: c8f8da46139d3aec +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes: + en: a3a5753044d1188b + zh: 16562b29b23a3fea +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes/change: + en: a571055593a2aa44 + zh: 405b322b9863f841 +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes/migration: + en: 92213118a4373782 + zh: d41450b2776c59ea diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md new file mode 100644 index 0000000000..3725460565 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot gains required overview fields, ChangeRequestCheck gains the required rerun field, and ForgeActionFailure gains the unknown code." +--- + +# Forge snapshots carry the change request overview, and actions report unknown outcomes + +English | [中文](guide.zh.md) + +## Change + +`ChangeRequestSnapshot` gains seven required fields: `reviewers` and `reviewersTruncated`, `closingIssues` and `closingIssuesTruncated`, `branchUpdates`, `canRequestReviews`, and `canRerunChecks`. `ChangeRequestCheck` gains the required `rerun: ForgeCheckId | null`, which names how the provider reruns the check. The change request card reads these fields to list reviewers, linked issues, and the branch update, and to offer rerunning failed checks, requesting reviews, and updating the branch. + +`ForgeActionFailure['code']` gains `unknown`: the host's answer did not confirm the outcome, so the change may have been applied. The GitHub provider returns it for viewed marks, review requests, and branch updates GitHub did not confirm; `ctx.forge.markReady` and `ctx.forge.merge` return it only from a provider that does. + +`ForgeProvider` also gains optional `viewedFiles` with `setViewed`, `rerunChecks`, `requestReviews` with `reviewerCandidates`, and `updateBranch`; a provider without them keeps working, and the card then offers none of those actions. + +This affects third-party `ForgeProvider` implementations registered with `ctx.forge.register` and other code that builds `ChangeRequestSnapshot` or `ChangeRequestCheck` values. All types come from `@deepseek-ai/dsh-experimental-forge`. + +## Migration + +1. In every `ChangeRequestCheck` a provider builds, set `rerun: null` unless the provider implements `rerunChecks`; a provider that does names each rerunnable check with a branded `ForgeCheckId` it can resolve again, as [`actionsRun`](../../../../packages/experimental/forge-github/src/graphql.ts) does for GitHub Actions runs. +2. In every `ChangeRequestSnapshot`, set the overview fields the host reports. Without host data, use `reviewers: []`, `reviewersTruncated: false`, `closingIssues: []`, `closingIssuesTruncated: false`, `branchUpdates: []`, `canRequestReviews: false`, and `canRerunChecks: false`; the card then shows the review decision alone and offers no overview action. +3. Optionally implement the new provider methods; [`GitHubProvider`](../../../../packages/experimental/forge-github/src/provider.ts) shows each one, and the [forge subsystem page](../../../subsystems/forge.md#overview-and-viewed-marks) states their contract. +4. Handle `unknown` wherever code switches exhaustively over `ForgeActionFailure['code']`: show that the outcome must be checked on the host, and do not try the change again before it is. +5. Run your type check; it succeeds when every snapshot and check a provider builds sets the new fields and no `ForgeActionFailure` code is unhandled. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md new file mode 100644 index 0000000000..6c7ac4933f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestCheck 新增必填的 rerun 字段,ForgeActionFailure 新增 unknown 代码。" +--- + +# Forge 快照携带变更请求概览,操作报告结果不明 + +[English](guide.md) | 中文 + +## 变更 + +`ChangeRequestSnapshot` 新增七个必填字段:`reviewers` 与 `reviewersTruncated`、`closingIssues` 与 `closingIssuesTruncated`、`branchUpdates`、`canRequestReviews`,以及 `canRerunChecks`。`ChangeRequestCheck` 新增必填的 `rerun: ForgeCheckId | null`,指出提供方如何重跑该检查。变更请求卡片读取这些字段,列出评审者、关联 issue 与分支更新,并提供重跑失败检查、请求评审与更新分支。 + +`ForgeActionFailure['code']` 新增 `unknown`:主机的答复无法确认结果,改动可能已经生效。GitHub 提供方在 GitHub 未确认已审阅标记、评审请求与分支更新的结果时返回它;`ctx.forge.markReady` 与 `ctx.forge.merge` 只在提供方返回它时才会返回。 + +`ForgeProvider` 还新增可选的 `viewedFiles` 与 `setViewed`、`rerunChecks`、`requestReviews` 与 `reviewerCandidates`,以及 `updateBranch`;未实现它们的提供方照常工作,卡片不提供对应操作。 + +受影响的是通过 `ctx.forge.register` 注册的第三方 `ForgeProvider` 实现,以及其他构造 `ChangeRequestSnapshot` 或 `ChangeRequestCheck` 值的代码。所有类型都来自 `@deepseek-ai/dsh-experimental-forge`。 + +## 迁移 + +1. 在提供方构造的每个 `ChangeRequestCheck` 中设置 `rerun: null`,除非提供方实现了 `rerunChecks`;实现了的提供方为每个可重跑的检查给出能再次解析的品牌化 `ForgeCheckId`,GitHub Actions 运行的做法见 [`actionsRun`](../../../../packages/experimental/forge-github/src/graphql.ts)。 +2. 在每个 `ChangeRequestSnapshot` 中设置托管平台报告的概览字段。没有平台数据时,使用 `reviewers: []`、`reviewersTruncated: false`、`closingIssues: []`、`closingIssuesTruncated: false`、`branchUpdates: []`、`canRequestReviews: false` 与 `canRerunChecks: false`;卡片随后只显示评审结论,不提供概览操作。 +3. 可选地实现新的提供方方法;[`GitHubProvider`](../../../../packages/experimental/forge-github/src/provider.ts) 展示了每个方法,契约见 [forge 子系统页面](../../../subsystems/forge.zh.md#overview-and-viewed-marks)。 +4. 在所有对 `ForgeActionFailure['code']` 做穷举的地方处理 `unknown`:提示需要到主机上核对结果,核对之前不要再次尝试该改动。 +5. 运行类型检查;提供方构造的每个快照与检查都设置了新字段、且没有未处理的 `ForgeActionFailure` 代码时即通过。 diff --git a/packages/boot/plugin-manager/tests/github-connection.spec.ts b/packages/boot/plugin-manager/tests/github-connection.spec.ts index 1d76e1eaf1..d1d292fc2c 100644 --- a/packages/boot/plugin-manager/tests/github-connection.spec.ts +++ b/packages/boot/plugin-manager/tests/github-connection.spec.ts @@ -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>) + 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>) diff --git a/packages/client/ui-primitives/src/FileTypeIcon.tsx b/packages/client/ui-primitives/src/FileTypeIcon.tsx index 1fbcee6750..fc2e3c2667 100644 --- a/packages/client/ui-primitives/src/FileTypeIcon.tsx +++ b/packages/client/ui-primitives/src/FileTypeIcon.tsx @@ -44,7 +44,9 @@ export type FileTypeIconProps = IconProps & ( } ) -const EXTENSION_TYPES: Readonly> = { +// Maps, not objects: a basename or extension equal to an `Object.prototype` key +// (`constructor`, `__proto__`) must miss instead of resolving the inherited member. +const EXTENSION_TYPES: ReadonlyMap = new Map(Object.entries({ scss: 'code', sass: 'code', less: 'code', @@ -101,13 +103,13 @@ const EXTENSION_TYPES: Readonly> = { ots: 'excel', fods: 'excel', numbers: 'excel', -} +})) -const NAME_TYPES: Readonly> = { +const NAME_TYPES: ReadonlyMap = new Map(Object.entries({ changelog: 'markdown', contributing: 'markdown', readme: 'markdown', -} +})) function basename(path: string): string { return path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) @@ -140,8 +142,8 @@ export function classifyFileType( const name = basename(path).toLowerCase() const extension = fileExtension(name).toLowerCase() return classifyCodeFileType(name, extension, context) - ?? NAME_TYPES[name] - ?? EXTENSION_TYPES[extension] + ?? NAME_TYPES.get(name) + ?? EXTENSION_TYPES.get(extension) ?? 'other' } diff --git a/packages/client/ui-primitives/src/code-file-types.ts b/packages/client/ui-primitives/src/code-file-types.ts index 9b5ce75459..5bb1a5a628 100644 --- a/packages/client/ui-primitives/src/code-file-types.ts +++ b/packages/client/ui-primitives/src/code-file-types.ts @@ -61,7 +61,9 @@ export interface FileTypeProjectContext { const CODE_FILE_TYPE_SET = new Set(CODE_FILE_TYPES) -const FILE_NAME_TYPES: Readonly> = { +// Maps, not objects: a basename or extension equal to an `Object.prototype` key +// (`constructor`, `__proto__`) must miss instead of resolving the inherited member. +const FILE_NAME_TYPES: ReadonlyMap = new Map(Object.entries({ '.bash_profile': 'shell', '.bashrc': 'shell', '.env': 'env', @@ -90,7 +92,7 @@ const FILE_NAME_TYPES: Readonly> = { 'package.json': 'node', 'podfile': 'ruby', 'rakefile': 'ruby', -} +})) const FILE_NAME_PREFIX_TYPES: readonly (readonly [string, CodeFileType])[] = [ ['dockerfile.', 'docker'], @@ -109,7 +111,7 @@ const FILE_NAME_SUFFIX_TYPES: readonly (readonly [string, CodeFileType])[] = [ ['.dockerfile', 'docker'], ] -const EXTENSION_TYPES: Readonly> = { +const EXTENSION_TYPES: ReadonlyMap = new Map(Object.entries({ 'bash': 'shell', 'c': 'c', 'c++': 'cpp', @@ -217,7 +219,7 @@ const EXTENSION_TYPES: Readonly> = { 'yml': 'yaml', 'zig': 'zig', 'zsh': 'shell', -} +})) const LINK_CODE_EXTENSIONS = new Set([ 'ts', @@ -322,7 +324,7 @@ export function classifyCodeFileType( extension: string, context?: FileTypeProjectContext, ): CodeFileType | null { - const exact = FILE_NAME_TYPES[name] + const exact = FILE_NAME_TYPES.get(name) if (exact !== undefined) return exact for (const [prefix, type] of FILE_NAME_PREFIX_TYPES) { if (name.startsWith(prefix)) return type @@ -334,5 +336,5 @@ export function classifyCodeFileType( const pubspec = Object.entries(context.files).find(([path]) => basename(path).toLowerCase() === 'pubspec.yaml')?.[1] if (pubspec?.includes('flutter:') === true) return 'flutter' } - return EXTENSION_TYPES[extension] ?? null + return EXTENSION_TYPES.get(extension) ?? null } diff --git a/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx b/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx index b39b22f0f2..e9c8367d59 100644 --- a/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx +++ b/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { classifyFileType, fileExtension, FileTypeIcon, type FileTypeKind, } from '@deepseek-ai/dsh-client-ui-primitives' +import { classifyCodeFileType } from '../src/code-file-types.ts' import css from '../src/FileTypeIcon.module.css' afterEach(cleanup) @@ -58,6 +59,30 @@ describe('classifyFileType', () => { }) }) +describe('Object.prototype key names', () => { + const keys = ['constructor', '__proto__', 'toString', 'hasOwnProperty'] + + it.each(keys.flatMap(key => [ + [key, 'other'], + [`src/${key.toUpperCase()}`, 'other'], + [`archive.${key}`, 'other'], + [`${key}.md`, 'markdown'], + [`${key}.ts`, 'typescript'], + ] as [string, Exclude][]))('%s → %s', (path, type) => { + expect(classifyFileType(path)).toBe(type) + }) + + it.each(keys)('%s misses the code-file name and extension tables', (key) => { + expect(classifyCodeFileType(key, key)).toBeNull() + expect(classifyCodeFileType(key, 'ts')).toBe('typescript') + }) + + it.each(keys.flatMap(key => [key, `notes.${key}`]))('%s renders the generic file glyph', (path) => { + const { container } = render() + expect(container.querySelector('svg')!.classList.contains(css.other!)).toBe(true) + }) +}) + describe('FileTypeIcon', () => { const types: FileTypeKind[] = [ 'code', 'excel', 'folder', 'html', 'image', 'markdown', 'other', 'pdf', 'ppt', 'video', 'word', diff --git a/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts new file mode 100644 index 0000000000..e65cb1a16a --- /dev/null +++ b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts @@ -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`, + ]) +}) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.ts b/packages/client/ui-theme/tests/stylesheet-scan.ts index 91311945bf..ce796bc62c 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.ts @@ -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 } diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 4d76beeea8..b7e2d93083 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 6fc86067b4cf949e - zh: 04c9ba17de9839cc + en: c3fa707a638717e4 + zh: dfeba8a57c58a8aa /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: aadfb4c411863289 - zh: 0d077134d56126d0 + en: d977b08e15833905 + zh: 681306c58da73674 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: ec34e3517df7eb5e - zh: a4cd60e62c481027 + en: fcae07054935d3b9 + zh: ce316479012ebcef /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 21200e41b0..3df66099f2 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,12 +36,12 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button. - **Header button** — appears when the Session has bound change requests or its directory is inside a Git checkout, and shows or hides the tab. A red dot marks an open change request with failed checks, requested changes, or conflicts. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. -- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, 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. +- **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, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. 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 label shortened to a bare count beside its ring, 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 branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. -- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. -- **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 only Add to input, which quotes the whole thread, and View on GitHub. 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. +- **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, as a ring filled to the viewed share and a label such as 2 / 3 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. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other 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. 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. @@ -49,7 +49,7 @@ The diff follows the file tree’s depth-first order: directories before files, `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. ----- @@ -72,6 +72,8 @@ Each inspection also decides whether the worktree is missing: the Session's dire `localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old or the reader refreshes the view, since resolving a GitHub thread leaves the update time unchanged. +`changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it. + `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport 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. @@ -89,6 +91,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | +| [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | Checks, review, merge, and linked issue rows with their menus | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | @@ -102,6 +105,8 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`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/host-viewed.ts`](src/client/host-viewed.ts) | Viewed marks the code host keeps, with marks being saved | +| [`src/client/menu-search.ts`](src/client/menu-search.ts) | Keys of the search field at the top of a menu | | [`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 | @@ -147,8 +152,8 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws. - **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. -- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. -- **Review thread actions** — threads are read-only: replying, resolving, and editing comments, and drafts in GitHub's pending review, are deferred to the provider's review writes. Minimized comments show like others, and avatars load from the code host's image server in the browser. +- **Viewed files on the code host** — GitHub keeps one viewed mark per file and user, not one per commit, so marks in a view of chosen commits stay in this browser, and another browser or device starts without them. A file beyond the provider's `maxViewedFiles` shows no mark from GitHub until it is marked in this view. +- **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. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index da598fab35..91d1a4144c 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,12 +36,12 @@ kind: "package-reference" - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 +- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 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 中查看”两个操作。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.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 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 +- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -49,7 +49,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `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 并明确允许再次提交。 ----- @@ -72,6 +72,8 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后,或读者刷新视图时,重新读取,因为解决 GitHub 讨论不会改变更新时间。 +`changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。 + `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。 @@ -89,6 +91,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | +| [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | 检查、评审、合并与关联 issue 行及其菜单 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | @@ -102,6 +105,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`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/host-viewed.ts`](src/client/host-viewed.ts) | 代码托管平台保存的已审阅标记,以及正在保存的标记 | +| [`src/client/menu-search.ts`](src/client/menu-search.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 缺失卡片 | @@ -147,8 +152,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 -- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 -- **评审讨论的操作**——讨论是只读的:回复、解决、编辑评论,以及 GitHub 待提交评审中的草稿,留待提供方的评审写入能力实现。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 +- **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 +- **评审讨论的写入**——在一个变更视图中的写操作,会在该变更请求的其他已打开视图收到下一次状态时显示;解决讨论不会改变 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)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx index 9125fef677..0bcabc3408 100644 --- a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx @@ -10,6 +10,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts' import type { NS } from './locales.ts' +import { searchFieldKeyDown } from './menu-search.ts' import css from './BaseMenu.module.css' /** Milliseconds between the last keystroke of a search and the listing it reads. */ @@ -169,12 +170,7 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B } value={query} aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} onChange={(event) => { setQuery(event.target.value) }} - onKeyDown={(event) => { - if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() - if (event.key !== 'Enter' || event.nativeEvent.isComposing || first === undefined) return - event.preventDefault() - pick(first.base) - }} /> + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.base) }) }} />
{body}
{t('diff.base.note')}
diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index a5f1abbab2..4e455c1037 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -1,33 +1,36 @@ /** * One change request as a card: its title links to the host, a one-line - * summary shows while collapsed, and while expanded one row per fact (checks, - * review, merge state, and the changed lines, which open its changes) above - * the ready-for-review or merge action. + * summary shows while collapsed, and while expanded one sentence per fact + * (checks, review, merge state, the changed lines, which open its changes, and + * the linked issues) above the ready-for-review or merge action. */ -import { useEffect, useState, type ReactNode } from 'react' +import { useId, useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, - IconListPenOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, IconUserOutlineRegular, Menu, MenuItemButton, - StateDot, Tooltip, + Button, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, IconListPenOutlineRegular, + IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu, MenuItemButton, StateDot, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { - ChangeRequestCheck, ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest, + ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import type { ForgePanelChangeRequest } from '../types.ts' -import { formatAgo, formatDuration } from './format.ts' +import { ChecksRow, IssuesRow, MergeRow, ReviewRow, RowParts, ThreadGlyph, type OverviewActions } from './ChangeRequestOverview.tsx' +import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' -import { checkCounts, checkDuration, ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' +import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' import css from './ForgeTab.module.css' type Translate = PropsLocale['t'] -/** What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, and `viewChanges`. */ -export interface ChangeRequestActions { +/** + * What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, `viewChanges`, and the + * overview actions. + */ +export interface ChangeRequestActions extends OverviewActions { /** Open a URL outside the app. */ readonly openLink: (url: string) => void /** Copy a URL to the clipboard. */ @@ -87,10 +90,6 @@ const ROLLUP: Record = { failure: 'failure', } -const CHECK_RANK: Record = { - failure: 0, pending: 1, success: 2, neutral: 3, skipped: 3, cancelled: 3, -} - /** The unresolved thread count, with `+` when the provider counted only some threads. */ function threadCount(snapshot: ChangeRequestSnapshot, locale: string): string { const count = snapshot.unresolvedThreads.toLocaleString(locale) @@ -101,17 +100,6 @@ function failureOf(entry: ForgePanelChangeRequest): ForgeFailure | undefined { return entry.update !== null && 'failure' in entry.update ? entry.update.failure : undefined } -/** Failed checks first, then running ones, then the rest, each group in host order. */ -function orderedChecks(checks: readonly ChangeRequestCheck[]): ChangeRequestCheck[] { - return checks.toSorted((left, right) => CHECK_RANK[left.state] - CHECK_RANK[right.state]) -} - -function checkTime(check: ChangeRequestCheck, t: Translate): string { - if (check.state === 'pending') return t(check.startedAt === null ? 'change.check.queued' : 'change.check.running') - const elapsed = checkDuration(check) - return elapsed === undefined ? '' : formatDuration(elapsed, t) -} - function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapshot; readonly locale: string }): ReactNode { return ( @@ -121,7 +109,10 @@ function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapsh ) } -/** The changed lines, as a row that opens the changes view when the provider serves the change request. */ +/** + * The changed lines with the unresolved review thread count, as a row that opens the changes view when the provider + * serves the change request. + */ function ChangesRow({ entry, snapshot, name, actions, locale, t }: { readonly entry: ForgePanelChangeRequest readonly snapshot: ChangeRequestSnapshot @@ -131,14 +122,24 @@ function ChangesRow({ entry, snapshot, name, actions, locale, t }: { readonly t: Translate }): ReactNode { const { viewChanges } = actions + const described = useId() + const threads = snapshot.unresolvedThreads > 0 || snapshot.threadsTruncated ? threadCount(snapshot, locale) : undefined + const threadsText = threads === undefined ? undefined : t('change.threads', { count: threads }) + const trailing = threadsText === undefined ? undefined : ( + + + + ) + const opens = viewChanges !== undefined && entry.ref !== null + // The count shows only a number, so the threads are named in full for assistive technology. const parts = ( <> - - {t('change.row.changes')} - + } + value={} trailing={trailing} opens={opens} /> + {threadsText !== undefined && {threadsText}} ) - if (viewChanges === undefined || entry.ref === null) return
{parts}
+ if (!opens) return
{parts}
return ( ) } @@ -198,105 +199,6 @@ function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; rea ) } -type CheckRead = { readonly kind: 'idle' | 'loading' } - | { readonly kind: 'ready'; readonly snapshot: ChangeRequestSnapshot } - | { readonly kind: 'failed'; readonly message: string } - -function ChecksRow({ snapshot, openLink, readChecks, t }: { - readonly snapshot: ChangeRequestSnapshot - readonly openLink: (url: string) => void - readonly readChecks: ChangeRequestActions['readChecks'] - readonly t: Translate -}): ReactNode { - const [open, setOpen] = useState(false) - const [read, setRead] = useState({ kind: 'idle' }) - const [attempt, setAttempt] = useState(0) - const { url, headSha, checksTruncated } = snapshot - useEffect(() => { - if (!open || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } - const controller = new AbortController() - setRead({ kind: 'loading' }) - void (async () => { - try { - const result = await readChecks(url, headSha, controller.signal) - if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) - } catch (error) { - if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) - } - })() - return () => { controller.abort() } - }, [open, url, headSha, checksTruncated, readChecks, attempt]) - const displayed = read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot - if (displayed.checks.length === 0 && !displayed.checksTruncated) { - return ( -
- - {t('change.row.checks')} - {t('change.ci.none')} -
- ) - } - const counts = checkCounts(displayed.checks) - const summary = displayed.checksTruncated ? t('change.checks.truncated', { count: displayed.checks.length }) : [ - ...counts.failed > 0 ? [t('change.checks.failed', { count: counts.failed })] : [], - ...counts.running > 0 ? [t('change.checks.running', { count: counts.running })] : [], - ...counts.passed > 0 ? [t('change.checks.passed', { count: counts.passed })] : [], - ...counts.cancelled > 0 ? [t('change.checks.cancelled', { count: counts.cancelled })] : [], - ...counts.other > 0 ? [t('change.checks.other', { count: counts.other })] : [], - ].join(' · ') - const close = (): void => { setOpen(false) } - const footer: MenuEntry[] = displayed.checksTruncated - ? [{ type: 'label', id: 'truncated', text: t('change.checks.truncated', { count: displayed.checks.length }) }] : [] - if (read.kind === 'loading') footer.push({ id: 'loading', label: t('change.checks.loading'), disabled: true, icon: }) - if (read.kind === 'failed') { - footer.push({ type: 'label', id: 'failed', text: t('change.checks.loadFailed', { message: read.message }) }, - { id: 'retry', label: t('change.checks.retry') }) - } - return ( - { setOpen(!open) }}> - - {t('change.row.checks')} - 0 ? 'error' : undefined}> - {summary} - - - - )} - footer={footer} - onSelect={() => { setAttempt(value => value + 1) }} - > - {orderedChecks(displayed.checks).map((check, index) => { - const { url } = check - return ( - } - disabled={url === null} - onSelect={url === null ? close : () => { - close() - openLink(url) - }} - > - - {check.name} - {checkTime(check, t)} - - - ) - })} - - ) -} - /** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: { readonly snapshot: ChangeRequestSnapshot @@ -423,8 +325,8 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { return (
- - {finished(snapshot, now, t)} + } + value={finished(snapshot, now, t)} tone={snapshot.state} opens={false} />
{changes}
@@ -437,21 +339,15 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { : snapshot.mergeability === 'conflicting' ? t('change.merge.conflicting', { base: snapshot.baseBranch }) : t('change.merge.unknown') return (
- -
- - {t('change.row.review')} - - {snapshot.unresolvedThreads > 0 || snapshot.threadsTruncated - ? t('change.review.threads', { review, count: threadCount(snapshot, locale) }) : review} - -
-
- - {t('change.row.merge')} - {merge} -
+ + + } + tone={snapshot.mergeability === 'conflicting' ? 'error' : undefined} t={t} /> {changes} +
) } diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css new file mode 100644 index 0000000000..3f0cc3ba36 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css @@ -0,0 +1,196 @@ +/* Overview rows of an expanded change request card and the menus they open. */ + +/* A row that anchors its menu keeps the card's row grid. */ +.rowAnchor { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; +} + +/* Overlapping reviewer avatars at the end of the review row. */ +.avatars { + display: inline-flex; + align-items: center; +} + +.avatars > .avatar + .avatar { + margin-left: -5px; +} + +.avatars > .avatar { + box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-layer-1); +} + +.moreCount { + margin-left: 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + font-variant-numeric: tabular-nums; +} + +.avatar { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + box-sizing: border-box; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-interactive-bg-active); + color: var(--dsw-alias-label-secondary); + font-size: 10px; + font-weight: 600; + line-height: 1; + object-fit: cover; +} + +/* The update action named at the end of the merge row. */ +.action { + color: var(--dsw-alias-link); + white-space: nowrap; +} + +.menu { + width: min(300px, calc(100vw - 24px)); + max-height: min(420px, calc(100vh - 48px)); +} + +.menuLabel { + padding: 6px 8px 2px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.menuStatus { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 6px 8px; + color: var(--dsw-alias-label-secondary); + font-size: 12px; +} + +.check { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + min-width: 0; +} + +.checkTime { + flex: none; + margin-left: auto; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +/* A reviewer is information, not a choice, so it sits in the menu's row geometry without a hover. */ +.reviewer { + display: flex; + align-items: center; + gap: 8px; + min-height: 32px; + padding: 0 8px; + font-size: 12px; +} + +.who { + display: inline-flex; + flex: 1; + align-items: baseline; + gap: 6px; + min-width: 0; + color: var(--dsw-alias-label-primary); +} + +.kind { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + white-space: nowrap; +} + +/* The outcome, then a note when it was given on an older commit, on one line. */ +.outcome { + display: inline-flex; + flex: none; + align-items: baseline; + gap: 4px; + color: var(--dsw-alias-label-secondary); + white-space: nowrap; +} + +.outcome [data-tone='success'] { + color: var(--dsw-alias-state-success-primary); +} + +.outcome [data-tone='error'] { + color: var(--dsw-alias-state-error-primary); +} + +.outcome [data-tone='pending'] { + color: var(--dsw-alias-state-warn-label); +} + +.older { + color: var(--dsw-alias-label-tertiary); + font-size: 11px; +} + +.older::before { + content: '· '; +} + +.menuSearch { + padding: 4px 4px 6px; +} + +.menuRows { + max-height: 280px; + overflow: auto; +} + +.candidate { + display: flex; + align-items: baseline; + gap: 6px; + min-width: 0; +} + +.badge { + flex: none; + padding: 0 5px; + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 17px; +} + +/* An issue the change request closes, named by its number; a closed one takes the merged tone. */ +.issue { + border-radius: var(--dsw-radius-xs); + color: var(--dsw-alias-link); + font-variant-numeric: tabular-nums; + text-decoration: none; +} + +.issue[data-state='closed'] { + color: var(--dsw-alias-state-done-primary); +} + +@media (hover: hover) { + .issue:hover { + text-decoration: underline; + text-underline-offset: 2px; + } +} + +.issue:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx new file mode 100644 index 0000000000..4fb047f74d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -0,0 +1,620 @@ +/** + * Overview rows of an expanded change request card, each one line: the checks outcome, the review decision with the + * reviewers' avatars, the merge state, and the issues linked to the change request. Details and actions open in a menu + * from the row: the checks grouped by outcome with the rerun of the failed ones, the reviewers with review requests, + * and the branch update. + */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconChevronRightOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconSearchOutlineRegular, + IconUserOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip, + type MenuEntry, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { + BranchUpdateMethod, BranchUpdateRequest, ChangeRequestCheck, ChangeRequestIssue, ChangeRequestReviewer, ChangeRequestSnapshot, + ForgeRerunRequest, ForgeReviewerCandidate, ReviewVerdict, +} from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgePanelChangeRequest } from '../types.ts' +import { formatDuration } from './format.ts' +import { CheckGlyph } from './glyphs.tsx' +import type { ForgePanelKey, NS } from './locales.ts' +import { checkCounts, checkDuration } from './status.ts' +import { searchFieldKeyDown } from './menu-search.ts' +import css from './ForgeTab.module.css' +import overview from './ChangeRequestOverview.module.css' + +type Translate = PropsLocale['t'] + +/** Milliseconds between the last keystroke of a reviewer search and the listing it reads. */ +const SEARCH_DELAY_MS = 150 + +/** Avatars the review row shows before it counts the rest. */ +const AVATARS = 3 + +/** Requests reviews of a change request from more reviewers; settles once the outcome is reported. */ +type RequestReviews = (entry: ForgePanelChangeRequest, reviewers: readonly Pick[]) => Promise + +/** Lists the accounts a review of the change request at `url` can be requested from. */ +type ListCandidates = (url: string, query: string, signal: AbortSignal) => Promise + +/** Overview actions of a card; a surface without a Session binding omits them. */ +export interface OverviewActions { + /** Rerun the failed checks; settles once the outcome is reported. */ + readonly rerunChecks?: ((entry: ForgePanelChangeRequest, request: ForgeRerunRequest) => Promise) | undefined + /** Request reviews from more reviewers; settles once the outcome is reported. */ + readonly requestReviews?: RequestReviews | undefined + /** List accounts a review can be requested from; rejects with the host's reason. */ + readonly reviewerCandidates?: ListCandidates | undefined + /** Bring the base branch's new commits into the head branch; settles once the outcome is reported. */ + readonly updateBranch?: ((entry: ForgePanelChangeRequest, request: BranchUpdateRequest) => Promise) | undefined +} + +/** One action at a time per control: it stays disabled until the previous action settles. */ +function useBusy(): readonly [boolean, (action: () => Promise) => void] { + const [busy, setBusy] = useState(false) + return [busy, (action) => { + setBusy(true) + void action().finally(() => { setBusy(false) }) + }] +} + +/** + * The parts of one fact row: its glyph, its one-line value after the fact's name, which only assistive technology + * reads unless the value names the fact itself, an optional trailing part, and the chevron of a row that opens something. + * @param props - the fact's name for assistive technology, the glyph, the value with its tone, the trailing part, and + * whether the row opens something. + * @returns the row's cells. + */ +export function RowParts({ label, icon, value, tone, trailing, opens }: { + readonly label: string | undefined + readonly icon: ReactNode + readonly value: ReactNode + readonly tone?: string | undefined + readonly trailing?: ReactNode + readonly opens: boolean +}): ReactNode { + return ( + <> + {icon} + + {label !== undefined && {label}} + {value} + + {trailing !== undefined && {trailing}} + {opens && } + + ) +} + +type CheckGroup = 'failed' | 'running' | 'cancelled' | 'passed' | 'other' + +/** Groups that need attention, listed whenever the menu opens. */ +const ATTENTION: readonly CheckGroup[] = ['failed', 'running', 'cancelled'] + +/** Groups the menu lists only on request. */ +const QUIET: readonly CheckGroup[] = ['passed', 'other'] + +const GROUP_LABEL: Record = { + failed: 'checks.group.failed', + running: 'checks.group.running', + cancelled: 'checks.group.cancelled', + passed: 'checks.group.passed', + other: 'checks.group.other', +} + +function groupOf(check: ChangeRequestCheck): CheckGroup { + switch (check.state) { + case 'failure': return 'failed' + case 'pending': return 'running' + case 'success': return 'passed' + case 'cancelled': return 'cancelled' + case 'neutral': + case 'skipped': return 'other' + } +} + +function checkTime(check: ChangeRequestCheck, t: Translate): string { + if (check.state === 'pending') return t(check.startedAt === null ? 'change.check.queued' : 'change.check.running') + const elapsed = checkDuration(check) + return elapsed === undefined ? '' : formatDuration(elapsed, t) +} + +/** The checks outcome in a few words: what needs attention, else that all passed. */ +function checksValue(snapshot: ChangeRequestSnapshot, t: Translate): string { + if (snapshot.checksTruncated) return t('change.checks.truncated', { count: snapshot.checks.length }) + const counts = checkCounts(snapshot.checks) + const parts = [ + ...counts.failed > 0 ? [t('change.checks.failed', { count: counts.failed })] : [], + ...counts.running > 0 ? [t('change.checks.running', { count: counts.running })] : [], + ...counts.cancelled > 0 ? [t('change.checks.cancelled', { count: counts.cancelled })] : [], + ] + return parts.length > 0 ? parts.join(' · ') : t('checks.allPassed', { count: counts.passed + counts.other }) +} + +type CheckRead = { readonly kind: 'idle' | 'loading' } + | { readonly kind: 'ready'; readonly snapshot: ChangeRequestSnapshot } + | { readonly kind: 'failed'; readonly message: string } + +/** Props of the checks row. */ +export interface ChecksRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + readonly openLink: (url: string) => void + /** Load complete check details independently of polling; cancellation follows the open menu. */ + readonly readChecks: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined + readonly rerunChecks: OverviewActions['rerunChecks'] + readonly t: Translate +} + +/** + * Whether a failed check names a rerun that none of the checks sharing it still waits for, as a rerun of checks in + * progress cannot start. + * @param checks - the checks of the head commit. + * @returns whether a rerun of failed checks can start. + */ +function rerunnable(checks: readonly ChangeRequestCheck[]): boolean { + const running = new Set(checks.flatMap(check => check.state === 'pending' && check.rerun !== null ? [check.rerun] : [])) + return checks.some(check => check.state === 'failure' && check.rerun !== null && !running.has(check.rerun)) +} + +/** + * Render the checks outcome as a row whose menu lists the failed, running, and cancelled checks by group, offers to + * rerun the failed ones, and lists the passed and skipped ones on request. A list the poll read only in part is + * completed while the menu is open. + * @param props - the change request, its snapshot, the link and read actions, the rerun action, and copy. + * @returns the row with its menu. + */ +export function ChecksRow({ entry, snapshot, openLink, readChecks, rerunChecks, t }: ChecksRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [quiet, setQuiet] = useState(false) + const [read, setRead] = useState({ kind: 'idle' }) + const [attempt, setAttempt] = useState(0) + const [busy, run] = useBusy() + const { url, headSha, checksTruncated } = snapshot + useEffect(() => { + if (!open || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } + const controller = new AbortController() + setRead({ kind: 'loading' }) + void (async () => { + try { + const result = await readChecks(url, headSha, controller.signal) + if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) + } catch (error) { + if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) + } + })() + return () => { controller.abort() } + }, [open, url, headSha, checksTruncated, readChecks, attempt]) + const displayed = read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot + if (displayed.checks.length === 0 && !displayed.checksTruncated) { + return
} value={t('change.ci.none')} opens={false} />
+ } + const counts = checkCounts(displayed.checks) + const rerun = displayed.state === 'open' && displayed.canRerunChecks && rerunnable(displayed.checks) ? rerunChecks : undefined + const groups = (list: readonly CheckGroup[]): { readonly group: CheckGroup; readonly checks: ChangeRequestCheck[] }[] => + list.map(group => ({ group, checks: displayed.checks.filter(check => groupOf(check) === group) })) + .filter(({ checks }) => checks.length > 0) + const quietCount = counts.passed + counts.other + const close = (): void => { + setOpen(false) + setQuiet(false) + } + const rows = (list: readonly CheckGroup[]): ReactNode => groups(list).map(({ group, checks }) => ( +
+
{`${t(GROUP_LABEL[group])} · ${checks.length}`}
+ {checks.map((check, index) => { + const link = check.url + return ( + // The list is replaced as a whole with each snapshot, and check names can repeat. + } disabled={link === null} + onSelect={link === null ? close : () => { + close() + openLink(link) + }}> + + {check.name} + {checkTime(check, t)} + + + ) + })} +
+ )) + const rollup = displayed.checksRollup === 'none' ? 'neutral' : displayed.checksRollup + return ( + { if (open) close(); else setOpen(true) }}> + } value={checksValue(displayed, t)} opens + tone={!displayed.checksTruncated && counts.failed > 0 ? 'error' : undefined} /> + + )}> + {rerun !== undefined && ( + } disabled={busy} onSelect={() => { + close() + run(() => rerun(entry, { headSha })) + }}> + {t('checks.rerunFailed')} + + )} + {rows(ATTENTION)} + {quiet ? rows(QUIET) : quietCount > 0 && ( + 0} + icon={ 0 ? 'success' : 'skipped'} size={14} />} + onSelect={() => { setQuiet(true) }}> + {t('checks.showQuiet', { count: quietCount })} + + )} + {read.kind === 'loading' &&
{t('change.checks.loading')}
} + {read.kind === 'failed' && ( +
+ {t('change.checks.loadFailed', { message: read.message })} + +
+ )} +
+ ) +} + +const VERDICT: Record = { + 'approved': { key: 'reviewers.approved', tone: 'success' }, + 'changes-requested': { key: 'reviewers.changesRequested', tone: 'error' }, + 'commented': { key: 'reviewers.commented', tone: undefined }, + 'dismissed': { key: 'reviewers.dismissed', tone: undefined }, +} + +function Avatar({ url, login, size = 20 }: { readonly url: string | null; readonly login: string; readonly size?: number }): ReactNode { + const [broken, setBroken] = useState(false) + const style = { width: size, height: size } + if (url === null || broken) { + return ( + + ) + } + // Lazy images inside the panel's scroller never load in Chromium, so avatars load eagerly. + return { setBroken(true) }} /> +} + +/** Props of the review row. */ +export interface ReviewRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + /** The aggregate review outcome. */ + readonly value: string + /** Tone of the aggregate outcome. */ + readonly tone: string | undefined + readonly requestReviews: OverviewActions['requestReviews'] + readonly reviewerCandidates: OverviewActions['reviewerCandidates'] + readonly openLink: (url: string) => void + readonly t: Translate +} + +/** + * Render the review decision as a row with the first reviewers' avatars. Its menu lists each reviewer with their + * latest outcome or that their review is requested, and, when the signed-in user may request reviews, offers to ask a + * reviewer again and to request a review from someone else through a search. + * @param props - the change request, its snapshot, the aggregate outcome, the review request actions, and copy. + * @returns the row with its menu. + */ +export function ReviewRow({ entry, snapshot, value, tone, requestReviews, reviewerCandidates, openLink, t }: ReviewRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [searching, setSearching] = useState(false) + const [busy, run] = useBusy() + const { reviewers } = snapshot + const ask = snapshot.canRequestReviews && reviewerCandidates !== undefined ? requestReviews : undefined + const canRequest = ask !== undefined + const avatars = reviewers.length === 0 ? undefined : ( + + ) + const opens = reviewers.length > 0 || canRequest + const parts = ( + } value={value} tone={tone} trailing={avatars} + opens={opens} /> + ) + if (!opens) return
{parts}
+ const close = (): void => { + setOpen(false) + setSearching(false) + } + const request = ask === undefined ? undefined : (reviewer: Pick): void => { + close() + run(() => ask(entry, [reviewer])) + } + // Asking again suits people who reviewed and are not asked now; bots review on their own triggers. + const again = reviewers.filter(reviewer => reviewer.kind !== 'bot' && !reviewer.requested && reviewer.verdict !== null) + return ( + { if (open) close(); else setOpen(true) }}> + {parts} + + )}> + {searching && request !== undefined && reviewerCandidates !== undefined + ? { request({ kind: 'user', login }) }} t={t} /> + : ( + <> + {reviewers.length === 0 &&
{t('reviewers.none')}
} + {reviewers.map(reviewer => ( + + ))} + {snapshot.reviewersTruncated && ( + { + close() + openLink(snapshot.url) + }}> + {t('reviewers.truncated')} + + )} + {request !== undefined && again.map((reviewer, index) => ( + } + onSelect={() => { request(reviewer) }}> + {t('reviewers.rerequestAria', { login: reviewer.login })} + + ))} + {canRequest && ( + } + onSelect={() => { setSearching(true) }}> + {t('reviewers.requestMore')} + + )} + + )} +
+ ) +} + +/** One reviewer in the review menu: avatar, login, what kind of reviewer, and their latest outcome or pending request. */ +function ReviewerLine({ reviewer, headSha, t }: { + readonly reviewer: ChangeRequestReviewer + readonly headSha: string + readonly t: Translate +}): ReactNode { + const verdict = reviewer.verdict === null ? undefined : VERDICT[reviewer.verdict] + // A shown outcome older than the head; a requested review hides the outcome. + const older = !reviewer.requested && reviewer.verdict !== null && reviewer.reviewedSha !== null + && reviewer.reviewedSha.toLowerCase() !== headSha.toLowerCase() + const kind = reviewer.codeOwner ? t('reviewers.codeOwner') : reviewer.kind === 'team' ? t('reviewers.team') + : reviewer.kind === 'bot' ? t('reviewers.bot') : undefined + return ( +
+ + + {reviewer.login} + {kind !== undefined && {kind}} + + + {reviewer.requested + ? {t('reviewers.pending')} + : verdict !== undefined && {t(verdict.key)}} + {older && {t('reviewers.older')}} + +
+ ) +} + +/** The accounts a reviewer search listed for `query`, or that the listing failed. */ +type Listing = { readonly query: string } & ( + { readonly ok: true; readonly value: readonly ForgeReviewerCandidate[] } | { readonly ok: false }) + +/** The searchable account list of a review request: the host's suggestions first, then accounts matching the search. */ +function ReviewerSearch({ url, list, choose, t }: { + readonly url: string + readonly list: ListCandidates + readonly choose: (login: string) => void + readonly t: Translate +}): ReactNode { + const [query, setQuery] = useState('') + const [attempt, setAttempt] = useState(0) + const [listing, setListing] = useState(null) + const search = useRef(null) + useEffect(() => { + const controller = new AbortController() + const timer = setTimeout(() => { + list(url, query, controller.signal).then( + (value) => { if (!controller.signal.aborted) setListing({ query, ok: true, value }) }, + () => { if (!controller.signal.aborted) setListing({ query, ok: false }) }, + ) + }, query === '' ? 0 : SEARCH_DELAY_MS) + return () => { + clearTimeout(timer) + controller.abort() + } + }, [url, query, attempt, list]) + useEffect(() => { + if (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches) return + const frame = requestAnimationFrame(() => { search.current?.focus() }) + return () => { cancelAnimationFrame(frame) } + }, []) + // A listing of an earlier query is never shown or chosen from, so Enter cannot request a review from an account the + // current query no longer names. + const current = listing !== null && listing.query === query ? listing : null + const candidates = current !== null && current.ok ? current.value : [] + let body: ReactNode + if (current === null) { + body =
{t('reviewers.loading')}
+ } else if (!current.ok) { + body = ( +
+ {t('reviewers.loadFailed')} + +
+ ) + } else if (candidates.length === 0) { + body =
{t('reviewers.empty')}
+ } else { + body = candidates.map(candidate => ( + } + onSelect={() => { choose(candidate.login) }}> + + {candidate.login} + {candidate.name !== null && candidate.name !== candidate.login && {candidate.name}} + {candidate.suggested && {t('reviewers.suggested')}} + + + )) + } + const first = candidates[0] + return ( + <> +
+ } value={query} aria-label={t('reviewers.search')} + placeholder={t('reviewers.search')} onChange={(event) => { setQuery(event.target.value) }} + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { choose(first.login) }) }} /> +
+
{body}
+ + ) +} + +/** Props of the merge row. */ +export interface MergeRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + /** Glyph of the row. */ + readonly icon: ReactNode + /** The merge conflict status. */ + readonly value: string + /** Tone of the conflict status. */ + readonly tone: string | undefined + readonly updateBranch: OverviewActions['updateBranch'] + readonly t: Translate +} + +/** + * Render the merge state as a row: the conflict status and whether the head is behind its base. While the signed-in + * user can update the head branch, the row opens the update menu: a title, one row per method, and the confirmation, + * which is refused once the head moved after the menu opened. + * @param props - the change request, its snapshot, the row glyph and status, the update action, and copy. + * @returns the row, with its menu when the branch can be updated. + */ +export function MergeRow({ entry, snapshot, icon, value, tone, updateBranch, t }: MergeRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [confirmedHead, setConfirmedHead] = useState(snapshot.headSha) + const [usual = 'merge'] = snapshot.branchUpdates + const [chosen, setChosen] = useState(usual) + const [busy, run] = useBusy() + const behind = snapshot.branchUpdates.length > 0 + const text = behind ? `${value} · ${t('branch.behind', { base: snapshot.baseBranch })}` : value + if (!behind || updateBranch === undefined) { + return
+ } + const stale = confirmedHead !== snapshot.headSha + const method: BranchUpdateMethod = snapshot.branchUpdates.find(entry => entry === chosen) ?? usual + const base = snapshot.baseBranch + const items: MenuEntry[] = [ + { type: 'label', id: 'title', text: t('branch.updateTitle', { head: snapshot.headBranch, base }) }, + ...snapshot.branchUpdates.map(entry => ({ + id: entry, + label: ( + + {t(`branch.method.${entry}`)} + {t(`branch.note.${entry}`, { base })} + + ), + })), + ] + return ( + { setOpen(false) }} portal align="end" className={overview.rowAnchor} items={items} + selectedId={method} onSelect={setChosen} + anchor={( + + )}> + { + setOpen(false) + run(() => updateBranch(entry, { method, headSha: confirmedHead })) + }}> + {t(stale ? 'branch.changed' : 'branch.confirm')} + + + ) +} + +/** + * A speech bubble, the glyph of review threads. + * @param props - glyph size in pixels. + * @returns the decorative glyph. + */ +export function ThreadGlyph({ size = 14 }: { readonly size?: number }): ReactNode { + return ( + + ) +} + +/** An issue: a ring around a dot. */ +function IssueGlyph(): ReactNode { + return ( + + ) +} + +/** The issue's label: `#n` within the change request's repository, else `owner/name#n`. */ +function issueLabel(issue: ChangeRequestIssue, snapshot: ChangeRequestSnapshot): string { + const { owner, name } = snapshot.ref.repository + const same = issue.repository.owner.toLowerCase() === owner.toLowerCase() + && issue.repository.name.toLowerCase() === name.toLowerCase() + return same ? `#${issue.number}` : `${issue.repository.owner}/${issue.repository.name}#${issue.number}` +} + +/** + * Render the issues linked to the change request, which the host closes once it merges, as one row of links, each + * named by its number with its title in a tooltip, or nothing without one. More issues than the provider read end the + * row with a note. + * @param props - the snapshot, the link action, and copy. + * @returns the row, or null. + */ +export function IssuesRow({ snapshot, openLink, t }: { + readonly snapshot: ChangeRequestSnapshot + readonly openLink: (url: string) => void + readonly t: Translate +}): ReactNode { + if (snapshot.closingIssues.length === 0) return null + const links = snapshot.closingIssues.map((issue, index) => { + const label = issueLabel(issue, snapshot) + return ( + + {index > 0 && t('issues.separator')} + + { + event.preventDefault() + openLink(issue.url) + }}> + {label} + + + + ) + }) + return ( +
+ } opens={false} + value={<>{t('issues.label')}{' '}{links}{snapshot.closingIssuesTruncated && t('issues.more')}} /> +
+ ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css index 2006c2b546..db93e6decd 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css @@ -14,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; } } diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index eb24d62b51..73edf2f7aa 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -133,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 { setOpen(false) }} + return { setOpen(false) }} anchor={}> + onClick={() => { setOpen(value => !value) }}> + {props.t('diff.allFiles', { count: props.files.length })} + + }> { setOpen(false); props.jump(path) }} /> } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 9183d560e4..6b71b2428c 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -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 label shortened to the bare count beside its 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; @@ -528,6 +540,13 @@ } } +/* While its write is in flight or the host's marks could not be read, the mark keeps its place and shows it cannot change. */ +.viewed[data-disabled], +.viewed[data-disabled] input { + color: var(--dsw-alias-label-tertiary); + cursor: default; +} + .viewed:has(input:focus-visible) { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: -1px; @@ -679,6 +698,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. */ @@ -860,7 +909,8 @@ .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; } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 18142cf969..9fe4e1831d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -25,13 +25,15 @@ 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, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeThreadId, + ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, + ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -44,6 +46,7 @@ import type { ChangesLens, createChangesStore } from './changes-store.ts' import { CommitMenu } from './CommitMenu.tsx' import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts' +import { hostViewedOf, useHostViewed, type HostViewed } from './host-viewed.ts' import { Counts, DiffFile, type DiffFileAction, type DiffFileHandlers } from './DiffFile.tsx' import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' @@ -53,7 +56,9 @@ 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 type { FileThreads, ThreadActions, ThreadFocus } from './ReviewThreads.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' @@ -98,14 +103,23 @@ export interface ChangesTabInjected { ) => Promise> /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */ readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise> - /** The Session's viewed marks, kept in the browser. */ + /** The Session's viewed marks, kept in the browser for local changes, chosen commits, and hosts that keep none. */ readonly viewedFiles: ViewedFiles + /** + * Read the signed-in user's viewed marks on a change request's files at `headSha`, or null when its provider keeps + * none; `signal` aborts the read. + */ + readonly changeRequestViewed: (url: string, headSha: string, signal: AbortSignal) => Promise> + /** Set or clear the signed-in user's viewed mark on one file of a change request. */ + readonly setFileViewed: (url: string, request: ForgeViewedRequest) => Promise> /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** 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> + /** Write to the review threads or the pending review of a change request; never retries a write. */ + readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise> /** 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. */ @@ -150,8 +164,16 @@ type ChangesData = readonly localAhead: number | null /** Web page of each file at the head. */ readonly fileUrls: Readonly> + /** The code host's viewed marks of the whole change request, or null when the browser keeps the marks. */ + readonly viewed: HostViewed | null } +/** 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 @@ -208,11 +230,23 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T return key === undefined || base === null ? undefined : t(key, { base: base.name }) } +/** + * Read the changes a view shows. The whole change request also reads the host's viewed marks at the head of the latest + * status, beside the diff; marks read at another head refuse the read as the diff refuses a moved head. + * @param source - local changes or a change request. + * @param scope - local scope to read. + * @param commits - chosen commits of a change request, or null for all of it. + * @param head - head commit of the change request's latest status, or null. + * @param reads - the Remote reads. + * @param signal - cancellation of the reads. + * @returns the changes, or why they could not be read. + */ async function readChanges( source: ChangesSource, scope: ForgeLocalScope, commits: ForgeCommitRange | null, - reads: Pick, + head: string | null, + reads: Pick, signal: AbortSignal, ): Promise> { if (source.kind === 'local') { @@ -221,10 +255,15 @@ async function readChanges( const { files, base, omitted } = result.value return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } - const result = await reads.changeRequestDiff(source.url, commits, signal) + const [result, marks] = await Promise.all([ + reads.changeRequestDiff(source.url, commits, signal), + commits === null && head !== null && head !== '' ? reads.changeRequestViewed(source.url, head, signal) : Promise.resolve(null), + ]) if (!result.ok) return result + if (marks !== null && !marks.ok && marks.error.code === 'forgePanel/stale-head') return marks const { files, headSha, localAhead, fileUrls } = result.value - return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } } + const viewed = hostViewedOf(marks, headSha) + return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls, viewed } } } /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ @@ -320,7 +359,7 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis {number !== null && {t('change.number', { number })}} {commitMenu} - @@ -371,7 +410,7 @@ function LocalHeader({ state, scope, base, missing, visible, diffBases, choose, } {(scope === 'branch' || creatable) && {scope === 'branch' && commitMenu} - {creatable && } + {creatable && } } ) @@ -434,7 +473,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { return

{path}

{state.threads.map(thread => )} + actions={actions} locked={state.locked} outdated t={t} />)}
} @@ -445,7 +484,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, viewedFiles, + changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -494,6 +533,47 @@ 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.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 => { + const run = async (): Promise => { + 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 => (await sendWrite(url, write))?.message const choices = useStore(store => store.byTab[tab.id]) const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) @@ -564,30 +644,32 @@ export function ChangesTab({ if (!tab.visible || read === null || read === finished || waiting) return const controller = new AbortController() const readAt = latestStatusAt.current - void readChanges(source, localScope, changeCommits, { localDiff, changeRequestDiff }, controller.signal).then((result) => { - if (controller.signal.aborted) return - if (!result.ok && result.error.code === 'forgePanel/stale-head') { - setRefused({ read, statusAt: readAt }) - setFailure(null) - return - } - setFinished(read) - if (result.ok) { - setLoaded({ key: dataKey, data: result.value }) - setFailure(null) - } else { - setFailure({ key: dataKey, code: result.error.code }) - } - }) + void readChanges(source, localScope, changeCommits, head, { localDiff, changeRequestDiff, changeRequestViewed }, controller.signal) + .then((result) => { + if (controller.signal.aborted) return + if (!result.ok && result.error.code === 'forgePanel/stale-head') { + setRefused({ read, statusAt: readAt }) + setFailure(null) + return + } + setFinished(read) + if (result.ok) { + setLoaded({ key: dataKey, data: result.value }) + setFailure(null) + } else { + setFailure({ key: dataKey, code: result.error.code }) + } + }) return () => { controller.abort() } - }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, head, dataKey, localDiff, changeRequestDiff, + changeRequestViewed]) 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, read: changeRequestReview }) + 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) @@ -605,7 +687,15 @@ export function ChangesTab({ allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record, [allFiles, hideTests]) const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data]) const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource) - const marks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) + const localMarks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) + const hostOwner = useMemo(() => data?.kind === 'change' && data.viewed !== null + ? { url: data.url, headSha: data.headSha, files: data.files, viewed: data.viewed } : null, [data]) + const host = useHostViewed(hostOwner, setFileViewed, (failure) => { + if (failure.kind === 'stale') report('viewed.syncStale') + else if (failure.kind === 'unknown') report('viewed.syncUnknown', { message: failure.message }) + else report('viewed.syncFailed', { message: failure.message }) + }) + const marks = host?.marks ?? localMarks // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -622,6 +712,13 @@ export function ChangesTab({ const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file) const sections = useRef(new Map()) const scrollport = useRef(null) + const toolbarRow = useRef(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 @@ -711,16 +808,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, done: ForgePanelKey): Promise => { + 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 && { 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 => { + 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) } @@ -742,6 +891,11 @@ export function ChangesTab({ 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(threadActions === null ? [] : [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions]) @@ -819,7 +973,9 @@ export function ChangesTab({ } /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */ const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => { - if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { + if (host !== null) { + if (!host.mark(file.path, viewed)) return + } else if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { report('viewed.saveFailed') return } @@ -853,8 +1009,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, nextThread, t }) - live.current = { data, expandedByDefault, expand, markViewed, fileActions, publishReview, report, nextThread, 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) @@ -883,24 +1042,28 @@ export function ChangesTab({ 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) { @@ -960,6 +1123,9 @@ export function ChangesTab({ threads={fileThreads.get(path)} drawNow={wanted !== null && wanted.center !== null && wanted.path === path} viewed={viewedStateOf(marks, path, file.digest)} + viewedNote={host === null ? t('viewed.hint') : host.unavailable ? t('viewed.unavailable') + : host.saving(path) ? t('viewed.saving') : t('viewed.hintHost')} + viewedDisabled={host !== null && (host.unavailable || host.saving(path))} handlers={handlers} t={t} /> @@ -979,6 +1145,10 @@ export function ChangesTab({ // 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 @@ -1000,7 +1170,8 @@ export function ChangesTab({ ? { actions.based(tab.id, next) }} commitMenu={commitMenu} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
@@ -1013,16 +1184,16 @@ export function ChangesTab({
{/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */} {treeShown &&
} -
+
{tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } + {tab.visible && } {tab.visible && allFiles.length > 0 && ( - + )} - {allFiles.length > 0 && -
{data !== null && failed !== null && ( @@ -1082,6 +1257,11 @@ export function ChangesTab({ {t('diff.stale', { count: data.localAhead })} )} {data?.kind === 'local' && data.omitted > 0 && {t('diff.omitted', { count: data.omitted })}} + {data?.kind === 'change' && data.viewed?.kind === 'failed' && ( + {t('retry')}}> + {t('viewed.readFailed', { message: data.viewed.message })} + + )} {data?.kind === 'change' && threadRead.failure !== null && ( {t('retry')}}> {t('thread.loadFailed', { message: threadRead.failure })} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index e07bb2f722..fc25c20ebc 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -95,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 + /** Tooltip of the viewed mark: where marks are kept, or why the mark cannot change now. */ + readonly viewedNote: string + /** Whether the mark cannot change now, while its write is in flight or the host's marks could not be read. */ + readonly viewedDisabled: boolean /** 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. */ @@ -161,6 +165,21 @@ 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' } @@ -176,33 +195,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(null) + // Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range. + const chosen = useRef(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([]) const root = useRef(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(`[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 => { @@ -220,10 +259,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) @@ -237,12 +276,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. @@ -252,8 +292,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) => { @@ -262,13 +304,14 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme })) { return {line ?? ''} } - 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 { if (dragging.current === 'gutter' && origin.current?.side === side && event.buttons === 1) choose(side, line, true) }}> - {plus && ( + {plus !== null && ( )} {/* Keyboard and assistive technology reach the same editor through the line button and the labeled plus above. */} - {hover && !plus && !editing && ( + {hover && plus === null && (
) - 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) - appendThreads(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(
{ 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)}{SIGN[row.kind]}
) - if (!inserted && endsAt(row.old, row.new)) { - rows.push(editor) - inserted = true - } - appendComments(row.old, row.new) - appendThreads(row.old, row.new) + rows.push(...commentsAt('L', row.old), ...commentsAt('R', row.new)) } } } - if (review !== undefined) for (const thread of remaining) { - rows.push() + 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() + } } - for (const item of unplaced) rows.push(threadCard(item, false)) - if (!inserted) rows.push(editor) + for (const item of unplaced) rows.push(threadCard(item)) return
{ setNativeSide(side) - if (editing) return - setSelection(null) + select(null) setSelecting(true) }) }}>{rows}
@@ -425,7 +475,7 @@ 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 => ) + actions={review} locked={comments.locked} outdated={!reviewMatches(thread.selection, review.source, file)} t={t} />) const lineThreads = threads?.lines.map(item => ) if (file.binary) return <>

{t('diff.binary')}

{records}{lineThreads} @@ -504,7 +554,7 @@ function FileMenu({ name, file, handlers, t }: { * @returns the file section. */ function DiffFileSection(props: DiffFileProps): ReactNode { - const { file, expanded, large, revealed, badge, tooltip, viewed, threads, handlers, t } = props + const { file, expanded, large, revealed, badge, tooltip, viewed, viewedNote, viewedDisabled, threads, handlers, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) const element = useRef(null) const [reached, setReached] = useState(false) @@ -555,8 +605,8 @@ function DiffFileSection(props: DiffFileProps): ReactNode { {badge !== '' && {badge}} {!file.binary && } - diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css index 168caafc17..3ce29555e6 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css @@ -395,13 +395,14 @@ line-height: 18px; } -/* Expanded facts, one row each: an icon under the glyph, the label, the value, - and a chevron on a row that opens something. */ +/* Expanded facts, one sentence per row: an icon under the glyph, the value, an optional trailing part, and a chevron + on a row that opens something. */ .rows { + /* Contains the visually hidden row labels, so they never extend a scroll area outside the panel. */ + position: relative; display: grid; - /* Edge tracks include each row's padding; labels retain their Chinese width and grow for longer translations. */ - grid-template-columns: 24px minmax(32px, max-content) minmax(0, 1fr) 22px; - gap: 2px 10px; + grid-template-columns: 24px minmax(0, 1fr) auto 12px; + gap: 0 8px; padding: 4px 6px 6px; border-top: 0.5px solid var(--dsw-alias-border-l2); } @@ -411,12 +412,12 @@ grid-column: 1 / -1; grid-template-columns: subgrid; align-items: center; - column-gap: 10px; + column-gap: 8px; box-sizing: border-box; width: 100%; - min-height: 34px; + min-height: 32px; margin: 0; - padding: 0 10px 0 8px; + padding: 0 8px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; @@ -429,6 +430,10 @@ grid-column: 2 / 4; } +.row:disabled { + cursor: default; +} + .rowButton { cursor: pointer; } @@ -445,23 +450,33 @@ .rowIcon { display: inline-flex; + grid-column: 1; + justify-content: center; color: var(--dsw-alias-label-tertiary); } -.rowLabel { - color: var(--dsw-alias-label-secondary); -} - .rowChevron { + grid-column: 4; color: var(--dsw-alias-label-tertiary); } .rowValue { display: inline-flex; + grid-column: 2; align-items: center; gap: 6px; min-width: 0; - overflow-wrap: anywhere; +} + +/* Trailing detail of a row, such as the reviewers' avatars or the unresolved thread count. */ +.rowTrailing { + display: inline-flex; + grid-column: 3; + align-items: center; + gap: 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + font-variant-numeric: tabular-nums; } .rowValue[data-tone='error'] { @@ -592,3 +607,21 @@ text-overflow: ellipsis; white-space: nowrap; } + +/* The unresolved review thread count at the end of the changes row. */ +.threads { + display: inline-flex; + align-items: center; + gap: 3px; + color: var(--dsw-alias-label-secondary); +} + +/* The name of a fact row, read by assistive technology before its value. */ +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx index a919d92f23..20eec63c19 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx @@ -43,6 +43,14 @@ export interface ForgeTabInjected { readonly merge: (entry: ForgePanelChangeRequest, request: MergeRequest) => Promise /** Read the complete checks of an opened change request. */ readonly readChecks: NonNullable + /** Rerun the failed checks or one check; settles once the outcome is reported. */ + readonly rerunChecks: NonNullable + /** Request reviews from more reviewers; settles once the outcome is reported. */ + readonly requestReviews: NonNullable + /** List accounts a review can be requested from. */ + readonly reviewerCandidates: NonNullable + /** Bring the base branch's new commits into the head branch; settles once the outcome is reported. */ + readonly updateBranch: NonNullable /** Check the removed worktree of the Session out again, reporting the outcome. */ readonly restore: () => void /** Open a URL outside the app. */ @@ -158,7 +166,7 @@ function SignIn({ state, copyText, t }: { */ export function ForgeTab({ useTabInfo, sessionId, usePanel, useHost, useLocale, reconnect, refresh, remove, markReady, merge, readChecks, restore, - openLink, copyText, copyPath, + rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, copyPath, reportVisible, createChangeRequest, t, }: ForgeTabProps): ReactNode { const snapshot = usePanel(current => current) @@ -190,6 +198,7 @@ export function ForgeTab({ } const actions: ChangeRequestActions = { openLink, copyLink: copyText, retry: startRefresh, remove, markReady, merge, readChecks, + rerunChecks, requestReviews, reviewerCandidates, updateBranch, viewChanges: (entry) => { viewChanges({ kind: 'change', url: entry.url }) }, } const local = state.local !== null && state.local.files.length > 0 ? state.local : null diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css index 5ce683c482..d79ac0b0e2 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css @@ -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; } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 94407dfee8..694dc51bea 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -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 - /** 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 } -function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocale & { +/** + * 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
- - {publish !== undefined && { setOpen(false) }} + + {other !== undefined && { setOpen(false) }} anchor={}> - { setOpen(false); publish() }}>{t('review.publish')} + aria-label={menuLabel} onClick={() => { setOpen(value => !value) }}>}> + { setOpen(false); menu() }}>{other} }
} @@ -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 & { +export function ReviewComposer({ selection, actions, close, visible = true, t }: PropsLocale & { 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 => { - 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) | undefined): Promise => { + 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 ( -
+
{t('review.range', { range })}