From 2ef5f9dc534bcc935f3dfbcebdd39d9280f078a6 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:20:20 +0800 Subject: [PATCH 01/15] fix(cua): select applications and windows without reading AX --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 4 +- ...026-11-05-cua-scoped-surfaces-and-input.md | 2 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 2 +- .../cua-native-platform/guide.i18n.yaml | 4 +- .../v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../cua-native-platform/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 8 +- packages/experimental/cua-macos/README.md | 14 +- packages/experimental/cua-macos/README.zh.md | 14 +- .../tests/loader-composition.spec.ts | 2 +- .../tests/persistent-bridge.built.e2e.ts | 2 +- packages/experimental/cua/README.i18n.yaml | 8 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/package.json | 3 +- packages/experimental/cua/src/api.ts | 15 +- packages/experimental/cua/src/guidance.ts | 8 +- packages/experimental/cua/src/types.ts | 8 +- packages/experimental/cua/tests/api.spec.ts | 145 ++++++++++++++++-- .../experimental/cua/tests/bridge.spec.ts | 5 +- packages/experimental/cua/tsconfig.host.json | 3 + pnpm-lock.yaml | 3 + .../cua-native/system-prompt.expected.md | 8 +- .../cua-native/workspace/native-helper.mjs | 1 + snapshots/session/cua-ptc/consent-fixture.mjs | 6 +- .../session/cua-ptc/replay.override.json | 35 ++++- snapshots/session/cua-ptc/session.v4.jsonl | 26 +++- .../session/cua-ptc/system-prompt.expected.md | 8 +- .../system-prompt.expected.md | 8 +- 29 files changed, 276 insertions(+), 78 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index f3a0d8f1d3..5f1ff64a4d 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: 4fa61247fe33edb0 + zh: afa76f74841eb586 /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 609e5bf901..3888527013 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; `getWindow` validates membership in the application’s current window list. 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 081f02986e..8a3f152e67 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` 只选择对象,不读取辅助功能或替换该快照;`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/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 a76d4de320..c907006371 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: b09e3dde32391786 - zh: f702e1e25b260b29 + en: b4d5bf5c30f42dfb + zh: 7ec59dc6a90165ef 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 3179dae0d9..a49a251c37 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 no longer read AX implicitly. 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. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. 4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. 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 f0a4a905e0..fae92008f1 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 读取成功。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 0d83c6e538..7571c8004d 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,11 +15,11 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 533ed4dd11af5126 - zh: 03036e8c949d6aca + en: e9c78a8cbd68147c + zh: 98c64b09f858edf7 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: b734a0907747580e - zh: 8110c5951b70e100 + en: 7c460511bb1cee4c + zh: 2eba4fc997427e18 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 46b035112e..d139d988a3 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -41,7 +41,7 @@ For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugin pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config ``` -The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object reads initial AX silently without activating the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session. +The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object does not read AX or activate the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session. Source builds default to `sourceSigning: ad-hoc`, without creating certificates or keychains. Changed binaries can require new permission grants. To reduce repeated grants during rebuilds and across worktrees, select an existing certificate and its absolute keychain path in the DSH home’s `cordis.patch.yml`; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`: @@ -111,9 +111,9 @@ const window = await app.getWindow(windows[0].windowId) void await window.getScreenshot() ``` -Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` read their initial trees silently; choose the window by its observed title and bounds. +Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` return without reading AX; choose the window from `getWindows()` by its title and bounds. -`getWindow` reads its initial tree silently. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` validates the ID against the current application window list. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. `mouseMove(target)` defaults to AX hover. An enabled target or ancestor must advertise both `AXShowAlternateUI` and `AXShowDefaultUI`. Moving into its descendants keeps the UI open, and leaving restores it. Without an AX route the helper returns `HOVER_UNAVAILABLE` before sending input. Click a visible control or use `performAction` with an advertised action. For browser content without these AX actions, use browser tools. Enable `systemPointerHover` only when moving the user’s visible cursor is acceptable. That route requires a foreground, unobscured target and leaves the cursor at the destination. @@ -189,9 +189,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -199,7 +199,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 341796b8c4..f8fed7b624 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -41,7 +41,7 @@ provider 按当前界面语言生成引导和恢复文案,不支持的语言 pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config ``` -配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回的对象静默读取初始 AX,不自动激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 +配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回对象时不读取 AX,也不激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 源码构建默认使用 `sourceSigning: ad-hoc` 临时签名,不创建证书或钥匙串。二进制变化后可能需要重新授权。需要减少开发重建和跨 worktree 的授权次数时,在 DSH home 的 `cordis.patch.yml` 中选择已有证书及其钥匙串绝对路径;`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID: @@ -111,9 +111,9 @@ const window = await app.getWindow(windows[0].windowId) void await window.getScreenshot() ``` -使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 静默读取初始树;根据观察到的标题与位置选择窗口。 +使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 返回时不读取 AX;根据 `getWindows()` 中的标题与位置选择窗口。 -`getWindow` 静默读取初始树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 根据当前应用窗口清单验证 ID。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `mouseMove(target)` 默认通过 AX 悬停。目标或其祖先必须已启用,并同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`。进入子控件会保持展开,离开后恢复默认界面。如果没有可用的 AX 路径,helper 返回 `HOVER_UNAVAILABLE`,不发送输入。可点击已经可见的控件,或用 `performAction` 执行控件声明的动作。浏览器内容缺少这些 AX 动作时,请使用浏览器工具。只有允许移动用户可见光标时才开启 `systemPointerHover`。这条路径要求目标在前台且未被遮挡,操作后光标停在目标位置。 @@ -189,9 +189,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -199,7 +199,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token 影响 diff --git a/packages/experimental/cua-macos/tests/loader-composition.spec.ts b/packages/experimental/cua-macos/tests/loader-composition.spec.ts index e92f138d87..e1395145d4 100644 --- a/packages/experimental/cua-macos/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-macos/tests/loader-composition.spec.ts @@ -181,7 +181,7 @@ it.skipIf(process.platform === 'win32')('shares one application between retained const screenshot = await peerWindow.getScreenshot({ emit: false }) expect(screenshot).toMatchObject({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7 }) expect(Buffer.from(screenshot.bytes).toString('base64')).toBe(png) - await peerApp.getWindow(8) + await (await peerApp.getWindow(8)).getAccessibilityTree({ emit: false }) const recovery = 'Snapshot belongs to window 8; read getAccessibilityTree on window 7' await expect(peerWindow.click(element('0'))).rejects.toThrow(recovery) await expect(peerWindow.mouseMove(element('0'))).rejects.toThrow(recovery) diff --git a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts index b37b79b6c1..61fe3b3bdb 100644 --- a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts +++ b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts @@ -74,7 +74,7 @@ it.skipIf(process.platform === 'win32' || !existsSync(bridge) || !existsSync(boo const section = (await ctx.systemPrompt.assemble()).sections.find(value => value.name === 'computer-use:dsh-cua') const initialization = section?.text.match(/Persistent PTC initialization:\n\n```ts\n([\s\S]*?)\n```/u)?.[1] expect(initialization).toContain('/lib/bridge.js') - const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') + const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.getAccessibilityTree({emit:false}); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') expect(first.error).toBeUndefined() expect(first.value).toEqual({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7, byteLength: 90 }) expect(images).toBe(1) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index f4abb13c43..fffdfaa5c6 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,14 +15,14 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ba1f8e6ae51f69d7 - zh: 8f4fde9857bae319 + en: 77dbaaa91d5b92c8 + zh: 94c3a758a91476bd /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2ab74a1ff120459e - zh: 39b3ef198989f133 + en: fbd52f5ae2ca44f8 + zh: 386fb22fa7f7703d /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index c95e4ae8ec..0b3d39fdd1 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -31,7 +31,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations on macOS. External PTC hosts import `connectCua` from `@deepseek-ai/dsh-cua/bridge` and supply the current `tools.cua` binding. Source compositions and native preparation belong to the provider. -Use `cua.getApp(selector)` to select an application; it obtains consent, optionally launches a stopped application in the background, and reads its initial accessibility tree silently when the provider supports application-level accessibility. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` returns the object for screenshots and pointer input. Select an application and one of its windows before any capture or pointer input. Call `app.getAccessibilityTree()` to emit the tree. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. +Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` validates the ID against the current application window list and returns the object without reading AX. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Failed cleanup is reported before that connection is retired; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. @@ -87,7 +87,7 @@ The provider calls [installCua](src/index.ts) with its prepared helper, connecti [The operation schema](src/protocol.ts) is the authority for model parameters and separately declared Host-only fields. Native implementations enforce target identity, window geometry, resource limits, and operating-system access at execution. The permission store owns durable consent separately from the native protocol. -One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and derives `CuaApp` and `CuaWindow` from it. The derived factories inject scope parameters and the accessibility and keyboard checks for their scope; the shared base does not branch on application-only capabilities. Within one API instance, the facade keeps one current accessibility snapshot per `appHandle` across every app and window object for that handle. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. Each later `getAccessibilityTree()` invalidates the previous snapshot before dispatch, and element operations use the latest snapshot ID. Only a `CuaWindow` captures screenshots or sends pointer input. +One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and derives `CuaApp` and `CuaWindow` from it. The derived factories inject scope parameters and the accessibility and keyboard checks for their scope; the shared base does not branch on application-only capabilities. Within one API instance, the facade keeps one current accessibility snapshot per `appHandle` across every app and window object for that handle. Selection leaves the current accessibility snapshot unchanged. Each explicit `getAccessibilityTree()` invalidates the previous snapshot before dispatch, and element operations use the latest snapshot ID. Only a `CuaWindow` captures screenshots or sends pointer input. Provider startup capabilities are fixed at installation: platform, methods, app-level accessibility, keyboard scopes, browser support, and coordinate space. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges both layers for the model-visible result. The raw RPC remains a common operation representation rather than a capability inventory, so provider guidance states the actions its platform supports. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c1c5ed863c..b79cc6fdb5 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以在 macOS 上启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,并在 provider 支持应用级辅助功能时静默读取初始辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 返回用于截图和指针输入的对象。进行任何截图或指针输入前,必须选择应用及其一个窗口。调用 `app.getAccessibilityTree()` 输出树。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 +使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 根据当前应用窗口清单验证 ID,然后返回对象,不读取 AX。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会先报告,再释放该连接;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 @@ -87,7 +87,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 [操作 schema](src/protocol.ts) 定义模型参数,并单独声明 Host 专用字段。原生实现在执行时检查目标身份、窗口几何、资源上限和操作系统访问条件。授权存储独立于原生协议保存持久许可。 -对象门面([src/api.ts](src/api.ts))构建共享的 `CuaSurface`,并从它派生 `CuaApp` 和 `CuaWindow`。派生工厂注入作用域参数以及该作用域的辅助功能和键盘检查;共享基类不为仅属于应用的能力分支。在单个 API 实例内,门面按 `appHandle` 保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它。`getWindow` 静默读取初始树;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后每次 `getAccessibilityTree()` 在分派前使上一份快照失效,元素操作使用最新快照 ID。只有 `CuaWindow` 可以截图或发送指针输入。 +对象门面([src/api.ts](src/api.ts))构建共享的 `CuaSurface`,并从它派生 `CuaApp` 和 `CuaWindow`。派生工厂注入作用域参数以及该作用域的辅助功能和键盘检查;共享基类不为仅属于应用的能力分支。在单个 API 实例内,门面按 `appHandle` 保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它。选择对象不改变当前辅助功能快照。每次显式调用 `getAccessibilityTree()` 在分派前使上一份快照失效,元素操作使用最新快照 ID。只有 `CuaWindow` 可以截图或发送指针输入。 提供方启动能力在安装时固定:平台、方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。原生 RPC 仍是通用操作表示,而不是能力清单,因此 provider 指引说明其平台支持的动作。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..0d62908a8a 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -107,7 +107,8 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-computer-use": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 22039c6591..509b9b8676 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -1,5 +1,6 @@ /** Object facade over logged native operations; its caller owns evaluator persistence. */ import { Buffer } from 'node:buffer' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' @@ -79,9 +80,7 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): if (!request.success) throw new Error(`getApp ${requestIssueMessage(request.error.issues)}`) const capabilities = await currentCapabilities() const { appHandle } = AppResult.parse(await call('getApp', { selector })) - const app = objects.createCuaApp(appHandle, capabilities) - if (capabilities.appLevelAccessibility) await app.getAccessibilityTree({ emit: false }) - return app + return objects.createCuaApp(appHandle, capabilities) }, } return api @@ -259,9 +258,13 @@ function createCuaObjects(call: ReturnType, sink: CuaObser return windows }, async getWindow(windowId): Promise { - const window = createCuaWindow(appHandle, windowId, capabilities) - await window.getAccessibilityTree({ emit: false }) - return window + const parsed = WindowsResult.element.shape.windowId.safeParse(windowId) + if (!parsed.success) throw new HarnessError(`getWindow ${requestIssueMessage(parsed.error.issues, ['params', 'windowId'])}`, 'INVALID_ARGS') + const windows = WindowsResult.parse(await base.call('listWindows', {})) + if (!windows.some(window => window.windowId === windowId)) { + throw new HarnessError('Selected window is unavailable for this application; read getWindows again', 'CUA_WINDOW_UNAVAILABLE') + } + return createCuaWindow(appHandle, windowId, capabilities) }, } } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 745ccfe9be..89a32bd21a 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -11,9 +11,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -21,7 +21,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -45,4 +45,4 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b84663f9e2..0e8624b6ea 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -238,9 +238,9 @@ export interface CuaApp extends CuaSurface { */ getWindows(options?: CuaObservationOptions): Promise /** - * Observe a specific window. + * Select a specific window. * @param windowId - ID obtained from getWindows. - * @returns A window object with its initial accessibility tree read silently; this updates the application's current snapshot. + * @returns A window object from the app’s current window list, without reading or replacing its accessibility snapshot. */ getWindow(windowId: number): Promise } @@ -272,9 +272,9 @@ export interface CuaApi { */ getState(options?: CuaObservationOptions): Promise<{ apps: CuaAppInfo[]; browsers: [] }> /** - * Select an app, obtain consent, launch it in the background if necessary, and silently retain initial AX state. + * Select an app, obtain consent, and launch it in the background if necessary, without reading AX. * @param selector - Exact name, bundle ID, absolute application path or running PID string; ambiguous names reject. - * @returns An application handle tied to this process lifetime; its initial tree read becomes the current snapshot. + * @returns An application handle tied to this process lifetime; call getAccessibilityTree explicitly before element operations. */ getApp(selector: string): Promise } diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index cbaa419951..fb2bf5a204 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -83,7 +83,7 @@ describe('application discovery', () => { const window = await app.getWindow(23) expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual([ - 'getCapabilities', 'listApps', 'getApp', 'getState', 'getState', 'screenshot', + 'getCapabilities', 'listApps', 'getApp', 'listWindows', 'screenshot', ]) expect(await app.getWindows()).toEqual([windowInfo(23)]) expect(f.sink.text).not.toHaveBeenCalled() @@ -124,8 +124,11 @@ describe('application discovery', () => { describe('background window restoration', () => { it('shows an app or selected window without dispatching activation or AXRaise', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(24) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.show()).toEqual({ ...delivered, windowId: 23, foregroundChanged: false }) expect(await window.show()).toEqual({ ...delivered, windowId: 24, foregroundChanged: false }) @@ -138,6 +141,7 @@ describe('background window restoration', () => { it.each([true, null])('preserves foreground change evidence %j without switching focus back', async (foregroundChanged) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce({ ...delivered, windowId: null, foregroundChanged }) expect(await app.show()).toEqual({ ...delivered, windowId: null, foregroundChanged }) @@ -147,6 +151,7 @@ describe('background window restoration', () => { it('leaves foreground fallback to the caller after restoration fails', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockRejectedValueOnce(new Error('UNSUPPORTED: Window cannot be restored')) await expect(app.show()).rejects.toThrow('UNSUPPORTED') @@ -157,8 +162,11 @@ describe('background window restoration', () => { describe('mouseMove across observations', () => { it('moves to an AX element then into a popup without inserting clicks or restoring a point', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await window.mouseMove(element('0'))).toEqual({ ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false }) await window.getAccessibilityTree({ emit: false }) @@ -171,13 +179,14 @@ describe('mouseMove across observations', () => { { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', windowId: 23, x: 30, y: 40 } }, ]) const other = await app.getWindow(24) + await other.getAccessibilityTree({ emit: false }) await other.mouseMove([5, 6]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-4', windowId: 24, x: 5, y: 6, } }) f.dispatch.mockRejectedValueOnce(new Error('WINDOW_CHANGED')) await expect(other.mouseMove([5, 6])).rejects.toThrow('WINDOW_CHANGED') - expect(f.dispatch).toHaveBeenCalledTimes(7) + expect(f.dispatch).toHaveBeenCalledTimes(8) }) }) @@ -185,7 +194,9 @@ describe('pointer buttons and modifiers', () => { it.each([0, 800])('preserves %d ms for window clicks at elements and coordinates', async (holdMs) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) for (const target of [element('0'), [10, 20] as const]) { await window.click(target, { holdMs, mouseButton: 'right' }) expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ method: 'click', params: { holdMs, mouseButton: 'right' } }) @@ -198,7 +209,9 @@ describe('pointer buttons and modifiers', () => { it('retains middle-button and modifier intent through click and drag dispatch', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('0'), { mouseButton: 'middle', modifiers: ['shift'] }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: 23, mouseButton: 'middle', modifiers: ['shift'], @@ -223,6 +236,7 @@ describe('text selections', () => { it('binds literal text and optional disambiguation to the latest observed control', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) await app.selectText(element('1'), 'target') expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'selectText', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '1', text: 'target', @@ -242,6 +256,7 @@ describe('element action queries', () => { it('returns raw provider action names including attribute-setting operations without reading new state', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.listActions(element('42.12345'))).toEqual(['AXPress', 'AXShowMenu', 'AXTextArea.AXValue.Set']) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ @@ -257,6 +272,7 @@ describe('element actions', () => { it('dispatches advertised actions with omitted, null or direct values without wrapping the value', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.performAction(element('42.12345'), 'AXPress')).toEqual(delivered) expect(await app.performAction(element('42.12345'), 'AXPress', null)).toEqual(delivered) @@ -274,6 +290,7 @@ describe('element actions', () => { it('rejects an empty action before dispatch', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(app.performAction(element('0'), '')).rejects.toThrow('performAction action') expect(f.dispatch).not.toHaveBeenCalled() @@ -284,6 +301,7 @@ describe('element default invocation', () => { it('uses the latest snapshot and opaque element id without reading fresh state', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.invoke(element('42.12345'))).toEqual(delivered) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ @@ -295,6 +313,7 @@ describe('element default invocation', () => { it('returns confirmed absence of a default action as un-dispatched evidence', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce({ dispatched: false }) await expect(app.invoke(element('9'))).resolves.toEqual({ dispatched: false }) }) @@ -302,6 +321,7 @@ describe('element default invocation', () => { it('rejects provider failures and malformed dispatch evidence', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const failure = new Error('PERMISSION_DENIED') f.dispatch.mockRejectedValueOnce(failure) await expect(app.invoke(element('0'))).rejects.toBe(failure) @@ -316,9 +336,12 @@ describe('application and window observations', () => { const f = fixture() f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(await app.getWindows({ emit: false })).toEqual([windowInfo(23), windowInfo(24)]) const first = await app.getWindow(23) + await first.getAccessibilityTree({ emit: false }) const second = await app.getWindow(24) + await second.getAccessibilityTree({ emit: false }) await app.setValue(element('1'), 'First document') await first.click(element('2')) await second.click(element('3')) @@ -342,9 +365,11 @@ describe('application and window observations', () => { it('keeps separate snapshots for different application handles', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce({ appHandle: 'app-18', name: 'Utility', running: true }) f.dispatch.mockResolvedValueOnce(state({ appHandle: 'app-18', snapshotId: 'other', windows: [] })) const other = await f.api.getApp('Utility') + await other.getAccessibilityTree({ emit: false }) await app.setValue(element('0'), 'Editor') await other.setValue(element('0'), 'Utility') expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -356,7 +381,15 @@ describe('application and window observations', () => { it('shares one current snapshot between repeated handles for the same application', async () => { const f = fixture() const first = await f.api.getApp('Editor') + await first.getAccessibilityTree({ emit: false }) const second = await f.api.getApp('Editor') + const window = await second.getWindow(23) + await window.getScreenshot({ emit: false }) + await first.setValue(element('1'), 'Preserved') + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'setValue', params: { + appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '1', value: 'Preserved', + } }) + await second.getAccessibilityTree({ emit: false }) expect(second.appHandle).toBe(first.appHandle) await first.setValue(element('1'), 'Shared') expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'setValue', params: { @@ -367,9 +400,11 @@ describe('application and window observations', () => { it('exposes screenshots and pointer input only on explicit windows', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(app).toHaveProperty('getAccessibilityTree') for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(app).not.toHaveProperty(method) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(window).toHaveProperty(method) expect(window).not.toHaveProperty('hover') expect(window).toHaveProperty('mouseMove') @@ -377,13 +412,17 @@ describe('application and window observations', () => { it('attaches the shared snapshot to coordinates only within its window scope', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const first = await app.getWindow(23) + await first.getAccessibilityTree({ emit: false }) await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) const second = await app.getWindow(24) + await second.getAccessibilityTree({ emit: false }) await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 23, x: 10, y: 20, mouseButton: 'left', clickCount: 1, @@ -398,8 +437,10 @@ describe('application and window observations', () => { it('keeps a validated AXless window usable for screenshots and coordinate input', async () => { const f = fixture() const app = await f.api.getApp('Editor') - f.dispatch.mockResolvedValueOnce(state({ windowId: 23, snapshotId: 'axless', tree: '', elements: [] })) + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + f.dispatch.mockResolvedValueOnce(state({ windowId: 23, snapshotId: 'axless', tree: '', elements: [] })) + await window.getAccessibilityTree({ emit: false }) expect(f.sink.text).not.toHaveBeenCalled() await expect(window.getScreenshot()).resolves.toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) await window.click([10, 20]) @@ -414,11 +455,12 @@ describe('application and window observations', () => { it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s while selecting a window without attempting image or input fallback', async (code) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const failure = new Error(code) f.dispatch.mockRejectedValueOnce(failure) const calls = f.dispatch.mock.calls.length await expect(app.getWindow(23)).rejects.toBe(failure) - expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['getState']) + expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['listWindows']) }) it('captures and clicks the explicitly selected window among several', async () => { @@ -431,8 +473,10 @@ describe('application and window observations', () => { ] f.setWindowRecords(windows) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(await app.getWindows({ emit: false })).toEqual(windows) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.getScreenshot() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) await window.click([10, 20]) @@ -440,6 +484,7 @@ describe('application and window observations', () => { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) const hidden = await app.getWindow(25) + await hidden.getAccessibilityTree({ emit: false }) await hidden.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 25, snapshotId: 'snapshot-3', x: 10, y: 20, mouseButton: 'left', clickCount: 1, @@ -471,6 +516,7 @@ describe('application and window observations', () => { it('returns provider window records without process filtering', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const observed = windowInfo(24) f.dispatch.mockResolvedValueOnce(state({ windows: [observed] })) await expect(app.getAccessibilityTree()).resolves.toBe('Changed tree') @@ -496,11 +542,11 @@ describe('application and window observations', () => { { method: 'typeText', params: { appHandle: 'app-17', text: 'keyboard without accessibility' } }, ]) const window = await app.getWindow(23) - await expect(window.getAccessibilityTree({ emit: false })).resolves.toBe('Tree 2') + await expect(window.getAccessibilityTree({ emit: false })).resolves.toBe('Tree 1') await expect(app.getAccessibilityTree()).rejects.toThrow('Application-level accessibility is not supported on current platform; observe a window instead.') await expect(window.invoke(element('0'))).resolves.toEqual(delivered) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'invoke', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', elementId: '0', + appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-1', elementId: '0', } }) }) @@ -508,7 +554,9 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await window.typeText('hello') await window.paste('bold', { format: 'html' }) @@ -530,7 +578,9 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(app.typeText('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') await expect(app.paste('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') @@ -544,7 +594,9 @@ describe('application and window observations', () => { it('accepts coordinate input without a current snapshot', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockRejectedValueOnce(new Error('Native app is busy')) await expect(window.getAccessibilityTree()).rejects.toThrow('Native app is busy') await window.click([10, 20]) @@ -556,7 +608,9 @@ describe('application and window observations', () => { it('clears a failed refresh and requires a new read before element operations', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const failure = new Error('Native app is busy') f.dispatch.mockRejectedValueOnce(failure) await expect(app.getAccessibilityTree()).rejects.toBe(failure) @@ -575,11 +629,54 @@ describe('application and window observations', () => { }) describe('screenshots', () => { + it('rejects a missing or foreign window without reading AX or taking a screenshot', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + await expect(app.getWindow(24)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) + f.setWindows([]) + await expect(app.getWindow(23)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) + expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'listWindows']) + await expect(app.getWindow(0)).rejects.toMatchObject({ name: 'HarnessError', code: 'INVALID_ARGS', message: 'getWindow windowId: Too small: expected number to be >0' }) + expect(f.dispatch).toHaveBeenCalledTimes(4) + }) + + it.each(['APP_ACCESS_REVOKED', 'WINDOW_UNAVAILABLE', 'STALE_APP'])('preserves %s when capturing a previously selected window', async (code) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow(23) + f.dispatch.mockRejectedValueOnce(new Error(code)) + await expect(window.getScreenshot()).rejects.toThrow(code) + expect(f.sink.image).not.toHaveBeenCalled() + }) + + it.each(['application', 'window'])('captures the first screenshot when %s AX reads fail', async (scope) => { + const f = fixture() + const dispatch = f.dispatch.getMockImplementation()! + const failure = new Error('AX read failed') + f.dispatch.mockImplementation(async (request) => { + if (request.method === 'getState' && (scope === 'application' ? request.params.windowId === undefined : request.params.windowId !== undefined)) throw failure + return dispatch(request) + }) + const app = await f.api.getApp('Editor') + expect(await app.getWindows({ emit: false })).toEqual([windowInfo(23)]) + const window = await app.getWindow(23) + const target = scope === 'application' ? app : window + await expect(target.getAccessibilityTree()).rejects.toBe(failure) + await expect(window.getScreenshot()).resolves.toMatchObject({ windowId: 23, pixelWidth: 1 }) + await expect(window.invoke(element('0'))).rejects.toThrow('Read getAccessibilityTree') + await window.click([0, 0]) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', windowId: 23, x: 0, y: 0, mouseButton: 'left', clickCount: 1, + } }) + }) + it('returns screenshot metadata independently of input point bounds and supports selective output', async () => { const f = fixture() f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(24) + await window.getAccessibilityTree({ emit: false }) f.sink.text.mockClear() const tree = await window.getAccessibilityTree() const image = await window.getScreenshot() @@ -597,7 +694,9 @@ describe('screenshots', () => { it('rejects a screenshot from another window before emitting its image', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce(screenshot({ windowId: 24 })) await expect(window.getScreenshot()).rejects.toThrow('belongs to another window') expect(f.sink.image).not.toHaveBeenCalled() @@ -606,7 +705,9 @@ describe('screenshots', () => { it.each(['image/jpeg', 'image/webp', 'image/gif'])('preserves Host-admitted %s bytes and metadata in the return value and image sink', async (mimeType) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const data = Buffer.from('admitted request image').toString('base64') f.dispatch.mockResolvedValueOnce(screenshot({ mimeType, data, pixelWidth: 320, pixelHeight: 240 })) const image = await window.getScreenshot() @@ -620,7 +721,9 @@ describe('input actions', () => { it('passes explicit relative mode to every coordinate gesture and rejects it on element ids', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click([500, 250], { relative: true }) await window.mouseMove([500, 250], { relative: true }) await window.drag([0, 0], [999, 999], { relative: true }) @@ -638,7 +741,9 @@ describe('input actions', () => { it('keeps the selected window when scroll options include another target identity', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const options = { x: 10, y: 20, deltaLinesX: 0, deltaLinesY: 1, appHandle: 'another-app', snapshotId: 'another-snapshot', windowId: 24, @@ -654,7 +759,9 @@ describe('input actions', () => { it('dispatches window-point gestures and reports delivery without claiming the action succeeded', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) expect(await window.click([10, 20], { mouseButton: 'right' })).toEqual(delivered) expect(await window.click([11, 21], { clickCount: 2 })).toEqual(delivered) expect(await window.scroll({ x: 10, y: 20, deltaLinesX: -2, deltaLinesY: 3 })).toEqual(delivered) @@ -685,7 +792,6 @@ describe('input actions', () => { ['empty key', ({ app }) => app.pressKey('')], ] it.each<[string, (surfaces: Surfaces) => Promise]>([ - ['getState windowId: Too small: expected number to be >0', ({ app }) => app.getWindow(0)], ['selectText text: Too small: expected string to have >=1 characters', ({ app }) => app.selectText(element('0'), '')], ['mouseMove x: Invalid input: expected number, received NaN', ({ window }) => window.mouseMove([NaN, 0])], ['mouseMove x: Too big: expected number to be <=999', ({ window }) => window.mouseMove([1000, 0], { relative: true })], @@ -693,7 +799,9 @@ describe('input actions', () => { ])('reports a readable validation failure: %s', async (message, run) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(run({ app, window })).rejects.toMatchObject({ name: 'Error', message }) expect(f.dispatch).not.toHaveBeenCalled() @@ -702,7 +810,9 @@ describe('input actions', () => { it.each(invalidActions)('rejects %s without invoking native input', async (_label, run) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const calls = f.dispatch.mock.calls.length await expect(run({ app, window })).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) @@ -716,6 +826,7 @@ describe('input actions', () => { ])('forwards literal key %s with modifiers %j without splitting', async (key, modifiers, expected) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) if (modifiers === undefined) await app.pressKey(key) else await app.pressKey(key, modifiers) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'pressKey', params: { appHandle: 'app-17', key, modifiers: expected } }) @@ -724,6 +835,7 @@ describe('input actions', () => { it('forwards the literal key unsplit in one RPC without mutating modifiers', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const modifiers: string[] = ['control', 'shift'] f.dispatch.mockClear() await app.pressKey('+', modifiers) @@ -737,6 +849,7 @@ describe('input actions', () => { it('forwards arbitrary provider-defined key and modifier names in one RPC', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await app.pressKey('PlatformKey', ['platform-modifier']) expect(f.dispatch).toHaveBeenCalledTimes(1) @@ -748,6 +861,7 @@ describe('input actions', () => { it('passes literal text and keys to the selected app identity', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) await app.typeText('中文\nline two') await app.paste('粘贴\nplain text') await app.paste('bold', { format: 'html' }) @@ -765,7 +879,9 @@ describe('input actions', () => { it('rejects keyboard input on a window surface without dispatching an app-level fallback', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() for (const run of [ () => window.typeText('hello'), @@ -787,6 +903,7 @@ describe('input actions', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const surface = scope === 'window' ? await app.getWindow(23) : app f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce(delivered) @@ -800,6 +917,7 @@ describe('input actions', () => { it('returns an un-dispatched key-event result from one RPC without retrying', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce({ dispatched: false }) await expect(app.sendKeyEvent('Command', 'down')).resolves.toEqual({ dispatched: false }) @@ -829,7 +947,9 @@ describe('input actions', () => { it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('12'), { mouseButton: 'right' }) await window.click(element('13'), { clickCount: 2 }) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -841,7 +961,9 @@ describe('input actions', () => { it('dispatches an opaque provider element id unchanged', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('42.12345')) await window.mouseMove(element('42.12345')) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -853,7 +975,7 @@ describe('input actions', () => { it('does not activate on selection and dispatches only an explicit activation request', async () => { const f = fixture() const app = await f.api.getApp('Editor') - expect(f.dispatch.mock.calls.map(([call]) => call.method)).toEqual(['getCapabilities', 'getApp', 'getState']) + expect(f.dispatch.mock.calls.map(([call]) => call.method)).toEqual(['getCapabilities', 'getApp']) await app.activate() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'activate', params: { appHandle: 'app-17' } }) }) @@ -861,14 +983,16 @@ describe('input actions', () => { it('propagates native failures once and rejects malformed delivery claims', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const failure = new Error('Application was restarted; select it again') f.dispatch.mockRejectedValueOnce(failure) await expect(app.typeText('hello')).rejects.toBe(failure) - expect(f.dispatch).toHaveBeenCalledTimes(5) + expect(f.dispatch).toHaveBeenCalledTimes(6) f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) await expect(window.click(element('0'))).rejects.toThrow() - expect(f.dispatch).toHaveBeenCalledTimes(6) + expect(f.dispatch).toHaveBeenCalledTimes(7) }) it('rejects invalid selection inputs before dispatch', async () => { @@ -876,6 +1000,7 @@ describe('input actions', () => { await expect(f.api.getApp('')).rejects.toThrow() expect(f.dispatch).not.toHaveBeenCalled() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const calls = f.dispatch.mock.calls.length await expect(app.getWindow(0)).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 14a36baaba..7bba3c4e0b 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -27,6 +27,7 @@ it('uses the current tool binding when a retained app is called by another execu const first = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected + if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return snapshot }) @@ -35,6 +36,7 @@ it('uses the current tool binding when a retained app is called by another execu const cua = connectCua(() => current, text) const app = await cua.getApp('Editor') const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const second = vi.fn(async (): Promise => ({ dispatched: true })) current = second @@ -69,6 +71,7 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n const tool = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected + if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', @@ -80,6 +83,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n text.mockClear() expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) - expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'getState', 'getState', 'screenshot']) + expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'screenshot']) expect(text).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..4bf0b7ddda 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -74,6 +74,9 @@ }, { "path": "../../boot/config-editor" + }, + { + "path": "../../util/error" } ], "exclude": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d016fe8deb..83d9bd763d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9800,6 +9800,9 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 0b9c1b29f6..04fb520f49 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -46,9 +46,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -56,7 +56,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -80,6 +80,6 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 1e148d7ab5..c39f62f769 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -162,6 +162,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (method === 'listWindows') return [window, axlessWindow] if (method === 'getState') { snapshots.delete(params.windowId ?? null) + if (existsSync(new URL('./fixture-ax-failure', import.meta.url))) refuse('NATIVE_ERROR', 'Fixture accessibility read failed') if (observationChanged) { observationChanged = false refuse('STALE_SNAPSHOT', 'Accessibility tree changed during observation; read fresh getAccessibilityTree') diff --git a/snapshots/session/cua-ptc/consent-fixture.mjs b/snapshots/session/cua-ptc/consent-fixture.mjs index 85e83bcf69..6fdbdbbfc2 100644 --- a/snapshots/session/cua-ptc/consent-fixture.mjs +++ b/snapshots/session/cua-ptc/consent-fixture.mjs @@ -1,5 +1,5 @@ /** Own a private native substitute for the PTC result replay. */ -import { chmod, copyFile, unlink } from 'node:fs/promises' +import { chmod, copyFile, unlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { startFixtureHost } from '../cua-native/fixture-host.mjs' export const name = 'cua-ptc-fixture' @@ -7,6 +7,10 @@ export const inject = ['userQuestions'] /** Prepare the helper and retire its service before removing the private executable. */ export async function apply(ctx) { + const bridge = join(process.cwd(), 'cua-bridge.mjs') + const face = process.env.DSH_EXAMPLE_MODE === 'src' ? 'src/bridge.ts' : 'lib/bridge.js' + await writeFile(bridge, `export { connectCua } from ${JSON.stringify(new URL('../../../packages/experimental/cua/' + face, import.meta.url).href)}\n`) + ctx.effect(() => () => unlink(bridge)) const helper = join(process.cwd(), 'native-helper.mjs') await copyFile(new URL('../cua-native/workspace/native-helper.mjs', import.meta.url), helper) await chmod(helper, 0o700) diff --git a/snapshots/session/cua-ptc/replay.override.json b/snapshots/session/cua-ptc/replay.override.json index 63e4009990..5ea62fee03 100644 --- a/snapshots/session/cua-ptc/replay.override.json +++ b/snapshots/session/cua-ptc/replay.override.json @@ -32,6 +32,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-ptc-ax-failure", + "name": "run_code", + "arguments": "{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -45,7 +78,7 @@ "index": 0, "block": { "type": "text", - "text": "Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a." + "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot." } }, { diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 87791413b2..f9d25d914b 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791864698727,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791864698727,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1791864698727,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791864698727,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024973829,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024973829,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -26,6 +26,28 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791864699463,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1791864699463,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a."}}},{"type":"chunk","time":1791864699463,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791864699463,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974646,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024974646,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-ax-failure"},"toolCallId":"cua-ptc-ax-failure","content":[{"type":"text","text":"{\n \"axFailures\": 2,\n \"screenshotWindow\": 7,\n \"pngBytes\": 90,\n \"elementRefused\": true\n}"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[28],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"}]}} {"type":"step/end","data":{"turn":1,"step":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":3}} +{"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974851,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794024974851,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 587436227a..be8ab5aed8 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -48,9 +48,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -58,7 +58,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index dd88fa8d9e..63e91315c0 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -48,9 +48,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -58,7 +58,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. From f2dc7347adbcb37322265e727ce09b134018b3fd Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:29:31 +0800 Subject: [PATCH 02/15] fix(cua): share HarnessError through a peer dependency --- packages/experimental/cua/package.json | 9 +++++---- pnpm-lock.yaml | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 0d62908a8a..410dd23cf7 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -99,7 +99,8 @@ "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*" + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", @@ -107,8 +108,7 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-computer-use": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", @@ -162,7 +162,8 @@ "@deepseek-ai/dsh-storage-json": "workspace:*", "@deepseek-ai/dsh-client-ui-user-questions": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*" + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dsh": { "client": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 83d9bd763d..f33fef7d42 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9800,9 +9800,6 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use - '@deepseek-ai/dsh-error': - specifier: workspace:* - version: link:../../util/error '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain @@ -9897,6 +9894,9 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local From 67561b163eebf322d39f6f87c27eac93b4ebaf39 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:35:17 +0800 Subject: [PATCH 03/15] docs(cua): regenerate shared dependency graph --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index a3a28f92fc..cc0d1e4f2c 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -952,6 +952,7 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1821,7 +1822,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9e337229b4..c9cf1d8d93 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -954,6 +954,7 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1823,7 +1824,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | From facebeb270d44d5d20143e850c7605b09b23ab29 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 14:12:45 +0800 Subject: [PATCH 04/15] fix(cua): let native window operations own window validation getWindow now creates the window object without a listWindows request. Screenshots and pointer input already reject closed and foreign windows natively, so the facade keeps only local windowId validation and drops the dsh-error dependency and CUA_WINDOW_UNAVAILABLE code. --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 4 +-- ...026-11-05-cua-scoped-surfaces-and-input.md | 2 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 2 +- docs/module-graph.md | 3 +-- docs/module-graph.zh.md | 3 +-- .../experimental/cua-macos/README.i18n.yaml | 4 +-- packages/experimental/cua-macos/README.md | 6 ++--- packages/experimental/cua-macos/README.zh.md | 6 ++--- packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/package.json | 6 ++--- packages/experimental/cua/src/api.ts | 14 ++++------ packages/experimental/cua/src/guidance.ts | 4 +-- packages/experimental/cua/src/types.ts | 3 ++- packages/experimental/cua/tests/api.spec.ts | 27 +++++++++---------- .../experimental/cua/tests/bridge.spec.ts | 6 ++--- packages/experimental/cua/tsconfig.host.json | 3 --- pnpm-lock.yaml | 3 --- .../cua-native/system-prompt.expected.md | 4 +-- snapshots/session/cua-ptc/session.v4.jsonl | 20 +++++++------- .../session/cua-ptc/system-prompt.expected.md | 4 +-- .../system-prompt.expected.md | 4 +-- 23 files changed, 58 insertions(+), 78 deletions(-) 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 5f1ff64a4d..53d7ee394c 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: 4fa61247fe33edb0 - zh: afa76f74841eb586 + 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 3888527013..23780d7e88 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. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; `getWindow` validates membership in the application’s current window list. 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. +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 8a3f152e67..f65ec242cb 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 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;`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)负责连接生命期。 +在单个 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/docs/module-graph.md b/docs/module-graph.md index cc0d1e4f2c..a3a28f92fc 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -952,7 +952,6 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment - pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1822,7 +1821,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index c9cf1d8d93..9e337229b4 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -954,7 +954,6 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment - pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1824,7 +1823,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 7571c8004d..6ddbd9a57f 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: e9c78a8cbd68147c zh: 98c64b09f858edf7 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 7c460511bb1cee4c - zh: 2eba4fc997427e18 + en: 3cd638c0c59fd9cc + zh: 594bacf314d4cd08 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d139d988a3..2e57fbaf13 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -113,7 +113,7 @@ void await window.getScreenshot() Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` return without reading AX; choose the window from `getWindows()` by its title and bounds. -`getWindow` validates the ID against the current application window list. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` sends no native request; screenshots and pointer input reject a closed or foreign window. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. `mouseMove(target)` defaults to AX hover. An enabled target or ancestor must advertise both `AXShowAlternateUI` and `AXShowDefaultUI`. Moving into its descendants keeps the UI open, and leaving restores it. Without an AX route the helper returns `HOVER_UNAVAILABLE` before sending input. Click a visible control or use `performAction` with an advertised action. For browser content without these AX actions, use browser tools. Enable `systemPointerHover` only when moving the user’s visible cursor is acceptable. That route requires a foreground, unobscured target and leaves the cursor at the destination. @@ -191,7 +191,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f8fed7b624..4a6be7b8ef 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -113,7 +113,7 @@ void await window.getScreenshot() 使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 返回时不读取 AX;根据 `getWindows()` 中的标题与位置选择窗口。 -`getWindow` 根据当前应用窗口清单验证 ID。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 不发送原生请求;截图和指针输入会拒绝已关闭或属于其他应用的窗口。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `mouseMove(target)` 默认通过 AX 悬停。目标或其祖先必须已启用,并同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`。进入子控件会保持展开,离开后恢复默认界面。如果没有可用的 AX 路径,helper 返回 `HOVER_UNAVAILABLE`,不发送输入。可点击已经可见的控件,或用 `performAction` 执行控件声明的动作。浏览器内容缺少这些 AX 动作时,请使用浏览器工具。只有允许移动用户可见光标时才开启 `systemPointerHover`。这条路径要求目标在前台且未被遮挡,操作后光标停在目标位置。 @@ -191,7 +191,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token 影响 diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index fffdfaa5c6..dee3c61085 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: 77dbaaa91d5b92c8 - zh: 94c3a758a91476bd + en: 01344bd3eba672cd + zh: e26f37a224899a46 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 0b3d39fdd1..dd262aede7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -31,7 +31,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations on macOS. External PTC hosts import `connectCua` from `@deepseek-ai/dsh-cua/bridge` and supply the current `tools.cua` binding. Source compositions and native preparation belong to the provider. -Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` validates the ID against the current application window list and returns the object without reading AX. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. +Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` returns the object without a native request; window operations reject closed or foreign windows. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Failed cleanup is reported before that connection is retired; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index b79cc6fdb5..ee274413ef 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以在 macOS 上启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 根据当前应用窗口清单验证 ID,然后返回对象,不读取 AX。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 +使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 返回对象时不发送原生请求;窗口操作会拒绝已关闭或属于其他应用的窗口。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会先报告,再释放该连接;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 410dd23cf7..440f321935 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -99,8 +99,7 @@ "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", @@ -162,8 +161,7 @@ "@deepseek-ai/dsh-storage-json": "workspace:*", "@deepseek-ai/dsh-client-ui-user-questions": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*" }, "dsh": { "client": { diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 509b9b8676..b28d4e9f1c 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -1,6 +1,5 @@ /** Object facade over logged native operations; its caller owns evaluator persistence. */ import { Buffer } from 'node:buffer' -import { HarnessError } from '@deepseek-ai/dsh-error' import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' @@ -257,14 +256,11 @@ function createCuaObjects(call: ReturnType, sink: CuaObser await emit(sink, windows, options) return windows }, - async getWindow(windowId): Promise { - const parsed = WindowsResult.element.shape.windowId.safeParse(windowId) - if (!parsed.success) throw new HarnessError(`getWindow ${requestIssueMessage(parsed.error.issues, ['params', 'windowId'])}`, 'INVALID_ARGS') - const windows = WindowsResult.parse(await base.call('listWindows', {})) - if (!windows.some(window => window.windowId === windowId)) { - throw new HarnessError('Selected window is unavailable for this application; read getWindows again', 'CUA_WINDOW_UNAVAILABLE') - } - return createCuaWindow(appHandle, windowId, capabilities) + getWindow(windowId): Promise { + // Native window operations reject closed and foreign windows; selection only admits the ID they accept. + const request = Request.safeParse({ method: 'screenshot', params: { appHandle, windowId } }) + if (!request.success) return Promise.reject(new Error(`getWindow ${requestIssueMessage(request.error.issues)}`)) + return Promise.resolve(createCuaWindow(appHandle, windowId, capabilities)) }, } } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 89a32bd21a..c1ede9f30b 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -13,7 +13,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -45,4 +45,4 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 0e8624b6ea..a9c4776acf 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -240,7 +240,8 @@ export interface CuaApp extends CuaSurface { /** * Select a specific window. * @param windowId - ID obtained from getWindows. - * @returns A window object from the app’s current window list, without reading or replacing its accessibility snapshot. + * @returns A window object without a native request; selection leaves the accessibility snapshot unchanged. + * Window operations reject a closed or foreign window. */ getWindow(windowId: number): Promise } diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index fb2bf5a204..2b023db37d 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -83,7 +83,7 @@ describe('application discovery', () => { const window = await app.getWindow(23) expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual([ - 'getCapabilities', 'listApps', 'getApp', 'listWindows', 'screenshot', + 'getCapabilities', 'listApps', 'getApp', 'screenshot', ]) expect(await app.getWindows()).toEqual([windowInfo(23)]) expect(f.sink.text).not.toHaveBeenCalled() @@ -186,7 +186,7 @@ describe('mouseMove across observations', () => { } }) f.dispatch.mockRejectedValueOnce(new Error('WINDOW_CHANGED')) await expect(other.mouseMove([5, 6])).rejects.toThrow('WINDOW_CHANGED') - expect(f.dispatch).toHaveBeenCalledTimes(8) + expect(f.dispatch).toHaveBeenCalledTimes(7) }) }) @@ -452,15 +452,15 @@ describe('application and window observations', () => { } }) - it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s while selecting a window without attempting image or input fallback', async (code) => { + it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s from coordinate input on a selected window without image or input fallback', async (code) => { const f = fixture() const app = await f.api.getApp('Editor') - await app.getAccessibilityTree({ emit: false }) + const window = await app.getWindow(23) const failure = new Error(code) f.dispatch.mockRejectedValueOnce(failure) const calls = f.dispatch.mock.calls.length - await expect(app.getWindow(23)).rejects.toBe(failure) - expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['listWindows']) + await expect(window.click([1, 2])).rejects.toBe(failure) + expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['click']) }) it('captures and clicks the explicitly selected window among several', async () => { @@ -629,15 +629,12 @@ describe('application and window observations', () => { }) describe('screenshots', () => { - it('rejects a missing or foreign window without reading AX or taking a screenshot', async () => { + it('selects windows without a native request and rejects invalid IDs locally', async () => { const f = fixture() const app = await f.api.getApp('Editor') - await expect(app.getWindow(24)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) - f.setWindows([]) - await expect(app.getWindow(23)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) - expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'listWindows']) - await expect(app.getWindow(0)).rejects.toMatchObject({ name: 'HarnessError', code: 'INVALID_ARGS', message: 'getWindow windowId: Too small: expected number to be >0' }) - expect(f.dispatch).toHaveBeenCalledTimes(4) + expect((await app.getWindow(24)).windowId).toBe(24) + await expect(app.getWindow(0)).rejects.toThrow('getWindow windowId: Too small: expected number to be >0') + expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp']) }) it.each(['APP_ACCESS_REVOKED', 'WINDOW_UNAVAILABLE', 'STALE_APP'])('preserves %s when capturing a previously selected window', async (code) => { @@ -989,10 +986,10 @@ describe('input actions', () => { const failure = new Error('Application was restarted; select it again') f.dispatch.mockRejectedValueOnce(failure) await expect(app.typeText('hello')).rejects.toBe(failure) - expect(f.dispatch).toHaveBeenCalledTimes(6) + expect(f.dispatch).toHaveBeenCalledTimes(5) f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) await expect(window.click(element('0'))).rejects.toThrow() - expect(f.dispatch).toHaveBeenCalledTimes(7) + expect(f.dispatch).toHaveBeenCalledTimes(6) }) it('rejects invalid selection inputs before dispatch', async () => { diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 7bba3c4e0b..be2edddb9f 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -27,7 +27,6 @@ it('uses the current tool binding when a retained app is called by another execu const first = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected - if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return snapshot }) @@ -41,7 +40,7 @@ it('uses the current tool binding when a retained app is called by another execu current = second await expect(window.click(element('0'))).resolves.toEqual({ dispatched: true }) - expect(first).toHaveBeenCalledTimes(4) + expect(first).toHaveBeenCalledTimes(3) expect(second).toHaveBeenCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '0', windowId: 23 } }) expect(text).not.toHaveBeenCalled() current = first @@ -71,7 +70,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n const tool = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected - if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', @@ -83,6 +81,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n text.mockClear() expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) - expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'screenshot']) + expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'screenshot']) expect(text).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 4bf0b7ddda..2386f83640 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -74,9 +74,6 @@ }, { "path": "../../boot/config-editor" - }, - { - "path": "../../util/error" } ], "exclude": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f33fef7d42..d016fe8deb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9894,9 +9894,6 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor - '@deepseek-ai/dsh-error': - specifier: workspace:* - version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 04fb520f49..e8dfa822c9 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -48,7 +48,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -80,6 +80,6 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index f9d25d914b..dd3c7c5ffa 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024973829,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024973829,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031895518,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794031895518,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794031895518,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031895518,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974646,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024974646,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031896364,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794031896364,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794031896364,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031896364,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -34,20 +34,18 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-ax-failure"},"toolCallId":"cua-ptc-ax-failure","content":[{"type":"text","text":"{\n \"axFailures\": 2,\n \"screenshotWindow\": 7,\n \"pngBytes\": 90,\n \"elementRefused\": true\n}"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[28],"surfaceOp":"append"} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"}]}} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974851,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794024974851,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031896552,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794031896552,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794031896552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031896552,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index be8ab5aed8..26186e4c92 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -50,7 +50,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 63e91315c0..e61732cc68 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -50,7 +50,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. From 9e802994cae8c181cf7b59b39257be7c7f6aece1 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 9 Nov 2026 16:47:12 +0800 Subject: [PATCH 05/15] fix(cua): preserve trees when writability discovery fails --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../native/Sources/CuaNative/AXAccess.swift | 11 ++++- .../native/tests/swift/AXFailureTests.swift | 45 +++++++++++++++++++ .../cua-native/workspace/native-helper.mjs | 7 ++- snapshots/session/cua-ptc/consent-fixture.mjs | 2 +- .../session/cua-ptc/replay.override.json | 35 ++++++++++++++- snapshots/session/cua-ptc/session.v4.jsonl | 23 ++++++++-- 9 files changed, 119 insertions(+), 12 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 335f01b093..9235ea51c3 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 8dd51156261bd414 - zh: 1e585b51193d891c + en: 98f739bfb1f2554b + zh: 4d4809f851df6b35 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: a08d37e868a0a860 zh: 5dc8a2cdd165cc7e diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index cdbc5dfc2e..bed625dc5a 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -91,7 +91,7 @@ Raw `getState` exposes validated state fields and the complete text for the requ AX observations show menu-bar entries by default. Use `app.getAccessibilityTree({ includeMenus: true })` to expand menu contents and `app.getAccessibilityTree({ details: true })` for identifiers, global-point bounds and complete action names. These options also apply to raw `getState`. Every read replaces the application's current snapshot; use element IDs from that read. Details do not bypass the configured node and depth limits. Truncation identifies the reached limit. -Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`. +Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. During tree observation, an AXValue or AXSelectedTextRange writability probe returning -25200 leaves that field unknown and preserves the remaining nodes. Actual writes remain strict; permission, communication and invalid-element errors still propagate. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`. Observations emit by default and also return their value. In persistent PTC, use `void await app.getAccessibilityTree()` for one emitted copy, or `emit:false` and one explicit print. Capturing a screenshot after an emitted tree can fail independently; retain the successful AX output. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 2dad1db12c..4367d116c3 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -91,7 +91,7 @@ CUA 工具在读取 AX、窗口标题、截图、激活和输入前检查应用 AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ includeMenus: true })` 展开菜单内容,使用 `app.getAccessibilityTree({ details: true })` 读取标识符、全局 point 坐标和完整动作名。原始 `getState` 也接受这两个选项。每次读取都会替换应用当前的快照;应使用该次读取返回的元素 ID。详情不会绕过配置的节点数和深度上限;截断提示会指明触发的上限。 -实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。 +实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。读树时,AXValue 或 AXSelectedTextRange 的可写性探测返回 -25200,会将该字段保留为未知并继续读取其他节点。实际写入仍严格校验;权限、通信和失效元素错误仍向上传播。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。 观察方法默认自动输出,同时返回结果。在 persistent PTC 中使用 `void await app.getAccessibilityTree()` 输出一次,或指定 `emit:false` 后自行打印一次。AX 输出后的截图可能单独失败,已成功取得的 AX 输出仍保留。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 3b39ab1f02..53333a0b14 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -208,6 +208,12 @@ final class AXAccess { guard error == .success else { throw failure(error, "read writability of \(name)") } return value } + /// Observation keeps unsupported writability unknown; mutation callers use strict writable checks. + static func observationWritability(role: String, probe: (String, Bool) throws -> Bool?) rethrows -> (value: Bool?, selection: Bool?) { + let value = AXTextNode.valueRoles.contains(role) ? try probe("AXValue", true) : nil + let selection = AXTextNode.textRoles.contains(role) ? try probe("AXSelectedTextRange", true) : nil + return (value, selection) + } func requireEnabled(_ element: AXUIElement) throws { if try boolean(element, "AXEnabled") == false { throw NativeFailure(code: "NATIVE_ERROR", message: "Accessibility element is disabled") } } @@ -586,10 +592,11 @@ final class AXAccess { let placeholder = try stringValue(observed("AXPlaceholderValue"), attribute: "AXPlaceholderValue") let description = try stringValue(observed("AXDescription"), attribute: "AXDescription") let actionNames = try self.actions(element) - let valueWritable = AXTextNode.valueRoles.contains(role) ? try writable(element, "AXValue") : nil + let writability = try Self.observationWritability(role: role) { try writable(element, $0, forDiscovery: $1) } + let valueWritable = writability.value let enabled = try booleanValue(observed("AXEnabled"), attribute: "AXEnabled") let selected = try booleanValue(observed("AXSelected"), attribute: "AXSelected") - let selectionWritable = AXTextNode.textRoles.contains(role) ? try writable(element, "AXSelectedTextRange") : nil + let selectionWritable = writability.selection let selectedRange = AXTextNode.textRoles.contains(role) ? try textRange(observed("AXSelectedTextRange")) : nil let selectedText = AXTextNode.textRoles.contains(role) ? try stringValue(observed("AXSelectedText"), attribute: "AXSelectedText") : nil let identifier = try stringValue(observed("AXIdentifier"), attribute: "AXIdentifier") diff --git a/packages/experimental/cua-macos/native/tests/swift/AXFailureTests.swift b/packages/experimental/cua-macos/native/tests/swift/AXFailureTests.swift index 2c25c943e4..5ededcff6e 100644 --- a/packages/experimental/cua-macos/native/tests/swift/AXFailureTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/AXFailureTests.swift @@ -183,3 +183,48 @@ func consumedContainerMetadataPreservesStaleAndCommunicationErrors(role: String) try access.nodeObservation(attributes: ["AXRole": "AXGroup" as CFString, "AXChildren": try wrappedAXError(.illegalArgument)]) { _ in nil }.attribute("AXChildren") } } + +@Test(arguments: ["AXValue", "AXSelectedTextRange"]) +func observationRetainsUnknownWritabilityAndFollowingNodes(failedAttribute: String) throws { + let access = AXAccess(timeout: 1, cancellation: CancellationLatch()) + var lines: [String] = [] + for title in ["Affected control", "Following control"] { + let writable = try AXAccess.observationWritability(role: "AXTextField") { name, discovery in + try access.attributeWritability(true, error: title == "Affected control" && name == failedAttribute ? .failure : .success, + name: name, forDiscovery: discovery) + } + let node = AXTextNode(index: nil, role: "AXTextField", title: title, value: "Text", description: nil, + actions: [], enabled: true, valueWritable: writable.value, selectionWritable: writable.selection, + selected: nil, selectedRange: nil, selectedText: nil) + lines.append(AXTextFormatter.line(node, level: 0)) + } + let unknown = failedAttribute == "AXValue" ? "valueWritable" : "selectionWritable" + #expect(lines[0].contains("\(unknown)=unknown")) + #expect(!lines[0].contains("\(unknown)=true")) + #expect(lines[0].contains("Affected control")) + #expect(lines[1].contains("Following control")) + #expect(lines[1].contains("valueWritable=true selectionWritable=true")) + do { + _ = try access.attributeWritability(true, error: .failure, name: failedAttribute, forDiscovery: false) + Issue.record("Mutation admitted unknown writability") + } catch let error as NativeFailure { + #expect(error.accessibilityError == -25200) + #expect(error.code == "NATIVE_ERROR") + } +} + +@Test(arguments: ["AXValue", "AXSelectedTextRange"]) +func observationWritabilityPreservesPermissionCommunicationAndInvalidElementErrors(attribute: String) { + let access = AXAccess(timeout: 1, cancellation: CancellationLatch()) + for code in [AXError.apiDisabled, .cannotComplete, .invalidUIElement, .illegalArgument] { + do { + _ = try AXAccess.observationWritability(role: "AXTextField") { name, discovery in + try access.attributeWritability(true, error: name == attribute ? code : .success, name: name, forDiscovery: discovery) + } + Issue.record("Observation hid an actionable AX error") + } catch let error as NativeFailure { + #expect(error.accessibilityError == code.rawValue) + #expect(error.code == (code == .apiDisabled ? "PERMISSION_DENIED" : "NATIVE_ERROR")) + } catch { Issue.record("Unexpected error: \(error)") } + } +} diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index d5bdceb896..764093e559 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -160,6 +160,8 @@ function createApplicationState(socket, record, application, captureBroker, conn } if (method === 'listWindows') return [window, axlessWindow] if (params.windowId !== undefined && ![7, 8, 9].includes(params.windowId)) refuse('WINDOW_UNAVAILABLE', 'Window is closed or belongs to another application') + const writableFailureFile = new URL('./fixture-ax-writability-failure', import.meta.url) + const writableFailure = existsSync(writableFailureFile) ? readFileSync(writableFailureFile, 'utf8') : undefined if (method === 'getState') { snapshots.delete(params.windowId ?? null) if (params.windowId === undefined) observedWindows.clear() @@ -177,7 +179,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (axless) return { appHandle: app.appHandle, windowId: 8, snapshotId, tree: '', elements: [], windows: [axlessWindow], truncated: false } return { appHandle: app.appHandle, windowId: params.windowId ?? null, - snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=true selectionWritable=true value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, + snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : 'true'} value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, elements: [{ elementId: '0', role: 'AXButton', title: 'Increment', value: null, description: null, identifier: null, bounds: [60, 80, 100, 20], actions: ['AXPress'], enabled: true }], windows: [params.windowId === 9 ? transformedWindow : window], truncated: false } @@ -203,6 +205,9 @@ function createApplicationState(socket, record, application, captureBroker, conn } if (['click', 'mouseMove', 'scroll', 'drag'].includes(method) && params.elementId === undefined && !observedWindows.has(params.windowId)) refuse('STALE_SNAPSHOT', 'Window has no observation; read getAccessibilityTree or take a screenshot before coordinate input') + if ((method === 'setValue' && writableFailure === 'AXValue') || (method === 'selectText' && writableFailure === 'AXSelectedTextRange')) { + refuse('NATIVE_ERROR', `Accessibility read writability of ${writableFailure} failed with error -25200`) + } if (method === 'click' || method === 'setValue' || method === 'mouseMove') { const observed = params.snapshotId === undefined && params.elementId === undefined ? snapshots.get(params.windowId) ?? snapshots.get(null) diff --git a/snapshots/session/cua-ptc/consent-fixture.mjs b/snapshots/session/cua-ptc/consent-fixture.mjs index 2e958b6c3c..e93ba645f8 100644 --- a/snapshots/session/cua-ptc/consent-fixture.mjs +++ b/snapshots/session/cua-ptc/consent-fixture.mjs @@ -1,4 +1,4 @@ -/** Own the bridge module and private native substitute; the replay owns its AX-failure marker through finally. */ +/** Own the bridge module and private native substitute; the replay owns its AX-failure markers through finally. */ import { chmod, copyFile, unlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { startFixtureHost } from '../cua-native/fixture-host.mjs' diff --git a/snapshots/session/cua-ptc/replay.override.json b/snapshots/session/cua-ptc/replay.override.json index 5098b66218..678896fb8d 100644 --- a/snapshots/session/cua-ptc/replay.override.json +++ b/snapshots/session/cua-ptc/replay.override.json @@ -65,6 +65,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-ptc-writability", + "name": "run_code", + "arguments": "{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree({ emit: false });\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\nreturn results;\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -78,7 +111,7 @@ "index": 0, "block": { "type": "text", - "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot." + "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict." } }, { diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 734f20ae62..9e2e3d52d4 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794212769549,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794212769549,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794212769549,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794212769549,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794213719496,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794213719496,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794213719496,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794213719496,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused, coordinateRefused, coordinateDispatched };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794212770340,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794212770340,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused, coordinateRefused, coordinateDispatched };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794212770340,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794212770340,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused, coordinateRefused, coordinateDispatched };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794213720632,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794213720632,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused, coordinateRefused, coordinateDispatched };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794213720632,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794213720632,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n let coordinateRefused = false;\\n try { await window.click([100, 100], { relative: true }); }\\n catch (error) { if (!error.message.includes('Window has no observation')) throw error; coordinateRefused = true; }\\n if (!coordinateRefused) throw new Error('Coordinate input accepted without observation');\\n const shot = await window.getScreenshot();\\n const coordinateDispatched = (await window.click([100, 100], { relative: true })).dispatched;\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused, coordinateRefused, coordinateDispatched };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -50,6 +50,23 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794212770534,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794212770534,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794212770534,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794212770534,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree({ emit: false });\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\nreturn results;\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794213720832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794213720832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree({ emit: false });\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\nreturn results;\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}}},{"type":"chunk","time":1794213720832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794213720832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-ptc-writability","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nconst cua = connectCua(() => tools.cua);\\nconst app = await cua.getApp('test.fixture');\\nconst results = [];\\nfor (const attribute of ['AXValue', 'AXSelectedTextRange']) {\\n await writeFile('fixture-ax-writability-failure', attribute);\\n try {\\n const tree = await app.getAccessibilityTree({ emit: false });\\n const field = attribute === 'AXValue' ? 'valueWritable' : 'selectionWritable';\\n if (!tree.includes(field + '=unknown') || tree.includes(field + '=true')) throw new Error('Unknown writability was lost');\\n if (!tree.includes('Increment') || !tree.includes('Count:')) throw new Error('Other nodes were lost');\\n let writeRefused = false;\\n try {\\n if (attribute === 'AXValue') await app.setValue('1', 'must not be written');\\n else await app.selectText('1', 'Fixture');\\n } catch (error) {\\n if (!error.message.includes('writability of ' + attribute + ' failed with error -25200')) throw error;\\n writeRefused = true;\\n }\\n if (!writeRefused) throw new Error('Write accepted with unknown writability');\\n results.push({ attribute, unknown: true, otherNodesRetained: true, writeRefused });\\n } finally { await unlink('fixture-ax-writability-failure'); }\\n}\\nreturn results;\",\"description\":\"Retain AX trees with unknown writability and reject writes\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":true,\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":null,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=unknown selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:4","name":"cua","arguments":{"method":"setValue","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-2","elementId":"1","value":"must not be written"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:4","name":"cua","arguments":{"method":"setValue","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-2","elementId":"1","value":"must not be written"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXValue failed with error -25200"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":null,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=unknown value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:6","name":"cua","arguments":{"method":"selectText","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-3","elementId":"1","text":"Fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-writability","parentCallId":"cua-ptc-writability","subCallId":"cua-ptc-writability:ptc:6","name":"cua","arguments":{"method":"selectText","params":{"appHandle":"fixture-app","snapshotId":"fixture-snapshot-3","elementId":"1","text":"Fixture"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Accessibility read writability of AXSelectedTextRange failed with error -25200"}]}} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-writability"},"toolCallId":"cua-ptc-writability","content":[{"type":"text","text":"[\n {\n \"attribute\": \"AXValue\",\n \"unknown\": true,\n \"otherNodesRetained\": true,\n \"writeRefused\": true\n },\n {\n \"attribute\": \"AXSelectedTextRange\",\n \"unknown\": true,\n \"otherNodesRetained\": true,\n \"writeRefused\": true\n }\n]"}],"isError":false,"id":"{{message:11}}"}},"sourceEventSeqs":[52],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} +{"type":"step/start","data":{"turn":1,"step":4}} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794213721002,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794213721002,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot. Both writability probe failures left the tree readable with unknown fields and kept writes strict."}}},{"type":"chunk","time":1794213721002,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794213721002,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":4}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From c1001a4b3cd2271df0dd84eb9053af42b5f2b0c9 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 9 Nov 2026 17:10:45 +0800 Subject: [PATCH 06/15] test(plugin-manager): observe Git timeout exit status --- .../boot/plugin-manager/tests/github-connection.spec.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/boot/plugin-manager/tests/github-connection.spec.ts b/packages/boot/plugin-manager/tests/github-connection.spec.ts index 1d76e1eaf1..008830210f 100644 --- a/packages/boot/plugin-manager/tests/github-connection.spec.ts +++ b/packages/boot/plugin-manager/tests/github-connection.spec.ts @@ -118,8 +118,12 @@ 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 childResult = await vi.mocked(subprocess.execa).mock.results.at(-1)!.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) From 0a4b8d1363eecc62714c294bb24f8f6e33de59a9 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 17:12:38 +0800 Subject: [PATCH 07/15] feat(forge): read and set viewed marks and act on the change request overview ChangeRequestSnapshot now carries the reviewers, linked closing issues, branch update methods, and the viewer's rights to request reviews and rerun checks; each check names its rerun. Providers may implement viewed mark reads and writes, failed check reruns, review requests with a reviewer search, and head-pinned branch updates. The registry fails an action a provider lacks without polling, and polls a watched change request after every action the provider answered. --- .../guide.i18n.yaml | 16 ++ .../forge-change-request-overview/guide.md | 23 +++ .../forge-change-request-overview/guide.zh.md | 23 +++ .../forge-session/tests/fixtures.ts | 7 + .../tests/loader-composition.spec.ts | 8 +- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 6 + packages/experimental/forge/README.zh.md | 6 + packages/experimental/forge/src/index.ts | 132 ++++++++++++++- packages/experimental/forge/src/types.ts | 150 ++++++++++++++++++ .../experimental/forge/tests/fake-provider.ts | 7 + .../experimental/forge/tests/registry.spec.ts | 56 +++++++ .../experimental/forge/tests/watch.spec.ts | 69 +++++++- 13 files changed, 499 insertions(+), 8 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md 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..6ecd0cfd15 --- /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: 6c0fc046709d9325 + zh: 532328a943b4b9bc +/forge-snapshots-carry-the-change-request-overview: + en: c68b2863aee295e2 + zh: 00caaff4e530872a +/forge-snapshots-carry-the-change-request-overview/change: + en: fd8113f3d0ad2af6 + zh: 9f01008ed1b1a349 +/forge-snapshots-carry-the-change-request-overview/migration: + en: 3fbd619c7646c8df + zh: ebf8ec7f5b3aeb47 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..feca3a50ac --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot gains required overview fields and ChangeRequestCheck gains the required rerun field." +--- + +# Forge snapshots carry the change request overview + +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. + +`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. Run your type check; it succeeds when every snapshot and check a provider builds sets the new fields. 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..891f735878 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestCheck 新增必填的 rerun 字段。" +--- + +# Forge 快照携带变更请求概览 + +[English](guide.md) | 中文 + +## 变更 + +`ChangeRequestSnapshot` 新增七个必填字段:`reviewers` 与 `reviewersTruncated`、`closingIssues` 与 `closingIssuesTruncated`、`branchUpdates`、`canRequestReviews`,以及 `canRerunChecks`。`ChangeRequestCheck` 新增必填的 `rerun: ForgeCheckId | null`,指出提供方如何重跑该检查。变更请求卡片读取这些字段,列出评审者、关联 issue 与分支更新,并提供重跑失败检查、请求评审与更新分支。 + +`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. 运行类型检查;提供方构造的每个快照与检查都设置了新字段时即通过。 diff --git a/packages/experimental/forge-session/tests/fixtures.ts b/packages/experimental/forge-session/tests/fixtures.ts index 2c857ad28e..cd05bf0cea 100644 --- a/packages/experimental/forge-session/tests/fixtures.ts +++ b/packages/experimental/forge-session/tests/fixtures.ts @@ -41,12 +41,19 @@ export function snapshot(ref: ChangeRequestRef, overrides: Partial ({ mergeable: 'MERGEABLE', mergeStateStatus: number === 7 ? 'BLOCKED' : 'CLEAN', reviewDecision: null, + viewerCanUpdateBranch: false, + canBeRebased: false, reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }, + reviewRequests: { totalCount: 0, nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + latestOpinionatedReviews: { totalCount: 0, nodes: [] }, + closingIssuesReferences: { totalCount: 0, nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-' + number, state: number === 7 ? 'PENDING' : 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ __typename: 'CheckRun', id: 'check-1', databaseId: 1, name: 'test', status: number === 7 ? 'IN_PROGRESS' : 'COMPLETED', conclusion: number === 7 ? null : 'SUCCESS', - detailsUrl: null, startedAt: null, completedAt: null, checkSuite: { app: { id: 'actions' }, workflowRun: { event: 'pull_request', workflow: { id: 'ci', name: 'ci' } } }, + detailsUrl: null, startedAt: null, completedAt: null, checkSuite: { app: { id: 'actions' }, workflowRun: { databaseId: 1, event: 'pull_request', workflow: { id: 'ci', name: 'ci' } } }, }] }, } } }] }, }) diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index 63af9c19d6..b0f3246322 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: bbcc0748865efab8 - zh: 6aaa7369baacfa4a + en: fefda1bceb0bfcb9 + zh: 63e30b340db2fba4 /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 85558b1fc5..e84cdd28c4 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -40,6 +40,12 @@ Mount the registry with at least one provider package, such as the GitHub provid Providers may implement `commits` and `compare` together. `commits(ref, signal)` lists a change request's commits oldest first, each with its full object name, first parent, title, author, and author time, at one head commit and with a `truncated` flag; `compare(ref, base, head, signal)` reads the unified patch from commit `base` to commit `head`. The registry returns undefined from `commits` and an `unavailable` failure from `compare` when the provider lacks either method, so a consumer can offer commit views only where both exist. +Providers may implement `viewedFiles` and `setViewed` together. `viewedFiles(ref, headSha, signal)` reads the signed-in user's viewed marks on the files of a change request at head commit `headSha`, each `viewed`, `unviewed`, or `dismissed` when the file changed after it was marked, with a `truncated` flag; `setViewed(ref, { path, viewed, headSha }, signal)` sets or clears one file's mark only while the head is still `headSha`. Both report a moved head as `stale`, which polls a watched change request as a stale `diff` does. When the provider lacks either method, `viewedFiles` returns undefined and `setViewed` a `failed` failure, so a consumer keeps viewed marks itself. + +Snapshots carry the overview of a change request. `reviewers` lists requested reviewers first, then the latest reviewer of each account with their verdict and the commit it was given at; `closingIssues` lists the issues the host closes when the change request merges; `reviewersTruncated` and `closingIssuesTruncated` mark lists the provider read only in part. `branchUpdates` names the methods that would bring a head behind its base up to date for the signed-in user, empty when the head is current, conflicts, or may not be updated. `canRequestReviews` and `canRerunChecks` state the signed-in user's rights, and each check's `rerun` names the host run that reruns it, or null. + +Providers may implement `rerunChecks(ref, { headSha }, signal)`, which reruns the failed checks of head commit `headSha`; `requestReviews(ref, { reviewers }, signal)` together with `reviewerCandidates(ref, query, signal)`, which lists accounts a review can be requested from with the host's suggestions first; and `updateBranch(ref, { method, headSha }, signal)`, which merges or rebases the base into the head only while the head is still `headSha`. Each action resolves to undefined once the host accepted it or to a `ForgeActionFailure`, and polls a watched change request once it settles. The registry fails an action the provider lacks with `failed`, and returns `unavailable` from `reviewerCandidates` unless the provider implements both review request methods. + `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. `ctx.forge.watch(ref, listener)` is also an effect. The first watcher of a change request polls it at once; `latest(ref)` returns the most recent result. Each forge has at most one polling fetch in flight, and that fetch includes every due change request of the forge. An open change request is polled every `activeIntervalMs` while checks are pending or mergeability is unknown, and every `idleIntervalMs` otherwise. Closed change requests use `idleIntervalMs` to detect reopening; merged requests stop automatic polling. `refresh(ref)` polls a watched change request at once, including after a terminal state; if a fetch is already in flight for its forge, another fetch starts immediately after it settles. A failed read repeats after `activeIntervalMs` doubled for each consecutive failure, up to `maxBackoffMs`, which must be at least `activeIntervalMs`. Unregistering a provider settles its watched change requests as `unavailable`. Polling stops when the last watcher leaves. The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge) lists the defaults. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 11a2ed87e6..11fa4569a3 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -40,6 +40,12 @@ kind: "package-reference" 提供方可以同时实现 `commits` 与 `compare`。`commits(ref, signal)` 在一个 head 提交上按从旧到新列出变更请求的提交,每个提交带完整对象名、第一个父提交、标题、作者与作者时间,并带 `truncated` 标志;`compare(ref, base, head, signal)` 读取从提交 `base` 到提交 `head` 的统一补丁。提供方缺少其中任一方法时,注册表的 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此使用方只在两者都存在时提供按提交查看。 +提供方可以同时实现 `viewedFiles` 与 `setViewed`。`viewedFiles(ref, headSha, signal)` 在 head 提交 `headSha` 上读取当前登录用户对变更请求各文件的已审阅标记,每个文件为 `viewed`、`unviewed`,或在标记后又有改动时为 `dismissed`,并带 `truncated` 标志;`setViewed(ref, { path, viewed, headSha }, signal)` 仅在 head 仍是 `headSha` 时设置或清除一个文件的标记。两者都把已移动的 head 报告为 `stale`,并像过期的 `diff` 一样立即轮询被监听的变更请求。提供方缺少其中任一方法时,`viewedFiles` 返回 undefined,`setViewed` 返回 `failed` 失败,因此使用方自行保存已审阅标记。 + +快照携带变更请求的概览。`reviewers` 先列出被请求的评审者,再列出每个账号最近一次评审的结论及其所针对的提交;`closingIssues` 列出变更请求合并时代码托管平台会关闭的 issue;`reviewersTruncated` 与 `closingIssuesTruncated` 标记提供方只读取了部分的列表。`branchUpdates` 列出能让落后于基线的 head 为当前登录用户更新的方式;head 已是最新、存在冲突或不允许更新时为空。`canRequestReviews` 与 `canRerunChecks` 说明当前登录用户的权限,每个检查的 `rerun` 指出能重跑它的托管平台运行,否则为 null。 + +提供方可以实现 `rerunChecks(ref, { headSha }, signal)`,重跑 head 提交 `headSha` 的失败检查;可以同时实现 `requestReviews(ref, { reviewers }, signal)` 与 `reviewerCandidates(ref, query, signal)`,后者列出可以请求评审的账号,托管平台的建议排在最前;还可以实现 `updateBranch(ref, { method, headSha }, signal)`,仅在 head 仍是 `headSha` 时把基线合并或变基进 head。每个操作在托管平台接受后返回 undefined,否则返回 `ForgeActionFailure`,结束后会立即轮询被监听的变更请求。提供方缺少某个操作时,注册表以 `failed` 失败返回;除非提供方同时实现两个评审请求方法,`reviewerCandidates` 返回 `unavailable`。 + `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 `ctx.forge.watch(ref, listener)` 同样是 effect。变更请求的第一个监听方会立即触发轮询;`latest(ref)` 返回最近一次结果。每个 forge 同时最多只有一次轮询读取在进行,这次读取包含该 forge 所有到期的变更请求。打开状态的变更请求在检查未完成或可合并性未知时每 `activeIntervalMs` 轮询一次,否则每 `idleIntervalMs` 轮询一次。已关闭的变更请求按 `idleIntervalMs` 轮询以检测重新打开;已合并的停止自动轮询。`refresh(ref)` 立即轮询一个被监听的变更请求,已结束的也包括在内;该 forge 已有读取在进行时,等待其结束后立即再读一次。读取失败后,重试间隔为 `activeIntervalMs` 按连续失败次数翻倍,最长 `maxBackoffMs`;该值必须大于或等于 `activeIntervalMs`。注销提供方会让其被监听的变更请求以 `unavailable` 结束。最后一个监听方离开后轮询停止。默认值见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge)。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index 9796d5e097..aca2a49f12 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -6,9 +6,10 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { changeRequestKey } from './keys.ts' import { nextPollDelay } from './schedule.ts' import type { - ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, - ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, - ForgeReviewWrite, ForgeReviewWriteResult, MergeRequest, + BranchUpdateRequest, ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, + ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, + ForgeReviewerCandidate, ForgeReviewersRequest, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, + ForgeViewedFiles, ForgeViewedRequest, MergeRequest, } from './types.ts' export { changeRequestKey } from './keys.ts' @@ -224,6 +225,68 @@ export class ForgeService extends Service { return failure } + /** + * 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 { + return await this.act(ref, signal, provider => provider.rerunChecks?.bind(provider), 'reruns no checks', + (action, operation) => action(ref, request, operation)) + } + + /** + * 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 { + return await this.act(ref, signal, + provider => provider.reviewerCandidates === undefined ? undefined : provider.requestReviews?.bind(provider), 'requests no reviews', + (action, operation) => action(ref, request, operation)) + } + + /** + * 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 { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.reviewerCandidates === undefined || provider.requestReviews === undefined + ? Promise.resolve({ code: 'unsupported', message: 'This provider requests no reviews' } as const) + : provider.reviewerCandidates(ref, query, operation)) + } + + /** + * 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 { + return await this.act(ref, signal, provider => provider.updateBranch?.bind(provider), 'updates no branches', + (action, operation) => action(ref, request, operation)) + } + /** * Read complete check details independently of periodic polling. * @param ref - change request served by a registered provider. @@ -297,6 +360,42 @@ export class ForgeService extends Service { return result } + /** + * 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 { + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.viewedFiles === undefined || provider.setViewed === undefined + ? Promise.resolve(undefined) : provider.viewedFiles(ref, headSha, operation)) + if (result !== undefined && 'code' in result) this.staleRead(ref, headSha, result.code) + return result + } + + /** + * 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 { + const failure = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.viewedFiles === undefined || provider.setViewed === undefined + ? Promise.resolve({ code: 'failed', message: 'This provider keeps no viewed marks' } as const) + : provider.setViewed(ref, request, operation)) + if (failure?.code === 'stale') this.staleRead(ref, request.headSha, failure.code) + return failure + } + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -429,6 +528,33 @@ export class ForgeService extends Service { this.refresh(ref) } + /** + * Run one optional provider action, then poll the change request at once when it is watched and the provider has the + * action. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the action. + * @param pick - the provider's action, or undefined when it lacks the capability. + * @param missing - what a provider without the action does not do, for its failure. + * @param run - calls the action. + * @returns the action's failure, or undefined once the host accepted it. + */ + private async act( + ref: ChangeRequestRef, + signal: AbortSignal, + pick: (provider: ForgeProvider) => A | undefined, + missing: string, + run: (action: A, signal: AbortSignal) => Promise, + ): Promise { + // Null stands for a provider without the action, which the host was never asked about. + const failure = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => { + const action = pick(provider) + return action === undefined ? Promise.resolve(null) : run(action, operation) + }) + if (failure === null) return { code: 'failed', message: `This provider ${missing}` } + this.refresh(ref) + return failure + } + private provider(forge: string): ForgeProvider { return this.registration(forge).provider } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 17b83d2059..270358de4e 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -31,6 +31,9 @@ export type ChangeRequestState = 'open' | 'closed' | 'merged' /** Normalized outcome of one status check. */ export type CheckState = 'pending' | 'success' | 'failure' | 'neutral' | 'skipped' | 'cancelled' +/** Opaque host identity of a status check that a rerun names. */ +export type ForgeCheckId = Branded<'ForgeCheckId'> + /** One status check reported for the head commit of a change request. */ export interface ChangeRequestCheck { /** Check name as the host displays it. */ @@ -45,6 +48,8 @@ export 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. */ + readonly rerun: ForgeCheckId | null } /** Combined outcome of all checks on the head commit. */ @@ -59,6 +64,44 @@ export type ReviewDecision = 'approved' | 'changes-requested' | 'review-required /** How a merge brings the commits of a change request into its base branch. */ export type MergeMethod = 'merge' | 'squash' | 'rebase' +/** 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. */ +export type BranchUpdateMethod = 'merge' | 'rebase' + +/** Outcome of a reviewer's latest submitted review. */ +export type ReviewVerdict = 'approved' | 'changes-requested' | 'commented' | 'dismissed' + +/** An account or team asked to review a change request, or an account that reviewed it. */ +export 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 +} + +/** One issue linked to a change request, which the host closes once the change request merges. */ +export 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 +} + /** Status of one change request at the time its provider read it. */ export interface ChangeRequestSnapshot { /** Change request the snapshot describes. */ @@ -97,18 +140,35 @@ export 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. + */ + 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. */ @@ -150,6 +210,38 @@ export interface MergeRequest { readonly headSha: string } +/** A branch update the user confirmed for the head commit they saw. */ +export 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 +} + +/** A rerun of the failed checks of the head commit whose checks the user saw. */ +export interface ForgeRerunRequest { + /** Head commit whose checks the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string +} + +/** Reviewers to ask in addition to those whose review is requested now; one who already reviewed is asked again. */ +export interface ForgeReviewersRequest { + /** The reviewers by kind and login, a team by `organization/slug`. */ + readonly reviewers: readonly Pick[] +} + +/** An account a review of the change request can be requested from. */ +export 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 +} + /** One inline comment addressed to the old or new side of a pull request diff. */ export interface ForgeLineComment { readonly path: string @@ -349,6 +441,32 @@ export interface ForgeCommitList { readonly truncated: boolean } +/** + * 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. + */ +export type ForgeViewedState = 'viewed' | 'unviewed' | 'dismissed' + +/** The signed-in user's viewed marks on the files of a change request, read at one head commit. */ +export 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 +} + +/** A viewed mark the user set or cleared on a file of the head commit they saw. */ +export 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 +} + /** Whether a provider can reach one host with the current credentials. */ export interface ForgeReadiness { /** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */ @@ -420,6 +538,38 @@ export 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`, while the head is still `request.headSha`, + * resolving to undefined once the host accepted the 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 } /** diff --git a/packages/experimental/forge/tests/fake-provider.ts b/packages/experimental/forge/tests/fake-provider.ts index 4c035071b7..722cd497a8 100644 --- a/packages/experimental/forge/tests/fake-provider.ts +++ b/packages/experimental/forge/tests/fake-provider.ts @@ -34,12 +34,19 @@ export function snapshot(target: ChangeRequestRef, overrides: Partial { expect(writeReview).toHaveBeenCalledWith(ref(3), write, expect.any(AbortSignal)) }) + it('reads and saves viewed marks only through a provider that implements both', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const marks = { headSha: 'a'.repeat(40), files: { 'src/a.ts': 'viewed' as const }, truncated: false } + const request = { path: 'src/a.ts', viewed: true, headSha: 'a'.repeat(40) } + + await expect(ctx.forge.viewedFiles(ref(3), 'a'.repeat(40), signal)).resolves.toBeUndefined() + await expect(ctx.forge.setViewed(ref(3), request, signal)).resolves.toEqual({ code: 'failed', message: 'This provider keeps no viewed marks' }) + const viewedFiles = vi.fn(async () => marks) + Object.assign(provider, { viewedFiles }) + await expect(ctx.forge.viewedFiles(ref(3), 'a'.repeat(40), signal)).resolves.toBeUndefined() + const setViewed = vi.fn(async () => undefined) + Object.assign(provider, { setViewed }) + await expect(ctx.forge.viewedFiles(ref(3), 'a'.repeat(40), signal)).resolves.toBe(marks) + await expect(ctx.forge.setViewed(ref(3), request, signal)).resolves.toBeUndefined() + expect(viewedFiles).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), expect.any(AbortSignal)) + expect(setViewed).toHaveBeenCalledWith(ref(3), request, expect.any(AbortSignal)) + }) + + it('fails the overview actions of a provider without them and forwards them to one with them', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const rerun = { headSha: 'a'.repeat(40) } + const reviewers = { reviewers: [{ kind: 'user' as const, login: 'mona' }] } + const update = { method: 'rebase' as const, headSha: 'a'.repeat(40) } + + await expect(ctx.forge.rerunChecks(ref(3), rerun, signal)).resolves.toEqual({ code: 'failed', message: 'This provider reruns no checks' }) + await expect(ctx.forge.requestReviews(ref(3), reviewers, signal)).resolves.toEqual({ code: 'failed', message: 'This provider requests no reviews' }) + await expect(ctx.forge.reviewerCandidates(ref(3), 'mo', signal)) + .resolves.toEqual({ code: 'unsupported', message: 'This provider requests no reviews' }) + await expect(ctx.forge.updateBranch(ref(3), update, signal)).resolves.toEqual({ code: 'failed', message: 'This provider updates no branches' }) + // Requests need both halves of the review request capability. + const requestReviews = vi.fn(async () => undefined) + Object.assign(provider, { requestReviews }) + await expect(ctx.forge.requestReviews(ref(3), reviewers, signal)).resolves.toMatchObject({ code: 'failed' }) + await expect(ctx.forge.reviewerCandidates(ref(3), 'mo', signal)).resolves.toMatchObject({ code: 'unsupported' }) + + const candidates = [{ login: 'mona', name: 'Mona', avatarUrl: null, suggested: true }] + const reviewerCandidates = vi.fn(async () => candidates) + const rerunChecks = vi.fn(async () => undefined) + const updateBranch = vi.fn(async () => ({ code: 'stale' as const, message: 'moved' })) + Object.assign(provider, { reviewerCandidates, rerunChecks, updateBranch }) + await expect(ctx.forge.rerunChecks(ref(3), rerun, signal)).resolves.toBeUndefined() + await expect(ctx.forge.requestReviews(ref(3), reviewers, signal)).resolves.toBeUndefined() + await expect(ctx.forge.reviewerCandidates(ref(3), 'mo', signal)).resolves.toBe(candidates) + await expect(ctx.forge.updateBranch(ref(3), update, signal)).resolves.toEqual({ code: 'stale', message: 'moved' }) + expect(rerunChecks).toHaveBeenCalledWith(ref(3), rerun, expect.any(AbortSignal)) + expect(requestReviews).toHaveBeenCalledWith(ref(3), reviewers, expect.any(AbortSignal)) + expect(reviewerCandidates).toHaveBeenCalledWith(ref(3), 'mo', expect.any(AbortSignal)) + expect(updateBranch).toHaveBeenCalledWith(ref(3), update, expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index f5a27e9749..540f108627 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -2,8 +2,8 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData, - ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeProvider, ForgeRepository, + ForgeReviewData, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, } from '../src/types.ts' import { FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' @@ -339,6 +339,71 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(4) }) + it('polls at once after the first stale viewed read or write at a head, and not for other outcomes', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const viewedFiles = vi.fn>() + .mockResolvedValueOnce({ headSha: 'a'.repeat(40), files: {}, truncated: false }) + .mockResolvedValueOnce({ code: 'stale', message: 'the head moved' }) + const setViewed = vi.fn>() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce({ code: 'failed', message: 'refused' }) + .mockResolvedValueOnce({ code: 'stale', message: 'the head moved' }) + Object.assign(provider, { viewedFiles, setViewed }) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + const request = { path: 'src/a.ts', viewed: true, headSha: 'a'.repeat(40) } + + await context.forge.viewedFiles(ref(1), 'a'.repeat(40), signal) + await context.forge.setViewed(ref(1), request, signal) + await context.forge.setViewed(ref(1), request, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(1) + + await context.forge.viewedFiles(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + // The read already polled once at this head. + await context.forge.setViewed(ref(1), request, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + }) + + it.each(['rerunChecks', 'requestReviews', 'updateBranch'] as const)('polls at once after %s, whatever the host answered', async (action) => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + Object.assign(provider, { + rerunChecks: vi.fn(async () => ({ code: 'failed', message: 'refused' })), + requestReviews: vi.fn(async () => undefined), + reviewerCandidates: vi.fn(async () => []), + updateBranch: vi.fn(async () => ({ code: 'stale', message: 'moved' })), + }) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + if (action === 'rerunChecks') await context.forge.rerunChecks(ref(1), { headSha: 'a'.repeat(40) }, signal) + else if (action === 'requestReviews') await context.forge.requestReviews(ref(1), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal) + else await context.forge.updateBranch(ref(1), { method: 'merge', headSha: 'a'.repeat(40) }, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + }) + + it('does not poll after an action the provider lacks, since the host was not asked', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + await expect(context.forge.rerunChecks(ref(1), { headSha: 'a'.repeat(40) }, signal)).resolves.toMatchObject({ code: 'failed' }) + await expect(context.forge.updateBranch(ref(1), { method: 'merge', headSha: 'a'.repeat(40) }, signal)).resolves.toMatchObject({ code: 'failed' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(1) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) From c8191be1e865ca1877e8f384450aa161c7394a1f Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Mon, 9 Nov 2026 17:12:47 +0800 Subject: [PATCH 08/15] Revert "test(plugin-manager): observe Git timeout exit status" This reverts commit 3c904f6b3a78f92ae1f3b3eff42d354ffb58a952. --- .../boot/plugin-manager/tests/github-connection.spec.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/boot/plugin-manager/tests/github-connection.spec.ts b/packages/boot/plugin-manager/tests/github-connection.spec.ts index 008830210f..1d76e1eaf1 100644 --- a/packages/boot/plugin-manager/tests/github-connection.spec.ts +++ b/packages/boot/plugin-manager/tests/github-connection.spec.ts @@ -118,12 +118,8 @@ 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') - // Git's termination status varies by platform; preserve the observed status, or the fallback when absent. - const childResult = await vi.mocked(subprocess.execa).mock.results.at(-1)!.value - expect(childResult.timedOut).toBe(true) - expect(result).toMatchObject({ - exitCode: childResult.exitCode ?? 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git'), - }) + // 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') }) expect(result!.output).toContain('connection to github.com timed out after 3000ms') await transport.disconnected expect(transport.sockets.size).toBe(0) From a71553a3fdf6682baa0b098f2f104553323b738a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 17:12:50 +0800 Subject: [PATCH 09/15] feat(forge-github): sync viewed files and read and act on the pull request overview Status reads add review requests, latest reviews, closing issue references, and whether the viewer may update or rebase the head. Viewed files are read through the files listing, bounded by the new maxViewedFiles, and set with markFileAsViewed or unmarkFileAsViewed after a head check. Failed GitHub Actions runs are rerun through the REST API, reviews are requested with requestReviewsByLogin, and branches are updated with expectedHeadOid. Every mutation goes through the sender review writes use, now in mutation.ts. --- .../forge-github/README.i18n.yaml | 8 +- packages/experimental/forge-github/README.md | 10 +- .../experimental/forge-github/README.zh.md | 10 +- .../experimental/forge-github/src/graphql.ts | 139 +++++++++++++++++- .../experimental/forge-github/src/index.ts | 5 +- .../experimental/forge-github/src/mutation.ts | 86 +++++++++++ .../experimental/forge-github/src/overview.ts | 128 ++++++++++++++++ .../experimental/forge-github/src/provider.ts | 90 +++++++++++- .../forge-github/src/pull-request-node.ts | 42 ++++++ .../forge-github/src/review-writes.ts | 72 +-------- .../experimental/forge-github/src/viewed.ts | 128 ++++++++++++++++ .../forge-github/tests/fixtures.ts | 11 +- .../forge-github/tests/graphql.spec.ts | 109 +++++++++++++- .../forge-github/tests/overview.spec.ts | 135 +++++++++++++++++ .../forge-github/tests/provider.spec.ts | 135 ++++++++++++++++- .../forge-github/tests/review-writes.spec.ts | 2 +- .../forge-github/tests/review.spec.ts | 5 +- .../forge-github/tests/threads.spec.ts | 2 +- .../forge-github/tests/viewed.spec.ts | 118 +++++++++++++++ 19 files changed, 1140 insertions(+), 95 deletions(-) create mode 100644 packages/experimental/forge-github/src/mutation.ts create mode 100644 packages/experimental/forge-github/src/overview.ts create mode 100644 packages/experimental/forge-github/src/pull-request-node.ts create mode 100644 packages/experimental/forge-github/src/viewed.ts create mode 100644 packages/experimental/forge-github/tests/overview.spec.ts create mode 100644 packages/experimental/forge-github/tests/viewed.spec.ts diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 42a42a70c5..52977df4e4 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: 2ab29060f216c1aa - zh: 0518073681b2c8e3 + en: ba6f281a24f3cce0 + zh: b99a3c479b250402 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: - en: c6975cef45d63fe8 - zh: ccb96a7eee385c13 + en: 9b639e511e850042 + zh: 25a1a3bde330e7da /deepseek-ai-dsh-experimental-forge-github/further-exploration: en: d377d5fd9d9f190e zh: 920bcbfdb8c993f2 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index cc87b02c32..d272b7bc67 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -34,7 +34,7 @@ Mount the provider after the forge registry and list every GitHub Enterprise hos hosts: [github.com, ghe.example.com] ``` -The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes`, `maxReviewThreads`, and `maxCommits` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, `maxReviewThreads`, and `maxCommits` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). +The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes`, `maxReviewThreads`, `maxCommits`, and `maxViewedFiles` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, `maxReviewThreads`, `maxCommits`, and `maxViewedFiles` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `git@github.com:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://///pull/` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname `: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none. @@ -56,6 +56,10 @@ The same first page reads what the signed-in viewer may write: each thread's `vi `writeReview` first reads the pull request's `headRefOid` and the viewer's pending review in one GraphQL query and returns `stale` without writing when the head is not `write.headSha`. It then sends one mutation with its variables as JSON on stdin: `addPullRequestReviewThreadReply`, inside the pending review for a pending reply; `resolveReviewThread` or `unresolveReviewThread`; `updatePullRequestReviewComment` or `deletePullRequestReviewComment`; `addPullRequestReviewThread` into the pending review, or `addPullRequestReview` at `write.headSha` with the comment as its first thread when the viewer has none; and `submitPullRequestReview` or `deletePullRequestReview` for the pending review the write names, which the check must still find. A pending reply without a pending review first starts an empty one at the head, so it takes two mutations; when the reply then fails, the empty review stays. A write to a thread or comment also reads, in the same check, the pull request that holds it, and returns `failed` without a mutation when that is another pull request. GitHub adds every reply of a user with a pending review to that review, even one sent without its id, so a reply at once returns `failed` without a mutation while the viewer has one; a thread added to a pending review numbers the lines of the current head, whichever commit the review started at. A mutation's payload means GitHub applied it; GraphQL errors whose types all name a refusal (`FORBIDDEN`, `INSUFFICIENT_SCOPES`, `NOT_FOUND`, `RATE_LIMITED`, `UNPROCESSABLE`) and HTTP 400, 401, 403, 404, 409, and 422 refusals return `failed`, as does a `gh` that cannot start; any other GraphQL error, such as GitHub's timeout message, a `gh` timeout, a server error, or an answer without the payload returns `unknown`. No mutation is retried. +Every status read also reads the overview of each pull request: up to 25 review requests, latest reviews, latest opinionated reviews, and closing issue references, each list marked truncated when GitHub counts more. A review request names a user, bot, or team, and whether it is a code owner request. Reviews of the author and reviews without an author are left out; a dismissed review counts as `dismissed`, and a later opinionated review decides the verdict over a comment. `branchUpdates` is empty for a pull request that is not open, that GitHub reports as conflicting, or whose head the signed-in user may not update; otherwise it offers merge, and rebase as well when GitHub can rebase the head. `canRequestReviews` requires triage, write, maintain, or admin permission on an open pull request, and `canRerunChecks` requires write, maintain, or admin permission. A check run of a GitHub Actions workflow names its workflow run as `rerun`; status contexts and other check runs name none. + +`viewedFiles` lists the pull request's files through GraphQL, 100 per page, up to `maxViewedFiles` (default 3,000) files, and sets `truncated` when GitHub counts more; GitHub's `VIEWED`, `UNVIEWED`, and `DISMISSED` map to `viewed`, `unviewed`, and `dismissed`, and an unknown state to `unviewed`. A page whose head is not the requested commit makes the read `stale`, and a page that does not advance makes it `unavailable`. `setViewed` checks the head, then calls `markFileAsViewed` or `unmarkFileAsViewed`; GitHub keeps one viewed mark per file and user, whatever the commit. `rerunChecks` reads the complete checks, returns `stale` when the head moved, and posts `repos///actions/runs//rerun-failed-jobs` once for each workflow run with a failed check, stopping at the first refusal; GitHub reruns the failed jobs with the jobs that depend on them. `requestReviews` calls `requestReviewsByLogin` with `union: true`, so existing requests stay, and adds the `[bot]` suffix to bot logins. `reviewerCandidates` lists up to 20 assignable users whose login or name contains the query, and with an empty query GitHub's suggested reviewers first; the author is left out. `updateBranch` checks the head, then calls `updatePullRequestBranch` with the update method and `expectedHeadOid`, so GitHub refuses once new commits arrived. These mutations go through the sender `writeReview` uses, with their GraphQL document and variables as JSON on stdin, and are never retried; because each sets a state, a refusal and an outcome GitHub did not confirm both become `failed` with GitHub's message. + ----- @@ -74,7 +78,11 @@ A fetch groups references by host and sends one initial `gh api graphql` query p | [`src/compare.ts`](src/compare.ts) | Patch between two commits through the compare API, shared by every diff read | | [`src/threads.ts`](src/threads.ts) | Review thread read, pagination, and mapping onto head and original positions | | [`src/review-writes.ts`](src/review-writes.ts) | Head check and review thread and pending review mutations | +| [`src/mutation.ts`](src/mutation.ts) | Sending one GraphQL mutation and classifying its outcome | | [`src/gh.ts`](src/gh.ts) | Host `gh` execution with environment scrubbing and limits | +| [`src/viewed.ts`](src/viewed.ts) | Viewed file reads and writes | +| [`src/overview.ts`](src/overview.ts) | Review requests, reviewer search, and branch updates | +| [`src/pull-request-node.ts`](src/pull-request-node.ts) | Pull request node id at a checked head, for mutations | | [`src/urls.ts`](src/urls.ts) | Remote URL and pull request URL parsing, and validation of inlined names and commits | diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 0000255392..9750b2846a 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -34,7 +34,7 @@ kind: "package-reference" hosts: [github.com, ghe.example.com] ``` -即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes`、`maxReviewThreads` 与 `maxCommits` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads` 与 `maxCommits` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 +即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes`、`maxReviewThreads`、`maxCommits` 与 `maxViewedFiles` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes`、`maxReviewThreads`、`maxCommits` 与 `maxViewedFiles` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 @@ -56,6 +56,10 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `writeReview` 先用一次 GraphQL 查询读出 pull request 的 `headRefOid` 和用户的待提交评审;head 不是 `write.headSha` 时不写入,直接返回 `stale`。随后发送一个 mutation,变量以 JSON 形式经 stdin 传入:回复用 `addPullRequestReviewThreadReply`,待提交的回复加入待提交评审;`resolveReviewThread` 或 `unresolveReviewThread`;`updatePullRequestReviewComment` 或 `deletePullRequestReviewComment`;新评论用 `addPullRequestReviewThread` 加入待提交评审,用户还没有待提交评审时,用 `addPullRequestReview` 在 `write.headSha` 上开始一个评审,并把这条评论作为它的第一个讨论;提交或丢弃用 `submitPullRequestReview` 或 `deletePullRequestReview`,作用于写操作指定的待提交评审,检查时必须仍能找到它。没有待提交评审时,待提交的回复会先在 head 上开始一个空评审,因此需要两个 mutation;回复随后失败时,这个空评审会保留下来。写入讨论或评论时,同一次检查还会读出它所属的 pull request,不是当前 pull request 时不发送 mutation,直接返回 `failed`。用户有待提交评审时,GitHub 会把该用户的每条回复都加入这个评审,即使发送时没有带上评审 id;因此该用户有待提交评审时,立即回复不发送 mutation,直接返回 `failed`。加入待提交评审的讨论使用当前 head 的行号,与评审开始时所在的提交无关。mutation 返回 payload 即表示 GitHub 已执行;错误类型全部表示拒绝(`FORBIDDEN`、`INSUFFICIENT_SCOPES`、`NOT_FOUND`、`RATE_LIMITED`、`UNPROCESSABLE`)的 GraphQL 错误以及 HTTP 400、401、403、404、409、422 拒绝返回 `failed`,`gh` 无法启动时也是如此;其他 GraphQL 错误(例如 GitHub 的超时提示)、`gh` 超时、服务端错误或没有 payload 的响应返回 `unknown`。mutation 从不重试。 +每次状态读取还会读取每个 pull request 的概览:最多 25 个评审请求、最近评审、最近的表态评审与关闭的 issue 引用,GitHub 统计到更多时把对应列表标记为截断。评审请求指向用户、bot 或团队,并说明是否为代码所有者请求。作者本人的评审与没有作者的评审被略去;被驳回的评审记为 `dismissed`,较新的表态评审优先于评论决定结论。pull request 未处于 open、GitHub 报告存在冲突或当前登录用户无权更新其 head 时,`branchUpdates` 为空;否则提供 merge,GitHub 能变基该 head 时也提供 rebase。`canRequestReviews` 要求 open 的 pull request 与 triage、write、maintain 或 admin 权限,`canRerunChecks` 要求 write、maintain 或 admin 权限。GitHub Actions 工作流的 check run 以其工作流运行作为 `rerun`;状态上下文与其他 check run 没有 `rerun`。 + +`viewedFiles` 经 GraphQL 每页 100 个列出 pull request 的文件,最多 `maxViewedFiles`(默认 3,000)个,GitHub 统计到更多时设置 `truncated`;GitHub 的 `VIEWED`、`UNVIEWED` 与 `DISMISSED` 分别映射为 `viewed`、`unviewed` 与 `dismissed`,未知状态映射为 `unviewed`。某页的 head 不是请求的提交时读取为 `stale`,分页不前进时为 `unavailable`。`setViewed` 先检查 head,再调用 `markFileAsViewed` 或 `unmarkFileAsViewed`;GitHub 对每个文件和用户只保存一个已审阅标记,与提交无关。`rerunChecks` 读取完整检查,head 已移动时返回 `stale`,再对每个含失败检查的工作流运行 POST 一次 `repos///actions/runs//rerun-failed-jobs`,遇到第一次拒绝即停止;GitHub 会重跑失败的 job 及依赖它们的 job。`requestReviews` 以 `union: true` 调用 `requestReviewsByLogin`,保留已有请求,并为 bot 登录名加上 `[bot]` 后缀。`reviewerCandidates` 列出登录名或名称包含查询文本的最多 20 个可指派用户,查询为空时 GitHub 建议的评审者排在最前;作者被略去。`updateBranch` 先检查 head,再以更新方式与 `expectedHeadOid` 调用 `updatePullRequestBranch`,因此新提交到来后 GitHub 会拒绝。这些写操作与 `writeReview` 使用同一个发送方式,把 GraphQL 文档与变量作为 JSON 经标准输入发送,且从不重试;由于每个写操作都只设置一种状态,GitHub 的拒绝与未确认的结果都为 `failed`,并附 GitHub 的原因。 + ----- @@ -74,7 +78,11 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 | [`src/compare.ts`](src/compare.ts) | 经 compare API 读取两个提交之间的补丁,供所有 diff 读取共用 | | [`src/threads.ts`](src/threads.ts) | 读取评审讨论、分页,并映射到 head 位置与原始位置 | | [`src/review-writes.ts`](src/review-writes.ts) | head 检查,以及评审讨论与待提交评审的 mutation | +| [`src/mutation.ts`](src/mutation.ts) | 发送单个 GraphQL mutation 并判定其结果 | | [`src/gh.ts`](src/gh.ts) | 在宿主上执行 `gh`,清理环境变量并施加限制 | +| [`src/viewed.ts`](src/viewed.ts) | 读取与写入已审阅文件 | +| [`src/overview.ts`](src/overview.ts) | 评审请求、评审者搜索与分支更新 | +| [`src/pull-request-node.ts`](src/pull-request-node.ts) | 在核对过的 head 上读取 pull request 节点 id,供写操作使用 | | [`src/urls.ts`](src/urls.ts) | 解析远端 URL 与 pull request URL,并校验写入请求的名称与提交 | diff --git a/packages/experimental/forge-github/src/graphql.ts b/packages/experimental/forge-github/src/graphql.ts index ec97758af6..479c3f3c54 100644 --- a/packages/experimental/forge-github/src/graphql.ts +++ b/packages/experimental/forge-github/src/graphql.ts @@ -3,8 +3,8 @@ import type { Branded } from '@deepseek-ai/dsh-brand' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, ForgeRepository, - Mergeability, MergeMethod, ReviewDecision, + ChangeRequestCheck, ChangeRequestKey, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, CheckState, ChecksRollup, + ForgeCheckId, ForgeFailure, ForgeRepository, Mergeability, MergeMethod, ReviewDecision, ReviewVerdict, } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' import { checkedRepository, isCommit } from './urls.ts' @@ -14,7 +14,7 @@ const CHECK_FIELDS = `pageInfo { hasNextPage endCursor } __typename ... on CheckRun { id databaseId name status conclusion detailsUrl startedAt completedAt - checkSuite { app { id } workflowRun { event workflow { id name } } } + checkSuite { app { id } workflowRun { databaseId event workflow { id name } } } } ... on StatusContext { context state targetUrl createdAt } }` @@ -24,6 +24,11 @@ const PAGE_SIZE = 100 const THREAD_FIELDS = 'pageInfo { hasNextPage endCursor } nodes { isResolved }' +/** Most review requests, reviews per kind, and closing issues one snapshot reads. */ +const OVERVIEW_PAGE = 25 + +const REVIEW_FIELDS = 'totalCount nodes { state commit { oid } author { __typename login avatarUrl } }' + /** * Pull request fields of one snapshot. * @param threads - review threads the first page holds, at most {@link PAGE_SIZE}. @@ -32,8 +37,15 @@ const THREAD_FIELDS = 'pageInfo { hasNextPage endCursor } nodes { isResolved }' function pullRequestFields(threads: number): string { return `id number url title state isDraft updatedAt closedAt author { login } - headRefName headRefOid baseRefName baseRefOid additions deletions mergeable mergeStateStatus reviewDecision + headRefName headRefOid baseRefName baseRefOid additions deletions mergeable mergeStateStatus reviewDecision viewerCanUpdateBranch + canBeRebased reviewThreads(first: ${threads}) { ${THREAD_FIELDS} } + reviewRequests(first: ${OVERVIEW_PAGE}) { totalCount nodes { asCodeOwner requestedReviewer { + __typename ... on User { login avatarUrl } ... on Bot { login avatarUrl } ... on Team { combinedSlug avatarUrl } + } } } + latestReviews(first: ${OVERVIEW_PAGE}) { ${REVIEW_FIELDS} } + latestOpinionatedReviews(first: ${OVERVIEW_PAGE}) { ${REVIEW_FIELDS} } + closingIssuesReferences(first: ${OVERVIEW_PAGE}) { totalCount nodes { number title state url repository { name owner { login } } } } commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: ${PAGE_SIZE}) { ${CHECK_FIELDS} } } } } }` @@ -76,7 +88,11 @@ const checkRunSchema = z.object({ completedAt: z.string().nullable(), checkSuite: z.object({ app: z.object({ id: z.string() }).nullable(), - workflowRun: z.object({ event: z.string(), workflow: z.object({ id: z.string(), name: z.string() }) }).nullable(), + workflowRun: z.object({ + databaseId: z.number().int().nonnegative().nullable(), + event: z.string(), + workflow: z.object({ id: z.string(), name: z.string() }), + }).nullable(), }).nullable(), }) @@ -120,6 +136,13 @@ export interface SnapshotPages { readonly checks?: (id: RollupId, cursor: string) => Promise } +const actorSchema = z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }) + +const reviewsSchema = z.object({ + totalCount: z.number().int().nonnegative(), + nodes: z.array(z.object({ state: z.string(), commit: z.object({ oid: z.string() }).nullable(), author: actorSchema.nullable() })), +}) + const pullRequestSchema = z.object({ id: z.string().transform(value => value as PullRequestId), url: z.string(), @@ -139,7 +162,33 @@ const pullRequestSchema = z.object({ mergeable: z.string(), mergeStateStatus: z.string(), reviewDecision: z.string().nullable(), + viewerCanUpdateBranch: z.boolean(), + canBeRebased: z.boolean(), reviewThreads: threadPageSchema, + reviewRequests: z.object({ + totalCount: z.number().int().nonnegative(), + nodes: z.array(z.object({ + asCodeOwner: z.boolean(), + requestedReviewer: z.object({ + __typename: z.string(), + login: z.string().optional(), + combinedSlug: z.string().optional(), + avatarUrl: z.string().nullable().optional(), + }).nullable(), + })), + }), + latestReviews: reviewsSchema, + latestOpinionatedReviews: reviewsSchema, + closingIssuesReferences: z.object({ + totalCount: z.number().int().nonnegative(), + nodes: z.array(z.object({ + number: z.number().int().positive(), + title: z.string(), + state: z.string(), + url: z.string(), + repository: z.object({ name: z.string(), owner: z.object({ login: z.string() }) }), + })), + }), commits: z.object({ nodes: z.array(z.object({ commit: z.object({ @@ -199,9 +248,17 @@ type RepositoryNode = z.infer /** GitHub merge states in which the merge button works: mergeable, with passing or non-required failing checks. */ const MERGEABLE_NOW: ReadonlySet = new Set(['CLEAN', 'HAS_HOOKS', 'UNSTABLE']) -/** Repository permissions that may merge. */ +/** Repository permissions that may merge and rerun workflow jobs. */ const MERGERS: ReadonlySet = new Set(['ADMIN', 'MAINTAIN', 'WRITE']) +/** Repository permissions that may request reviews. */ +const TRIAGERS: ReadonlySet = new Set(['ADMIN', 'MAINTAIN', 'WRITE', 'TRIAGE']) + +/** Outcome of a submitted review by GitHub state; a pending review is not submitted. */ +const VERDICTS: Readonly> = { + APPROVED: 'approved', CHANGES_REQUESTED: 'changes-requested', COMMENTED: 'commented', DISMISSED: 'dismissed', +} + /** Merge methods in menu order, with the repository setting that allows each and GitHub's name for it. */ const METHODS: readonly { readonly method: MergeMethod @@ -433,6 +490,7 @@ function toSnapshot( workflow: run.data.checkSuite?.workflowRun?.workflow.name ?? null, startedAt: run.data.startedAt, completedAt: run.data.completedAt, + rerun: workflow?.databaseId == null ? null : actionsRun(workflow.databaseId), }) continue } @@ -445,6 +503,7 @@ function toSnapshot( workflow: null, startedAt: null, completedAt: null, + rerun: null, }) } else if (typeof context === 'object' && context !== null && '__typename' in context && (context.__typename === 'CheckRun' || context.__typename === 'StatusContext')) { @@ -458,6 +517,8 @@ function toSnapshot( const summary: ChecksRollup = rollup?.contexts.pageInfo.hasNextPage || unknownContext || checks.length === 0 ? checksRollup(rollup?.state) : checks.some(check => check.state === 'failure' || check.state === 'cancelled') ? 'failure' : checks.some(check => check.state === 'pending') ? 'pending' : 'success' + const permission = settings?.viewerPermission ?? '' + const open = node.state === 'OPEN' return { ref, url: node.url, @@ -475,17 +536,83 @@ function toSnapshot( mergeReady: settings !== undefined && MERGERS.has(settings.viewerPermission ?? '') && node.state === 'OPEN' && !node.isDraft && MERGEABLE_NOW.has(node.mergeStateStatus), mergeMethods: settings === undefined ? [] : mergeMethods(settings), + branchUpdates: !open || !node.viewerCanUpdateBranch || node.mergeable === 'CONFLICTING' ? [] + : node.canBeRebased ? ['merge', 'rebase'] : ['merge'], reviewDecision: reviewDecision(node.reviewDecision), + reviewers: reviewersOf(node), + reviewersTruncated: [node.reviewRequests, node.latestReviews, node.latestOpinionatedReviews] + .some(connection => connection.totalCount > connection.nodes.length), + canRequestReviews: open && TRIAGERS.has(permission), checks, checksRollup: summary, checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false, + canRerunChecks: MERGERS.has(permission), unresolvedThreads: node.reviewThreads.nodes.filter(thread => !thread.isResolved).length, threadsTruncated: node.reviewThreads.pageInfo.hasNextPage, + closingIssues: node.closingIssuesReferences.nodes.map(issue => ({ + repository: { + forge: ref.repository.forge, host: ref.repository.host, owner: issue.repository.owner.login, name: issue.repository.name, + }, + number: issue.number, + title: issue.title, + state: issue.state === 'OPEN' ? 'open' as const : 'closed' as const, + url: issue.url, + })), + closingIssuesTruncated: node.closingIssuesReferences.totalCount > node.closingIssuesReferences.nodes.length, updatedAt: node.updatedAt, closedAt: node.closedAt, } } +/** + * The requested reviewers in host order, then the other accounts that submitted a review, each with their latest + * outcome. An approval or change request outlasts later comments, as GitHub's reviewer list shows it; the author and + * accounts GitHub does not name are left out. + */ +function reviewersOf(node: PullRequestNode): ChangeRequestReviewer[] { + const reviewers = new Map() + const keyOf = (kind: ChangeRequestReviewer['kind'], login: string): string => `${kind}:${login.toLowerCase()}` + for (const request of node.reviewRequests.nodes) { + const reviewer = request.requestedReviewer + const kind = reviewer?.__typename === 'User' ? 'user' : reviewer?.__typename === 'Bot' ? 'bot' : reviewer?.__typename === 'Team' ? 'team' : undefined + const login = kind === 'team' ? reviewer?.combinedSlug : reviewer?.login + if (kind === undefined || login === undefined) continue + reviewers.set(keyOf(kind, login), { + kind, login, avatarUrl: reviewer?.avatarUrl ?? null, requested: true, codeOwner: request.asCodeOwner, + verdict: null, reviewedSha: null, + }) + } + const author = node.author?.login.toLowerCase() + for (const review of [...node.latestReviews.nodes, ...node.latestOpinionatedReviews.nodes]) { + const verdict = VERDICTS[review.state] + const account = review.author + if (verdict === undefined || account === null || account.login.toLowerCase() === author) continue + const kind = account.__typename === 'Bot' ? 'bot' : 'user' + const key = keyOf(kind, account.login) + const known = reviewers.get(key) + reviewers.set(key, { + kind, login: account.login, avatarUrl: known?.avatarUrl ?? account.avatarUrl, requested: known?.requested ?? false, + codeOwner: known?.codeOwner ?? false, verdict, reviewedSha: review.commit?.oid ?? null, + }) + } + return [...reviewers.values()] +} + +/** The rerun identity of a GitHub Actions job: the database id of its workflow run, which reruns its failed jobs. */ +function actionsRun(run: number): ForgeCheckId { + return `actions:${run}` as ForgeCheckId +} + +/** + * Read the workflow run database id from a check's rerun identity. + * @param id - identity a snapshot of this provider named. + * @returns the workflow run id, or undefined for an identity this provider did not build. + */ +export function actionsRunOf(id: ForgeCheckId): number | undefined { + const match = /^actions:(\d{1,15})$/.exec(id) + return match === null ? undefined : Number(match[1]) +} + /** The methods the repository allows, the viewer's default first. */ function mergeMethods(settings: RepositoryNode): MergeMethod[] { const allowed = METHODS.filter(entry => settings[entry.allowed]) diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index 3235e030a3..aa5b5776f2 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -27,6 +27,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 } export const Config: z = z.object({ @@ -36,6 +38,7 @@ export const Config: z = z.object({ maxOutputBytes: z.number().default(8_388_608), maxReviewThreads: z.number().default(1_000), maxCommits: z.number().default(250), + maxViewedFiles: z.number().default(3_000), }) const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i @@ -50,7 +53,7 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } - for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits'] as const) { + for (const key of ['maxOutputBytes', 'maxReviewThreads', 'maxCommits', 'maxViewedFiles'] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved)) diff --git a/packages/experimental/forge-github/src/mutation.ts b/packages/experimental/forge-github/src/mutation.ts new file mode 100644 index 0000000000..0261f8d6e3 --- /dev/null +++ b/packages/experimental/forge-github/src/mutation.ts @@ -0,0 +1,86 @@ +/** GitHub GraphQL mutations sent once through `gh`, with the document and variables as JSON on standard input. */ + +import type { ForgeActionFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts' + +/** HTTP statuses that mean GitHub refused the request, so it changed nothing. */ +const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/ + +/** + * GraphQL error types that mean GitHub refused a mutation before applying it. An error without one of them, such as + * GitHub's "Something went wrong … may be the result of a timeout", leaves the outcome unknown. + */ +const REFUSALS: ReadonlySet = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES', 'NOT_FOUND', 'RATE_LIMITED', 'UNPROCESSABLE']) + +const graphqlErrors = z.object({ errors: z.array(z.object({ message: z.string(), type: z.string().optional() })).min(1) }) + +/** One mutation and the payload field that holds its result. */ +export interface GraphqlMutation { + /** GraphQL document with one mutation field. */ + readonly query: string + /** Name of the mutation field, which holds the payload once GitHub applied the mutation. */ + readonly field: string + /** Variables of the document. */ + readonly variables: Readonly> +} + +/** + * A mutation's result: the payload once GitHub applied it; else `failed` when GitHub refused it or `gh` could not start, + * so nothing changed, or `unknown` when the mutation may have been applied and must be checked on GitHub. + */ +export type MutationResult = + | { readonly ok: true; readonly payload: unknown } + | { readonly ok: false; readonly code: 'failed' | 'unknown'; readonly message: string } + +/** + * Runs one mutation on `host` through {@link sendMutation}; resolves to undefined once GitHub applied it, or to a + * `failed` action failure when GitHub refused it or did not confirm it. + */ +export type GraphqlWriter = (host: string, mutation: GraphqlMutation, signal: AbortSignal) => Promise + +/** + * Send one mutation with its query and variables as JSON on stdin. The mutation is never retried. + * @param gh - runs `gh` on the Host. + * @param host - GitHub host the mutation goes to. + * @param mutation - the document, its field, and its variables. + * @param signal - cancellation of the request. + * @returns the payload of `mutation.field`; `failed` when GitHub reports a refusal by its HTTP status or GraphQL error + * type, or `gh` cannot start, else `unknown`. + */ +export async function sendMutation(gh: GhRunner, host: string, mutation: GraphqlMutation, signal: AbortSignal): Promise { + let output: GhOutput + try { + output = await gh(['api', 'graphql', '--hostname', host, '--input', '-'], signal, + JSON.stringify({ query: mutation.query, variables: mutation.variables })) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { ok: false, code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message } + } + const body = parse(output.stdout) + // A payload means GitHub applied the mutation, even beside errors about the fields it selects. + const payload = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body) + const value = payload.success ? payload.data.data[mutation.field] : undefined + if (value !== undefined && value !== null) return { ok: true, payload: value } + const errors = graphqlErrors.safeParse(body) + if (errors.success) { + const refused = errors.data.errors.every(error => error.type !== undefined && REFUSALS.has(error.type)) + return { ok: false, code: refused ? 'failed' : 'unknown', message: errors.data.errors.map(error => error.message).join('; ') } + } + if (output.exitCode !== 0) { + const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}` + return { ok: false, code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message } + } + return { ok: false, code: 'unknown', message: `unexpected GitHub response to ${mutation.field}` } +} + +function parse(text: string): unknown { + let value: unknown + try { + value = JSON.parse(text) + } catch (error) { + void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers. + return undefined + } + return value +} diff --git a/packages/experimental/forge-github/src/overview.ts b/packages/experimental/forge-github/src/overview.ts new file mode 100644 index 0000000000..afba1a1e60 --- /dev/null +++ b/packages/experimental/forge-github/src/overview.ts @@ -0,0 +1,128 @@ +/** GitHub writes and reads of the change request overview: review requests, reviewer candidates, and branch updates. */ + +import type { + BranchUpdateRequest, ChangeRequestRef, ForgeActionFailure, ForgeFailure, ForgeReviewerCandidate, ForgeReviewersRequest, +} from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import type { GraphqlWriter } from './mutation.ts' +import { pullRequestNode } from './pull-request-node.ts' +import { checkedRepository, isCommit } from './urls.ts' + +/** Add review requests by login; variable `input` is a `RequestReviewsByLoginInput`. */ +export const REQUEST_REVIEWS_MUTATION = `mutation($input: RequestReviewsByLoginInput!) { + requestReviewsByLogin(input: $input) { clientMutationId } +}` + +/** Merge or rebase the base branch into the head branch; variable `input` is an `UpdatePullRequestBranchInput`. */ +export const UPDATE_BRANCH_MUTATION = `mutation($input: UpdatePullRequestBranchInput!) { + updatePullRequestBranch(input: $input) { clientMutationId } +}` + +/** Most accounts one candidate listing returns. */ +const CANDIDATES = 20 + +/** Accounts that can review and GitHub's suggestions; variables `owner`, `name`, and `search` are strings, `number` is an integer. */ +export const CANDIDATES_QUERY = `query($owner: String!, $name: String!, $number: Int!, $search: String!) { + repository(owner: $owner, name: $name) { + assignableUsers(first: ${CANDIDATES}, query: $search) { nodes { login name avatarUrl } } + pullRequest(number: $number) { author { login } suggestedReviewers { reviewer { login name avatarUrl } } } + } +}` + +const account = z.object({ login: z.string(), name: z.string().nullable(), avatarUrl: z.string().nullable() }) + +const candidatesSchema = z.object({ + data: z.object({ + repository: z.object({ + assignableUsers: z.object({ nodes: z.array(account) }), + pullRequest: z.object({ + author: z.object({ login: z.string() }).nullable(), + suggestedReviewers: z.array(z.object({ reviewer: account })), + }).nullable(), + }).nullable(), + }), +}) + +/** + * Request reviews by login with `requestReviewsByLogin`, adding to the requests GitHub holds; a bot is named with + * GitHub's `[bot]` suffix and a team by `organization/slug`. + * @param read - runs one GraphQL query. + * @param write - runs one GraphQL mutation. + * @param ref - pull request address. + * @param request - the reviewers to ask. + * @param signal - cancellation of both requests. + * @returns undefined once GitHub accepted the request, or why it refused. + */ +export async function requestGitHubReviews( + read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, +): Promise { + if (request.reviewers.length === 0) return { code: 'failed', message: 'No reviewer was named' } + const id = await pullRequestNode(read, ref, null, signal) + if (typeof id !== 'string') return id + const logins = (kind: string): string[] => request.reviewers.filter(reviewer => reviewer.kind === kind).map(reviewer => reviewer.login) + const input: Record = { pullRequestId: id, union: true } + const users = logins('user') + const bots = logins('bot').map(login => login.endsWith('[bot]') ? login : `${login}[bot]`) + const teams = logins('team') + if (users.length > 0) input.userLogins = users + if (bots.length > 0) input.botLogins = bots + if (teams.length > 0) input.teamSlugs = teams + return await write(ref.repository.host, { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviewsByLogin', variables: { input } }, signal) +} + +/** + * Update the head branch with `updatePullRequestBranch`. The head is read first and the update is refused once it is + * another commit; GitHub also checks `expectedHeadOid` itself. + * @param read - runs one GraphQL query. + * @param write - runs one GraphQL mutation. + * @param ref - pull request address. + * @param request - update method and the head commit the user confirmed. + * @param signal - cancellation of both requests. + * @returns undefined once GitHub accepted the update, `stale` when the head moved, or why GitHub refused. + * @throws when `request.headSha` is not a full commit object name. + */ +export async function updateGitHubBranch( + read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal, +): Promise { + if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`) + const id = await pullRequestNode(read, ref, request.headSha, signal) + if (typeof id !== 'string') return id + return await write(ref.repository.host, { query: UPDATE_BRANCH_MUTATION, field: 'updatePullRequestBranch', variables: { + input: { pullRequestId: id, expectedHeadOid: request.headSha, updateMethod: request.method === 'rebase' ? 'REBASE' : 'MERGE' }, + } }, signal) +} + +/** + * List accounts a review can be requested from: GitHub's suggestions for the pull request when `query` is empty, then + * the accounts that can be assigned in the repository whose login or name matches `query`, without the author. + * @param read - runs one GraphQL query. + * @param ref - pull request address. + * @param query - text the login or name contains. + * @param signal - cancellation of the read. + * @returns at most 20 accounts, each once, or why GitHub did not list them. + */ +export async function gitHubReviewerCandidates( + read: GraphqlReader, ref: ChangeRequestRef, query: string, signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const search = query.trim() + const body = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${CANDIDATES_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-f', `search=${search}`, + ], signal) + if (!body.ok) return body.failure + const parsed = candidatesSchema.safeParse(body.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the reviewer listing' } + const repository = parsed.data.data.repository + if (repository === null) return { code: 'not-found', message: `repository ${owner}/${name} is not visible` } + const author = repository.pullRequest?.author?.login.toLowerCase() + const listed = new Map() + const add = (entry: z.infer, suggested: boolean): void => { + const key = entry.login.toLowerCase() + if (key !== author && !listed.has(key)) listed.set(key, { login: entry.login, name: entry.name, avatarUrl: entry.avatarUrl, suggested }) + } + if (search === '') for (const suggestion of repository.pullRequest?.suggestedReviewers ?? []) add(suggestion.reviewer, true) + for (const user of repository.assignableUsers.nodes) add(user, false) + return [...listed.values()].slice(0, CANDIDATES) +} diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index bd99a59cf6..f3aca26627 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -2,22 +2,25 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, - ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, - MergeRequest, + BranchUpdateRequest, ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, + ForgeProvider, ForgeReadiness, ForgeRepository, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewersRequest, + ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import { listCommits } from './commits.ts' import type { GraphqlReader } from './commits.ts' +import { sendMutation, type GraphqlWriter } from './mutation.ts' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts' import type { GhOutput, GhRunner } from './gh.ts' import { readComparison } from './compare.ts' import { - CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse, + actionsRunOf, CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse, mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY, } from './graphql.ts' import type { PageResult, SnapshotPages } from './graphql.ts' import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' +import { readViewed, writeViewed } from './viewed.ts' +import { gitHubReviewerCandidates, requestGitHubReviews, updateGitHubBranch } from './overview.ts' import { writeGitHubReview } from './review-writes.ts' import { readReviewThreads } from './threads.ts' @@ -43,6 +46,8 @@ export interface GitHubLimits { readonly maxReviewThreads: number /** Most commits one commit listing returns. */ readonly maxCommits: number + /** Most files whose viewed marks one read lists. */ + readonly maxViewedFiles: number } /** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */ @@ -81,7 +86,8 @@ export class GitHubProvider implements ForgeProvider { /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. - * @param limits - bounds on retained check and review bytes, counted and read review threads, and listed commits. + * @param limits - bounds on retained check and review bytes, counted and read review threads, listed commits, and listed + * viewed files. */ constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) @@ -251,6 +257,70 @@ export class GitHubProvider implements ForgeProvider { return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal) } + /** Read the viewer's viewed marks through GraphQL, at most `maxViewedFiles`, every page at `headSha`. */ + async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return failure + return await readViewed(this.graphql, ref, headSha, this.limits.maxViewedFiles, signal) + } + + /** Set or clear the viewer's mark with `markFileAsViewed` or `unmarkFileAsViewed` after confirming the head. */ + async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return { code: 'failed', message: failure.message } + return await writeViewed(this.graphql, this.mutate, ref, request, signal) + } + + /** + * Rerun every workflow run with a failed GitHub Actions job on the head commit through the REST API; GitHub reruns + * its failed jobs with the jobs that depend on them. Other checks name no rerun. + */ + async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise { + const { host, owner, name } = checkedRepository(ref) + const failure = this.hostFailure(host) + if (failure !== undefined) return { code: 'failed', message: failure.message } + if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`) + const snapshot = await this.fetchChecks(ref, signal) + if ('code' in snapshot) return { code: snapshot.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: snapshot.message } + if (snapshot.headSha.toLowerCase() !== request.headSha.toLowerCase()) { + return { code: 'stale', message: `the pull request head moved from ${request.headSha} to ${snapshot.headSha}` } + } + const endpoint = `repos/${owner}/${name}/actions` + const runs = new Set() + for (const check of snapshot.checks) { + const run = check.state === 'failure' && check.rerun !== null ? actionsRunOf(check.rerun) : undefined + if (run !== undefined) runs.add(run) + } + if (runs.size === 0) return { code: 'failed', message: 'No failed GitHub Actions job of the head commit can be rerun' } + for (const run of runs) { + const refused = await this.act(['api', '--hostname', host, '--method', 'POST', `${endpoint}/runs/${run}/rerun-failed-jobs`], signal) + if (refused !== undefined) return refused + } + return undefined + } + + async requestReviews( + ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, + ): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return { code: 'failed', message: failure.message } + return await requestGitHubReviews(this.graphql, this.mutate, ref, request, signal) + } + + async reviewerCandidates( + ref: ChangeRequestRef, query: string, signal: AbortSignal, + ): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return failure + return await gitHubReviewerCandidates(this.graphql, ref, query, signal) + } + + async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise { + const failure = this.hostFailure(checkedRepository(ref).host) + if (failure !== undefined) return { code: 'failed', message: failure.message } + return await updateGitHubBranch(this.graphql, this.mutate, ref, request, signal) + } + fileUrl(ref: ChangeRequestRef, commit: string, path: string): string { const { host, owner, name } = ref.repository return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}` @@ -301,6 +371,16 @@ export class GitHubProvider implements ForgeProvider { return { ok: true, body } } + /** + * Run one GraphQL mutation with its query and variables as JSON on standard input, never in arguments. A refusal, a + * `gh` that cannot start, a body that is not GraphQL, and GraphQL errors become failures; the write is never retried. + */ + /** Every refusal and every unconfirmed outcome fails: these mutations set a state, so trying again is safe. */ + private readonly mutate: GraphqlWriter = async (host, mutation, signal) => { + const sent = await sendMutation(this.gh, host, mutation, signal) + return sent.ok ? undefined : { code: 'failed', message: sent.message } + } + /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */ private async act(args: readonly string[], signal: AbortSignal): Promise { const output = await this.attempt(args, signal) diff --git a/packages/experimental/forge-github/src/pull-request-node.ts b/packages/experimental/forge-github/src/pull-request-node.ts new file mode 100644 index 0000000000..4f155f5e1a --- /dev/null +++ b/packages/experimental/forge-github/src/pull-request-node.ts @@ -0,0 +1,42 @@ +/** The node id of a pull request that a GraphQL mutation names, read together with the head the write must still find. */ + +import type { ChangeRequestRef, ForgeActionFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import { checkedRepository } from './urls.ts' + +/** Node id and head commit of one pull request; variables `owner` and `name` are strings, `number` is an integer. */ +export const PULL_REQUEST_NODE_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid } } +}` + +const nodeSchema = z.object({ + data: z.object({ repository: z.object({ pullRequest: z.object({ id: z.string(), headRefOid: z.string() }).nullable() }).nullable() }), +}) + +/** + * Read a pull request's node id before a write, refusing once its head is not `headSha`. + * @param read - runs one GraphQL query. + * @param ref - pull request address. + * @param headSha - head commit the write must still find, or null for a write that does not depend on the head. + * @param signal - cancellation of the read. + * @returns the node id, `stale` when the head moved, or why the write must not proceed. + */ +export async function pullRequestNode( + read: GraphqlReader, ref: ChangeRequestRef, headSha: string | null, signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const node = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${PULL_REQUEST_NODE_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, + ], signal) + if (!node.ok) return { code: node.failure.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: node.failure.message } + const parsed = nodeSchema.safeParse(node.body) + if (!parsed.success) return { code: 'failed', message: 'unexpected GitHub response to the pull request read' } + const pull = parsed.data.data.repository?.pullRequest + if (pull == null) return { code: 'failed', message: `pull request ${ref.number} was not found` } + if (headSha !== null && pull.headRefOid.toLowerCase() !== headSha.toLowerCase()) { + return { code: 'stale', message: `the pull request head moved from ${headSha} to ${pull.headRefOid}` } + } + return pull.id +} diff --git a/packages/experimental/forge-github/src/review-writes.ts b/packages/experimental/forge-github/src/review-writes.ts index 86ae145d91..00a2cde7d8 100644 --- a/packages/experimental/forge-github/src/review-writes.ts +++ b/packages/experimental/forge-github/src/review-writes.ts @@ -6,7 +6,8 @@ import type { import { assertNever } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import type { GraphqlReader } from './commits.ts' -import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts' +import type { GhRunner } from './gh.ts' +import { sendMutation, type GraphqlMutation, type MutationResult } from './mutation.ts' import { checkedRepository } from './urls.ts' /** @@ -68,15 +69,6 @@ export const DELETE_REVIEW_MUTATION = 'mutation($review: ID!) { deletePullReques const EVENTS = { comment: 'COMMENT', approve: 'APPROVE', 'request-changes': 'REQUEST_CHANGES' } as const -/** HTTP statuses that mean GitHub refused the request, so it changed nothing. */ -const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/ - -/** - * GraphQL error types that mean GitHub refused a mutation before applying it. An error without one of them, such as - * GitHub's "Something went wrong … may be the result of a timeout", leaves the outcome unknown. - */ -const REFUSALS: ReadonlySet = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES', 'NOT_FOUND', 'RATE_LIMITED', 'UNPROCESSABLE']) - const checkSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ id: z.string(), @@ -86,18 +78,6 @@ const checkSchema = z.object({ data: z.object({ target: z.object({ pullRequest: z.object({ id: z.string() }).optional() }).nullable().optional(), }) }) -const graphqlErrors = z.object({ errors: z.array(z.object({ message: z.string(), type: z.string().optional() })).min(1) }) - -/** One mutation and the payload field that holds its result. */ -interface Mutation { - readonly query: string - readonly field: string - readonly variables: Readonly> -} - -/** A mutation's result: the payload on success, else the write's outcome. */ -type Sent = { readonly ok: true; readonly payload: unknown } | Extract - const stringId = z.object({ id: z.string() }) /** @@ -136,10 +116,10 @@ export async function writeGitHubReview( } const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)?.id ?? null signal.throwIfAborted() - const send = async (mutation: Mutation): Promise => await sendMutation(gh, host, mutation, signal) - const done = (sent: Sent): ForgeReviewWriteResult => sent.ok ? { ok: true } : sent + const send = async (mutation: GraphqlMutation): Promise => await sendMutation(gh, host, mutation, signal) + const done = (sent: MutationResult): ForgeReviewWriteResult => sent.ok ? { ok: true } : sent /** Find the pending review, starting one at the head without threads when the user has none. */ - const pendingReview = async (): Promise<{ readonly ok: true; readonly id: string } | Extract> => { + const pendingReview = async (): Promise<{ readonly ok: true; readonly id: string } | Extract> => { if (pending !== null) return { ok: true, id: pending } const started = await send({ query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview', variables: { pull: pull.id, commit: write.headSha, threads: null } }) @@ -210,45 +190,3 @@ function draftThread(comment: ForgeLineComment): Readonly { - let output: GhOutput - try { - output = await gh(['api', 'graphql', '--hostname', host, '--input', '-'], signal, - JSON.stringify({ query: mutation.query, variables: mutation.variables })) - } catch (error) { - const message = error instanceof Error ? error.message : String(error) - return { ok: false, code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message } - } - const body = parse(output.stdout) - // A payload means GitHub applied the mutation, even beside errors about the fields it selects. - const payload = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body) - const value = payload.success ? payload.data.data[mutation.field] : undefined - if (value !== undefined && value !== null) return { ok: true, payload: value } - const errors = graphqlErrors.safeParse(body) - if (errors.success) { - const refused = errors.data.errors.every(error => error.type !== undefined && REFUSALS.has(error.type)) - return { ok: false, code: refused ? 'failed' : 'unknown', message: errors.data.errors.map(error => error.message).join('; ') } - } - if (output.exitCode !== 0) { - const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}` - return { ok: false, code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message } - } - return { ok: false, code: 'unknown', message: `unexpected GitHub response to ${mutation.field}` } -} - -function parse(text: string): unknown { - let value: unknown - try { - value = JSON.parse(text) - } catch (error) { - void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers. - return undefined - } - return value -} diff --git a/packages/experimental/forge-github/src/viewed.ts b/packages/experimental/forge-github/src/viewed.ts new file mode 100644 index 0000000000..f9cedeeddf --- /dev/null +++ b/packages/experimental/forge-github/src/viewed.ts @@ -0,0 +1,128 @@ +/** The signed-in user's viewed marks on pull request files through GraphQL, pinned to one head commit. */ + +import type { + ChangeRequestRef, ForgeActionFailure, ForgeFailure, ForgeViewedFiles, ForgeViewedRequest, ForgeViewedState, +} from '@deepseek-ai/dsh-experimental-forge' +import { pullRequestNode } from './pull-request-node.ts' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import type { GraphqlWriter } from './mutation.ts' +import { checkedRepository, isCommit } from './urls.ts' + +/** Files GitHub returns per GraphQL page, its connection maximum. */ +const PAGE = 100 + +/** One page of a pull request's files with the viewer's marks and its head; `cursor` continues after the previous page. */ +export const VIEWED_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + headRefOid + files(first: $first, after: $cursor) { totalCount pageInfo { hasNextPage endCursor } nodes { path viewerViewedState } } + } + } +}` + +/** Mark one file viewed; variables `id` (pull request node id) and `path`, sent on standard input. */ +export const MARK_VIEWED_MUTATION = `mutation($id: ID!, $path: String!) { + markFileAsViewed(input: { pullRequestId: $id, path: $path }) { clientMutationId } +}` + +/** Clear one file's viewed mark; variables `id` (pull request node id) and `path`, sent on standard input. */ +export const UNMARK_VIEWED_MUTATION = `mutation($id: ID!, $path: String!) { + unmarkFileAsViewed(input: { pullRequestId: $id, path: $path }) { clientMutationId } +}` + +const STATES: Readonly> = { VIEWED: 'viewed', UNVIEWED: 'unviewed', DISMISSED: 'dismissed' } + +const pageSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ + headRefOid: z.string(), + files: z.object({ + totalCount: z.number().int().nonnegative(), + pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), + nodes: z.array(z.object({ path: z.string(), viewerViewedState: z.string() })), + }).nullable(), + }).nullable(), + }).nullable(), + }), +}) + +/** + * Read the viewer's marks on a pull request's files, at most `limit`, reading pages until the limit or the last file. + * Every page must name `headSha` as the head, so the marks never mix two pushes, and a cursor no earlier page returned, + * so the listing ends. A state GitHub adds later reads as `unviewed`. + * @param read - runs one GraphQL request. + * @param ref - pull request address. + * @param headSha - head commit the marks must be read at. + * @param limit - most files listed. + * @param signal - cancellation of every page. + * @returns the marks at `headSha`, `stale` once the head is another commit, or why GitHub did not list them. + * @throws when `headSha` is not a full commit object name. + */ +export async function readViewed( + read: GraphqlReader, + ref: ChangeRequestRef, + headSha: string, + limit: number, + signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`) + const files: Record = {} + let listed = 0 + const cursors = new Set() + let cursor: string | null = null + for (;;) { + const body = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${VIEWED_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE, limit - listed)}`, ...cursor === null ? [] : ['-f', `cursor=${cursor}`], + ], signal) + if (!body.ok) return body.failure + const parsed = pageSchema.safeParse(body.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the viewed file read' } + const pull = parsed.data.data.repository?.pullRequest + if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` } + if (pull.headRefOid.toLowerCase() !== headSha.toLowerCase()) { + return { code: 'stale', message: `the pull request head moved from ${headSha} to ${pull.headRefOid}` } + } + // GitHub answers null for the files of a pull request whose diff it cannot list. + if (pull.files === null) return { code: 'unavailable', message: 'GitHub did not list the pull request files' } + const { totalCount, pageInfo: { hasNextPage, endCursor }, nodes } = pull.files + for (const node of nodes) files[node.path] = STATES[node.viewerViewedState] ?? 'unviewed' + listed += nodes.length + if (!hasNextPage || listed >= limit) return { headSha: pull.headRefOid, files, truncated: totalCount > listed } + if (endCursor === null || cursors.has(endCursor)) return { code: 'unavailable', message: 'GitHub file pagination did not advance' } + cursors.add(endCursor) + cursor = endCursor + } +} + +/** + * Set or clear the viewer's mark on one file. GitHub's mutations take no head commit, so the pull request head is read + * first and the write is refused once it is another commit; a push between that read and the write leaves the mark on + * the file as the new head has it. + * @param read - runs one GraphQL query. + * @param write - runs one GraphQL mutation. + * @param ref - pull request address. + * @param request - the file, its mark, and the head commit the user saw. + * @param signal - cancellation of both requests. + * @returns undefined once GitHub saved the mark, `stale` when the head moved, or why GitHub refused. + * @throws when `request.headSha` is not a full commit object name. + */ +export async function writeViewed( + read: GraphqlReader, + write: GraphqlWriter, + ref: ChangeRequestRef, + request: ForgeViewedRequest, + signal: AbortSignal, +): Promise { + if (!isCommit(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`) + const id = await pullRequestNode(read, ref, request.headSha, signal) + if (typeof id !== 'string') return id + const variables = { id, path: request.path } + return await write(ref.repository.host, request.viewed + ? { query: MARK_VIEWED_MUTATION, field: 'markFileAsViewed', variables } + : { query: UNMARK_VIEWED_MUTATION, field: 'unmarkFileAsViewed', variables }, signal) +} diff --git a/packages/experimental/forge-github/tests/fixtures.ts b/packages/experimental/forge-github/tests/fixtures.ts index bc5d1297b0..7ec8fb50ea 100644 --- a/packages/experimental/forge-github/tests/fixtures.ts +++ b/packages/experimental/forge-github/tests/fixtures.ts @@ -18,7 +18,10 @@ export function checkRun(name: string, status: string, conclusion: string | null detailsUrl: `https://github.com/octo/demo/actions/runs/1/job/${name}`, startedAt: status === 'QUEUED' ? null : '2026-10-09T01:00:00Z', completedAt: status === 'COMPLETED' ? '2026-10-09T01:02:07Z' : null, - checkSuite: { app: { id: 'github-actions' }, workflowRun: workflow === null ? null : { event: 'pull_request', workflow: { id: workflow, name: workflow } } }, + checkSuite: { + app: { id: 'github-actions' }, + workflowRun: workflow === null ? null : { databaseId: 7, event: 'pull_request', workflow: { id: workflow, name: workflow } }, + }, } } @@ -60,7 +63,13 @@ export function pullRequestNode(number: number, overrides: Record { mergeability: 'mergeable', mergeReady: true, mergeMethods: ['merge', 'squash'], + branchUpdates: [], reviewDecision: 'none', + reviewers: [], + reviewersTruncated: false, + canRequestReviews: true, checks: [{ name: 'lint', state: 'success', @@ -77,11 +82,15 @@ describe('snapshot mapping', () => { workflow: 'ci', startedAt: '2026-10-09T01:00:00Z', completedAt: '2026-10-09T01:02:07Z', + rerun: 'actions:7', }], checksRollup: 'success', checksTruncated: false, + canRerunChecks: true, unresolvedThreads: 2, threadsTruncated: false, + closingIssues: [], + closingIssuesTruncated: false, updatedAt: '2026-10-09T01:02:03Z', closedAt: null, }) @@ -100,7 +109,7 @@ describe('snapshot mapping', () => { const old = checkRun('build', 'COMPLETED', 'FAILURE') const newer = { ...checkRun('build', 'QUEUED', null), databaseId: 9 } const suite = (app: string, workflow: string, event: string) => ({ app: { id: app }, - workflowRun: { event, workflow: { id: workflow, name: 'CI' } } }) + workflowRun: { databaseId: 7, event, workflow: { id: workflow, name: 'CI' } } }) const result = await single(pullRequestNode(1, {}, [ old, newer, { ...old, databaseId: 2 }, { ...old, checkSuite: suite('github-actions', 'ci', 'push') }, @@ -212,7 +221,7 @@ describe('snapshot mapping', () => { ['EXPECTED', 'pending'], ])('maps status context %s to %s', async (state, expected) => { expect((await single(pullRequestNode(1, {}, [statusContext('deploy', state)]))).checks).toEqual([{ - name: 'deploy', state: expected, url: null, workflow: null, startedAt: null, completedAt: null, + name: 'deploy', state: expected, url: null, workflow: null, startedAt: null, completedAt: null, rerun: null, }]) }) @@ -452,3 +461,95 @@ describe('head branch lookup mapping', () => { expect(() => mapHeadResponse({ data: {} }, demo, 'topic')).toThrow('forge-github: unexpected GitHub response to the head branch lookup') }) }) + +describe('overview mapping', () => { + const user = (login: string) => ({ __typename: 'User', login, avatarUrl: `https://avatars.example/${login}` }) + const review = (state: string, author: unknown, oid: string | null = 'f'.repeat(40)) => ({ state, commit: oid === null ? null : { oid }, author }) + + it('lists requested reviewers in host order, then other reviewers, each with their latest outcome', async () => { + const snapshot = await single(pullRequestNode(1, { + reviewRequests: { totalCount: 4, nodes: [ + { asCodeOwner: false, requestedReviewer: user('lin') }, + { asCodeOwner: true, requestedReviewer: { __typename: 'Team', combinedSlug: 'octo/forge', avatarUrl: null } }, + { asCodeOwner: false, requestedReviewer: { __typename: 'Bot', login: 'copilot', avatarUrl: null } }, + { asCodeOwner: false, requestedReviewer: { __typename: 'Mannequin', login: 'ghost' } }, + { asCodeOwner: false, requestedReviewer: null }, + ] }, + latestReviews: { totalCount: 4, nodes: [ + review('COMMENTED', { __typename: 'Bot', login: 'review-bot', avatarUrl: null }), + review('COMMENTED', user('zhou'), 'e'.repeat(40)), + review('COMMENTED', user('octo')), + review('PENDING', user('qian')), + review('COMMENTED', null), + ] }, + latestOpinionatedReviews: { totalCount: 2, nodes: [review('CHANGES_REQUESTED', user('zhou'), 'e'.repeat(40)), review('APPROVED', user('LIN'), null)] }, + })) + expect(snapshot.reviewers).toEqual([ + { kind: 'user', login: 'LIN', avatarUrl: 'https://avatars.example/lin', requested: true, codeOwner: false, verdict: 'approved', reviewedSha: null }, + { kind: 'team', login: 'octo/forge', avatarUrl: null, requested: true, codeOwner: true, verdict: null, reviewedSha: null }, + { kind: 'bot', login: 'copilot', avatarUrl: null, requested: true, codeOwner: false, verdict: null, reviewedSha: null }, + { kind: 'bot', login: 'review-bot', avatarUrl: null, requested: false, codeOwner: false, verdict: 'commented', reviewedSha: 'f'.repeat(40) }, + { kind: 'user', login: 'zhou', avatarUrl: 'https://avatars.example/zhou', requested: false, codeOwner: false, + verdict: 'changes-requested', reviewedSha: 'e'.repeat(40) }, + ]) + expect(snapshot.reviewersTruncated).toBe(false) + }) + + it.each([ + ['review requests', { reviewRequests: { totalCount: 30, nodes: [] } }], + ['reviews', { latestReviews: { totalCount: 30, nodes: [] } }], + ['opinionated reviews', { latestOpinionatedReviews: { totalCount: 30, nodes: [] } }], + ])('reports more %s than it read as an incomplete reviewer list', async (_label, overrides) => { + expect((await single(pullRequestNode(1, overrides))).reviewersTruncated).toBe(true) + }) + + it.each([ + ['an open, mergeable head the viewer may update', {}, ['merge']], + ['a head that can also be rebased', { canBeRebased: true }, ['merge', 'rebase']], + ['a conflicting head', { mergeable: 'CONFLICTING' }, []], + ['a closed pull request', { state: 'CLOSED' }, []], + ['a head the viewer may not update', { viewerCanUpdateBranch: false }, []], + ])('offers branch updates for %s', async (_label, overrides, updates) => { + expect((await single(pullRequestNode(1, { viewerCanUpdateBranch: true, ...overrides }))).branchUpdates).toEqual(updates) + }) + + it.each([ + ['TRIAGE', 'OPEN', true, false], + ['WRITE', 'OPEN', true, true], + ['READ', 'OPEN', false, false], + ['ADMIN', 'MERGED', false, true], + ])('lets a %s viewer of a %s pull request request reviews: %s, and rerun checks: %s', async (permission, state, requests, reruns) => { + const snapshot = await single(pullRequestNode(1, { state }), repositorySettings({ viewerPermission: permission })) + expect([snapshot.canRequestReviews, snapshot.canRerunChecks]).toEqual([requests, reruns]) + }) + + it('grants neither without readable repository settings', async () => { + const snapshot = await single(pullRequestNode(1), null) + expect([snapshot.canRequestReviews, snapshot.canRerunChecks]).toEqual([false, false]) + }) + + it('names a rerun only for a check of a workflow run with a database id', async () => { + const run = checkRun('lint', 'COMPLETED', 'FAILURE') + const snapshot = await single(pullRequestNode(1, {}, [ + run, + { ...checkRun('test', 'COMPLETED', 'FAILURE'), checkSuite: { app: { id: 'github-actions' }, workflowRun: null } }, + { ...checkRun('e2e', 'COMPLETED', 'FAILURE'), checkSuite: { app: { id: 'github-actions' }, + workflowRun: { databaseId: null, event: 'pull_request', workflow: { id: 'e2e', name: 'e2e' } } } }, + ])) + expect(snapshot.checks.map(check => [check.name, check.rerun])).toEqual([['lint', 'actions:7'], ['test', null], ['e2e', null]]) + expect(actionsRunOf('actions:7' as ForgeCheckId)).toBe(7) + expect(actionsRunOf('status:7' as ForgeCheckId)).toBeUndefined() + }) + + it('maps the linked issues of any repository on the host, noting more than it read', async () => { + const snapshot = await single(pullRequestNode(1, { closingIssuesReferences: { totalCount: 3, nodes: [ + { number: 6, title: 'Show progress', state: 'OPEN', url: 'https://github.com/octo/demo/issues/6', repository: { name: 'demo', owner: { login: 'octo' } } }, + { number: 2, title: 'Rerun', state: 'CLOSED', url: 'https://github.com/octo/tracker/issues/2', repository: { name: 'tracker', owner: { login: 'octo' } } }, + ] } })) + expect(snapshot.closingIssues).toEqual([ + { repository: demo, number: 6, title: 'Show progress', state: 'open', url: 'https://github.com/octo/demo/issues/6' }, + { repository: { ...demo, name: 'tracker' }, number: 2, title: 'Rerun', state: 'closed', url: 'https://github.com/octo/tracker/issues/2' }, + ]) + expect(snapshot.closingIssuesTruncated).toBe(true) + }) +}) diff --git a/packages/experimental/forge-github/tests/overview.spec.ts b/packages/experimental/forge-github/tests/overview.spec.ts new file mode 100644 index 0000000000..6890327d7c --- /dev/null +++ b/packages/experimental/forge-github/tests/overview.spec.ts @@ -0,0 +1,135 @@ +import { describe, expect, it, vi } from 'vitest' +import type { GraphqlReader } from '../src/commits.ts' +import type { GraphqlWriter } from '../src/mutation.ts' +import { + CANDIDATES_QUERY, gitHubReviewerCandidates, REQUEST_REVIEWS_MUTATION, requestGitHubReviews, UPDATE_BRANCH_MUTATION, updateGitHubBranch, +} from '../src/overview.ts' +import { pullRequestNode } from '../src/pull-request-node.ts' +import { pull } from './fixtures.ts' + +const HEAD = 'f'.repeat(40) +const signal = new AbortController().signal + +function reader(...bodies: unknown[]): { read: GraphqlReader; calls: (readonly string[])[] } { + const calls: (readonly string[])[] = [] + return { + calls, + read: async (args) => { + calls.push(args) + const body = bodies.shift() + if (body instanceof Error) return { ok: false, failure: { code: body.message === 'signed out' ? 'unauthenticated' : 'unavailable', message: body.message } } + return { ok: true, body } + }, + } +} + +const node = (headRefOid = HEAD) => ({ data: { repository: { pullRequest: { id: 'PR_7', headRefOid } } } }) + +describe('pull request node reads', () => { + it.each([ + ['a head that moved', node('e'.repeat(40)), HEAD, { code: 'stale', message: `the pull request head moved from ${HEAD} to ${'e'.repeat(40)}` }], + ['an unexpected response', { data: {} }, HEAD, { code: 'failed', message: 'unexpected GitHub response to the pull request read' }], + ['a missing pull request', { data: { repository: { pullRequest: null } } }, HEAD, { code: 'failed', message: 'pull request 7 was not found' }], + ['a missing repository', { data: { repository: null } }, null, { code: 'failed', message: 'pull request 7 was not found' }], + ['a refused read', new Error('rate limited'), null, { code: 'failed', message: 'rate limited' }], + ['a missing sign-in', new Error('signed out'), null, { code: 'unauthenticated', message: 'signed out' }], + ])('refuses %s', async (_label, body, head, failure) => { + await expect(pullRequestNode(reader(body).read, pull(7), head, signal)).resolves.toEqual(failure) + }) + + it('returns the node id at the head, or at any head without one, comparing heads without regard to case', async () => { + await expect(pullRequestNode(reader(node()).read, pull(7), HEAD.toUpperCase(), signal)).resolves.toBe('PR_7') + await expect(pullRequestNode(reader(node('e'.repeat(40))).read, pull(7), null, signal)).resolves.toBe('PR_7') + }) +}) + +describe('review requests', () => { + it('adds users, bots with the bot suffix, and teams by login to the requests GitHub holds', async () => { + const write = vi.fn(async () => undefined) + const reviewers = [ + { kind: 'user' as const, login: 'mona' }, { kind: 'bot' as const, login: 'copilot' }, { kind: 'bot' as const, login: 'helper[bot]' }, + { kind: 'team' as const, login: 'octo/forge' }, + ] + await expect(requestGitHubReviews(reader(node()).read, write, pull(7), { reviewers }, signal)).resolves.toBeUndefined() + expect(write).toHaveBeenCalledWith('github.com', { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviewsByLogin', variables: { input: { + pullRequestId: 'PR_7', union: true, userLogins: ['mona'], botLogins: ['copilot[bot]', 'helper[bot]'], teamSlugs: ['octo/forge'], + } } }, signal) + }) + + it('names only the kinds it requests, at any head', async () => { + const write = vi.fn(async () => ({ code: 'failed', message: 'Could not resolve user' })) + await expect(requestGitHubReviews(reader(node('e'.repeat(40))).read, write, pull(7), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)) + .resolves.toEqual({ code: 'failed', message: 'Could not resolve user' }) + expect(write.mock.calls[0]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, userLogins: ['mona'] } }) + await requestGitHubReviews(reader(node()).read, write, pull(7), { reviewers: [{ kind: 'team', login: 'octo/forge' }] }, signal) + expect(write.mock.calls[1]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, teamSlugs: ['octo/forge'] } }) + }) + + it('refuses an empty request without reading, and a failed node read without writing', async () => { + const write = vi.fn() + const empty = reader() + await expect(requestGitHubReviews(empty.read, write, pull(7), { reviewers: [] }, signal)).resolves.toEqual({ code: 'failed', message: 'No reviewer was named' }) + expect(empty.calls).toEqual([]) + await expect(requestGitHubReviews(reader(new Error('down')).read, write, pull(7), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)) + .resolves.toEqual({ code: 'failed', message: 'down' }) + expect(write).not.toHaveBeenCalled() + }) +}) + +describe('branch updates', () => { + it.each([['merge', 'MERGE'], ['rebase', 'REBASE']] as const)('updates by %s with the confirmed head as GitHub expects it', async (method, updateMethod) => { + const write = vi.fn(async () => undefined) + await expect(updateGitHubBranch(reader(node()).read, write, pull(7), { method, headSha: HEAD }, signal)).resolves.toBeUndefined() + expect(write).toHaveBeenCalledWith('github.com', { query: UPDATE_BRANCH_MUTATION, field: 'updatePullRequestBranch', + variables: { input: { pullRequestId: 'PR_7', expectedHeadOid: HEAD, updateMethod } } }, signal) + }) + + it('refuses a moved head without writing and an invalid head without reading', async () => { + const write = vi.fn() + await expect(updateGitHubBranch(reader(node('e'.repeat(40))).read, write, pull(7), { method: 'merge', headSha: HEAD }, signal)) + .resolves.toMatchObject({ code: 'stale' }) + expect(write).not.toHaveBeenCalled() + const none = reader() + await expect(updateGitHubBranch(none.read, write, pull(7), { method: 'merge', headSha: 'main' }, signal)) + .rejects.toThrow('forge-github: invalid head commit "main"') + expect(none.calls).toEqual([]) + }) +}) + +describe('reviewer candidates', () => { + const account = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null }) + const listing = (suggested: readonly unknown[], users: readonly unknown[], author: unknown = { login: 'Octo' }) => ({ data: { repository: { + assignableUsers: { nodes: users }, + pullRequest: { author, suggestedReviewers: suggested.map(reviewer => ({ reviewer })) }, + } } }) + + it('lists the suggestions first without the author, then the accounts, each once', async () => { + const { read, calls } = reader(listing([account('lin', 'Lin'), account('octo')], [account('LIN'), account('mona', 'Mona'), account('octo')])) + await expect(gitHubReviewerCandidates(read, pull(7), ' ', signal)).resolves.toEqual([ + { login: 'lin', name: 'Lin', avatarUrl: null, suggested: true }, + { login: 'mona', name: 'Mona', avatarUrl: null, suggested: false }, + ]) + expect(calls[0]).toEqual(['api', 'graphql', '--hostname', 'github.com', '-f', `query=${CANDIDATES_QUERY}`, '-f', 'owner=octo', '-f', 'name=demo', + '-F', 'number=7', '-f', 'search=']) + }) + + it('leaves suggestions out of a search and keeps at most twenty accounts', async () => { + const users = Array.from({ length: 25 }, (_, index) => account(`user${index}`)) + const result = await gitHubReviewerCandidates(reader(listing([account('lin')], users, null)).read, pull(7), 'user', signal) + expect('code' in result ? result : result.map(entry => entry.login)).toEqual(users.slice(0, 20).map(user => user.login)) + }) + + it('lists accounts when the pull request is gone', async () => { + const body = { data: { repository: { assignableUsers: { nodes: [account('mona')] }, pullRequest: null } } } + await expect(gitHubReviewerCandidates(reader(body).read, pull(7), '', signal)) + .resolves.toEqual([{ login: 'mona', name: null, avatarUrl: null, suggested: false }]) + }) + + it.each([ + ['a refused read', new Error('down'), { code: 'unavailable', message: 'down' }], + ['an unexpected response', { data: {} }, { code: 'unavailable', message: 'unexpected GitHub response to the reviewer listing' }], + ['a hidden repository', { data: { repository: null } }, { code: 'not-found', message: 'repository octo/demo is not visible' }], + ])('reports %s', async (_label, body, failure) => { + await expect(gitHubReviewerCandidates(reader(body).read, pull(7), '', signal)).resolves.toEqual(failure) + }) +}) diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index d923d7425e..a9a3d0c20f 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -3,6 +3,8 @@ import { describe, expect, it, vi } from 'vitest' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from '../src/gh.ts' import type { GhOutput, GhRunner } from '../src/gh.ts' import { PULL_REQUEST_COMMITS_QUERY, THREADS_QUERY } from '../src/graphql.ts' +import { CANDIDATES_QUERY } from '../src/overview.ts' +import { VIEWED_QUERY } from '../src/viewed.ts' import { GitHubProvider } from '../src/provider.ts' import type { GitHubLimits } from '../src/provider.ts' import { checkRun, demo, pull, pullRequestNode, threadPage } from './fixtures.ts' @@ -25,7 +27,7 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } } -const limits: GitHubLimits = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 } +const limits: GitHubLimits = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000 } function provider(run: GhRunner): GitHubProvider { return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits) @@ -706,3 +708,134 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.compare(unsafe, 'a'.repeat(40), 'b'.repeat(40), signal)).rejects.toThrow(invalid) expect(gh.calls).toEqual([]) }) + +describe('GitHub provider overview and viewed marks', () => { + const HEAD = 'f'.repeat(40) + const unconfigured = pull(1, { ...demo, host: 'gitlab.com' }) + const node = { data: { repository: { pullRequest: { id: 'PR_1', headRefOid: HEAD, baseRefOid: 'e'.repeat(40) } } } } + /** A double whose GraphQL reads answer `reads` by query and whose writes take their body from standard input. */ + function double( + reads: (query: string) => unknown, + write: (body: { query: string; variables: unknown }) => GhOutput = body => output({ data: { [/\{\s*(\w+)\(input:/.exec(body.query)?.[1] ?? '']: {} } }), + ) { + const inputs: unknown[] = [] + const calls: string[][] = [] + const run: GhRunner = async (args, _signal, input) => { + calls.push([...args]) + if (args.includes('--input')) { + const body = JSON.parse(input ?? '') as { query: string; variables: unknown } + inputs.push(body) + return write(body) + } + if (args[1] === 'graphql') return output(reads(args.find(arg => arg.startsWith('query='))?.slice('query='.length) ?? '')) + return output('') + } + return { run, inputs, calls } + } + + it('reads viewed marks through the files listing, bounded by maxViewedFiles', async () => { + const gh = double(query => query === VIEWED_QUERY ? { data: { repository: { pullRequest: { headRefOid: HEAD, files: { + totalCount: 1, pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ path: 'a.ts', viewerViewedState: 'VIEWED' }], + } } } } } : {}) + const subject = new GitHubProvider(gh.run, ['github.com'], { ...limits, maxViewedFiles: 7 }) + await expect(subject.viewedFiles(pull(1), HEAD, signal)).resolves.toEqual({ headSha: HEAD, files: { 'a.ts': 'viewed' }, truncated: false }) + expect(gh.calls[0]).toContain('first=7') + }) + + it('writes a viewed mark as JSON on standard input, never in the arguments', async () => { + const gh = double(() => node) + await expect(provider(gh.run).setViewed(pull(1), { path: 'src/$(x).ts', viewed: true, headSha: HEAD }, signal)).resolves.toBeUndefined() + expect(gh.calls[1]).toEqual(['api', 'graphql', '--hostname', 'github.com', '--input', '-']) + expect(gh.inputs[0]).toMatchObject({ variables: { id: 'PR_1', path: 'src/$(x).ts' } }) + expect(gh.calls.flat().some(arg => arg.includes('$(x)'))).toBe(false) + }) + + it.each([ + ['a refusing GraphQL error', output({ data: null, errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible by integration' }] }), + { code: 'failed', message: 'Resource not accessible by integration' }], + ['a GraphQL error that leaves the outcome unknown', output({ data: null, errors: [{ message: 'Something went wrong' }] }), + { code: 'failed', message: 'Something went wrong' }], + ['a refusal without a body', output('', 1, 'gh: Bad credentials (HTTP 401)'), { code: 'failed', message: 'gh: Bad credentials (HTTP 401)' }], + ['a body that is not GraphQL', output({ message: 'Not Found' }), { code: 'failed', message: 'unexpected GitHub response to unmarkFileAsViewed' }], + ])('reports a mutation refused or not confirmed with %s as failed', async (_label, answer, failure) => { + const gh = double(() => node, () => answer) + await expect(provider(gh.run).setViewed(pull(1), { path: 'a', viewed: false, headSha: HEAD }, signal)).resolves.toEqual(failure) + }) + + it('reports a mutation as failed when gh cannot start', async () => { + let reads = 0 + const run: GhRunner = async (args) => { + if (args.includes('--input')) throw new GhUnavailableError('gh could not start') + reads++ + return output(node) + } + await expect(provider(run).setViewed(pull(1), { path: 'a', viewed: true, headSha: HEAD }, signal)) + .resolves.toEqual({ code: 'failed', message: 'gh could not start' }) + expect(reads).toBe(1) + }) + + it('requests reviews, lists candidates, and updates the branch through GraphQL', async () => { + const gh = double(query => query === CANDIDATES_QUERY + ? { data: { repository: { assignableUsers: { nodes: [{ login: 'mona', name: null, avatarUrl: null }] }, pullRequest: null } } } + : node) + const subject = provider(gh.run) + await expect(subject.requestReviews(pull(1), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)).resolves.toBeUndefined() + await expect(subject.reviewerCandidates(pull(1), 'mo', signal)).resolves.toEqual([{ login: 'mona', name: null, avatarUrl: null, suggested: false }]) + await expect(subject.updateBranch(pull(1), { method: 'rebase', headSha: HEAD }, signal)).resolves.toBeUndefined() + expect(gh.inputs.map(body => (body as { variables: unknown }).variables)).toEqual([ + { input: { pullRequestId: 'PR_1', union: true, userLogins: ['mona'] } }, + { input: { pullRequestId: 'PR_1', expectedHeadOid: HEAD, updateMethod: 'REBASE' } }, + ]) + }) + + it('reruns each workflow run with a failed Actions job once, after confirming the head', async () => { + const actions = (name: string, conclusion: string, run: number | null) => ({ ...checkRun(name, 'COMPLETED', conclusion), + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: run, event: 'pull_request', workflow: { id: name, name } } } }) + const contexts = [actions('lint', 'FAILURE', 41), actions('test', 'FAILURE', 41), actions('e2e', 'FAILURE', 42), actions('docs', 'SUCCESS', 43), + actions('other', 'FAILURE', null)] + const gh = fakeGh(args => args[1] === 'graphql' ? output({ data: { r0: { p0: pullRequestNode(1, {}, contexts) } } }) : output('')) + await expect(provider(gh.run).rerunChecks(pull(1), { headSha: HEAD }, signal)).resolves.toBeUndefined() + expect(gh.calls.filter(args => args[0] === 'api' && args[1] !== 'graphql')).toEqual([ + ['api', '--hostname', 'github.com', '--method', 'POST', 'repos/octo/demo/actions/runs/41/rerun-failed-jobs'], + ['api', '--hostname', 'github.com', '--method', 'POST', 'repos/octo/demo/actions/runs/42/rerun-failed-jobs'], + ]) + }) + + it('stops at the first refused rerun', async () => { + const failed = (run: number) => ({ ...checkRun(`job${run}`, 'COMPLETED', 'FAILURE'), + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: run, event: 'pull_request', workflow: { id: `w${run}`, name: 'w' } } } }) + const gh = fakeGh(args => args[1] === 'graphql' ? output({ data: { r0: { p0: pullRequestNode(1, {}, [failed(1), failed(2)]) } } }) + : output({ message: 'Must have admin rights to Repository.' }, 1, 'gh: Must have admin rights to Repository. (HTTP 403)')) + await expect(provider(gh.run).rerunChecks(pull(1), { headSha: HEAD }, signal)) + .resolves.toEqual({ code: 'failed', message: 'Must have admin rights to Repository.' }) + expect(gh.calls.filter(args => args[4] === 'POST')).toHaveLength(1) + }) + + it.each([ + ['a moved head', () => output({ data: { r0: { p0: pullRequestNode(1, { headRefOid: 'e'.repeat(40) }) } } }), { code: 'stale' }], + ['no failed Actions job', () => output({ data: { r0: { p0: pullRequestNode(1, {}, [checkRun('lint', 'COMPLETED', 'SUCCESS')]) } } }), + { code: 'failed', message: 'No failed GitHub Actions job of the head commit can be rerun' }], + ['an unreadable status', () => output('', 1, 'gh: HTTP 401: Bad credentials'), { code: 'unauthenticated' }], + ['a status read that failed', () => output({ data: { r0: { p0: null } } }), { code: 'failed', message: 'pull request not found' }], + ])('refuses a rerun after %s', async (_label, answer, failure) => { + await expect(provider(fakeGh(answer).run).rerunChecks(pull(1), { headSha: HEAD }, signal)).resolves.toMatchObject(failure) + }) + + it('refuses a rerun at a head that is not a full commit object name', async () => { + await expect(provider(fakeGh(() => output('')).run).rerunChecks(pull(1), { headSha: 'main' }, signal)) + .rejects.toThrow('forge-github: invalid head commit "main"') + }) + + it('refuses every overview and viewed operation on an unconfigured host without running gh', async () => { + const gh = fakeGh(() => output('')) + const subject = provider(gh.run) + const failure = { code: 'failed', message: 'forge-github: host "gitlab.com" is not configured' } + await expect(subject.viewedFiles(unconfigured, HEAD, signal)).resolves.toEqual({ ...failure, code: 'unavailable' }) + await expect(subject.setViewed(unconfigured, { path: 'a', viewed: true, headSha: HEAD }, signal)).resolves.toEqual(failure) + await expect(subject.rerunChecks(unconfigured, { headSha: HEAD }, signal)).resolves.toEqual(failure) + await expect(subject.requestReviews(unconfigured, { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)).resolves.toEqual(failure) + await expect(subject.reviewerCandidates(unconfigured, '', signal)).resolves.toEqual({ ...failure, code: 'unavailable' }) + await expect(subject.updateBranch(unconfigured, { method: 'merge', headSha: HEAD }, signal)).resolves.toEqual(failure) + expect(gh.calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge-github/tests/review-writes.spec.ts b/packages/experimental/forge-github/tests/review-writes.spec.ts index 81c5b4e4ed..765c6b2df6 100644 --- a/packages/experimental/forge-github/tests/review-writes.spec.ts +++ b/packages/experimental/forge-github/tests/review-writes.spec.ts @@ -53,7 +53,7 @@ function fakeGh(check: GhOutput, ...mutations: Array): { run: } function provider(run: GhRunner): GitHubProvider { - return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }) + return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000 }) } function payload(field: string, value: unknown = { id: 'x' }): GhOutput { diff --git a/packages/experimental/forge-github/tests/review.spec.ts b/packages/experimental/forge-github/tests/review.spec.ts index 8a71ba6494..6d23ddab02 100644 --- a/packages/experimental/forge-github/tests/review.spec.ts +++ b/packages/experimental/forge-github/tests/review.spec.ts @@ -6,12 +6,13 @@ import { GhTimeoutError, GhUnavailableError, type GhRunner } from '../src/gh.ts' const ref = { repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 7 } const head = 'a'.repeat(40) +const LIMITS = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000 } const comment = { path: 'src/space name.ts', side: 'L' as const, startLine: 3, endLine: 5, body: 'Check `$(secret)`\n第二行' } const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment } const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' } function fixture() { const gh = vi.fn().mockResolvedValueOnce({ exitCode: 0, stdout: JSON.stringify({ head: { sha: head }, state: 'open' }), stderr: '' }).mockResolvedValue(success) - return { gh, provider: new GitHubProvider(gh, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }), signal: new AbortController().signal } + return { gh, provider: new GitHubProvider(gh, ['github.com'], LIMITS), signal: new AbortController().signal } } describe('review submission', () => { @@ -91,7 +92,7 @@ describe('review submission', () => { }) it('rejects a host outside the provider configuration without invoking gh', async () => { const { gh, signal } = fixture() - expect(await new GitHubProvider(gh, ['enterprise.test'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) + expect(await new GitHubProvider(gh, ['enterprise.test'], LIMITS).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) expect(gh).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts index 46bf80bf80..e7389b4b12 100644 --- a/packages/experimental/forge-github/tests/threads.spec.ts +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -21,7 +21,7 @@ function fakeGh(handler: (args: readonly string[]) => GhOutput): { run: GhRunner } function provider(run: GhRunner, limits: Partial = {}): GitHubProvider { - return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, ...limits }) + return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250, maxViewedFiles: 3_000, ...limits }) } function page(nodes: readonly unknown[], next: string | null = null): Record { diff --git a/packages/experimental/forge-github/tests/viewed.spec.ts b/packages/experimental/forge-github/tests/viewed.spec.ts new file mode 100644 index 0000000000..9dcf064810 --- /dev/null +++ b/packages/experimental/forge-github/tests/viewed.spec.ts @@ -0,0 +1,118 @@ +import { describe, expect, it, vi } from 'vitest' +import type { GraphqlReader } from '../src/commits.ts' +import type { GraphqlWriter } from '../src/mutation.ts' +import { PULL_REQUEST_NODE_QUERY } from '../src/pull-request-node.ts' +import { MARK_VIEWED_MUTATION, readViewed, UNMARK_VIEWED_MUTATION, VIEWED_QUERY, writeViewed } from '../src/viewed.ts' +import { pull } from './fixtures.ts' + +const HEAD = 'f'.repeat(40) +const signal = new AbortController().signal + +/** One files page at `head` with the viewer's marks, followed by the page after `next` when it is a cursor. */ +function page(files: readonly [string, string][], options: { head?: string; total?: number; next?: string | null } = {}): unknown { + return { data: { repository: { pullRequest: { headRefOid: options.head ?? HEAD, files: { + totalCount: options.total ?? files.length, + pageInfo: { hasNextPage: options.next != null, endCursor: options.next ?? null }, + nodes: files.map(([path, viewerViewedState]) => ({ path, viewerViewedState })), + } } } } } +} + +/** A reader that answers each request with the next body, recording the requests. */ +function reader(...bodies: unknown[]): { read: GraphqlReader; calls: (readonly string[])[] } { + const calls: (readonly string[])[] = [] + return { + calls, + read: async (args) => { + calls.push(args) + const body = bodies.shift() + return body instanceof Error ? { ok: false, failure: { code: 'unavailable', message: body.message } } : { ok: true, body } + }, + } +} + +describe('viewed file reads', () => { + it('reads the marks across pages at the requested head, mapping unknown states to unviewed', async () => { + const { read, calls } = reader( + page([['src/a.ts', 'VIEWED'], ['src/b.ts', 'DISMISSED']], { total: 3, next: 'files-1' }), + page([['src/c.ts', 'LATER_STATE']], { total: 3 }), + ) + await expect(readViewed(read, pull(7), HEAD.toUpperCase(), 3_000, signal)).resolves.toEqual({ + headSha: HEAD, files: { 'src/a.ts': 'viewed', 'src/b.ts': 'dismissed', 'src/c.ts': 'unviewed' }, truncated: false, + }) + expect(calls[0]).toEqual(['api', 'graphql', '--hostname', 'github.com', '-f', `query=${VIEWED_QUERY}`, '-f', 'owner=octo', '-f', 'name=demo', + '-F', 'number=7', '-F', 'first=100']) + expect(calls[1]?.slice(-2)).toEqual(['-f', 'cursor=files-1']) + }) + + it('stops at the limit and reports the rest as truncated', async () => { + const { read, calls } = reader(page([['src/a.ts', 'VIEWED'], ['src/b.ts', 'UNVIEWED']], { total: 5, next: 'files-1' })) + await expect(readViewed(read, pull(7), HEAD, 2, signal)).resolves.toEqual({ + headSha: HEAD, files: { 'src/a.ts': 'viewed', 'src/b.ts': 'unviewed' }, truncated: true, + }) + expect(calls[0]?.at(-1)).toBe('first=2') + expect(calls).toHaveLength(1) + }) + + it.each([ + ['a head that moved', [page([], { head: 'e'.repeat(40) })], { code: 'stale', message: `the pull request head moved from ${HEAD} to ${'e'.repeat(40)}` }], + ['a head that moved on a later page', [page([['a', 'VIEWED']], { next: 'files-1' }), page([], { head: 'e'.repeat(40) })], { code: 'stale' }], + ['a refused read', [new Error('rate limited')], { code: 'unavailable', message: 'rate limited' }], + ['an unexpected response', [{ data: {} }], { code: 'unavailable', message: 'unexpected GitHub response to the viewed file read' }], + ['a missing pull request', [{ data: { repository: { pullRequest: null } } }], { code: 'not-found', message: 'pull request 7 was not found' }], + ['a missing repository', [{ data: { repository: null } }], { code: 'not-found' }], + ['files GitHub cannot list', [{ data: { repository: { pullRequest: { headRefOid: HEAD, files: null } } } }], + { code: 'unavailable', message: 'GitHub did not list the pull request files' }], + ['a page without a cursor', [page([['a', 'VIEWED']], { next: null, total: 9 }), page([])], undefined], + ['a repeated cursor', [page([['a', 'VIEWED']], { next: 'files-1' }), page([['b', 'VIEWED']], { next: 'files-1' })], + { code: 'unavailable', message: 'GitHub file pagination did not advance' }], + ] as const)('refuses %s', async (_label, bodies, failure) => { + const result = await readViewed(reader(...bodies).read, pull(7), HEAD, 3_000, signal) + if (failure === undefined) expect(result).toMatchObject({ truncated: true }) + else expect(result).toMatchObject(failure) + }) + + it('reports a next page without a cursor as pagination that did not advance', async () => { + const body = page([['a', 'VIEWED']], { total: 9 }) as { data: { repository: { pullRequest: { files: { pageInfo: object } } } } } + body.data.repository.pullRequest.files.pageInfo = { hasNextPage: true, endCursor: null } + await expect(readViewed(reader(body).read, pull(7), HEAD, 3_000, signal)) + .resolves.toEqual({ code: 'unavailable', message: 'GitHub file pagination did not advance' }) + }) + + it('refuses a head that is not a full commit object name before reading', async () => { + const { read, calls } = reader() + await expect(readViewed(read, pull(7), 'main', 3_000, signal)).rejects.toThrow('forge-github: invalid head commit "main"') + expect(calls).toEqual([]) + }) +}) + +describe('viewed file writes', () => { + const node = { data: { repository: { pullRequest: { id: 'PR_7', headRefOid: HEAD } } } } + + it.each([ + [true, MARK_VIEWED_MUTATION, 'markFileAsViewed'], + [false, UNMARK_VIEWED_MUTATION, 'unmarkFileAsViewed'], + ])('confirms the head, then sends the mutation for viewed %s with the node id and path as variables', async (viewed, query, field) => { + const { read, calls } = reader(node) + const write = vi.fn(async () => undefined) + await expect(writeViewed(read, write, pull(7), { path: 'src/a b.ts', viewed, headSha: HEAD }, signal)).resolves.toBeUndefined() + expect(calls[0]).toContain(`query=${PULL_REQUEST_NODE_QUERY}`) + expect(write).toHaveBeenCalledWith('github.com', { query, field, variables: { id: 'PR_7', path: 'src/a b.ts' } }, signal) + }) + + it('refuses to write once the head moved, and passes a refused write on', async () => { + const write = vi.fn(async () => ({ code: 'failed', message: 'Resource not accessible' })) + const moved = { data: { repository: { pullRequest: { id: 'PR_7', headRefOid: 'e'.repeat(40) } } } } + await expect(writeViewed(reader(moved).read, write, pull(7), { path: 'a', viewed: true, headSha: HEAD }, signal)) + .resolves.toMatchObject({ code: 'stale' }) + expect(write).not.toHaveBeenCalled() + await expect(writeViewed(reader(node).read, write, pull(7), { path: 'a', viewed: true, headSha: HEAD }, signal)) + .resolves.toEqual({ code: 'failed', message: 'Resource not accessible' }) + }) + + it('refuses a head that is not a full commit object name before reading', async () => { + const { read, calls } = reader() + await expect(writeViewed(read, vi.fn(), pull(7), { path: 'a', viewed: true, headSha: 'main' }, signal)) + .rejects.toThrow('forge-github: invalid head commit "main"') + expect(calls).toEqual([]) + }) +}) From f5fd6ed8f92e933974c40d989326584bf9540592 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 17:13:04 +0800 Subject: [PATCH 10/15] feat(forge-panel): sync viewed files with GitHub and act from the card's overview rows A change request's view of all its commits reads and saves viewed marks on the code host, disabling a checkbox while its mark is saved and every checkbox when the marks cannot be read; local changes and chosen commits keep their marks in the browser. The expanded card shows one row per fact with a glyph and its value: checks open a grouped menu that reruns failed ones, the review row shows reviewer avatars and requests reviews, the merge row updates a head behind its base at the displayed head, the changes row counts unresolved threads, and linked issues take one row. --- .../forge-panel/local-and-pr.expected.md | 5 +- .../expected/forge-panel/panel.expected.md | 5 +- .../forge-panel/reference.expected.md | 5 +- apps/web/tests/forge-panel.e2e.ts | 312 ++++++++- .../client-ui-forge/README.i18n.yaml | 12 +- .../experimental/client-ui-forge/README.md | 10 +- .../experimental/client-ui-forge/README.zh.md | 10 +- .../src/client/ChangeRequestCard.tsx | 189 ++---- .../client/ChangeRequestOverview.module.css | 195 ++++++ .../src/client/ChangeRequestOverview.tsx | 610 ++++++++++++++++++ .../src/client/ChangesTab.module.css | 7 + .../client-ui-forge/src/client/ChangesTab.tsx | 94 ++- .../client-ui-forge/src/client/DiffFile.tsx | 10 +- .../src/client/ForgeTab.module.css | 60 +- .../client-ui-forge/src/client/ForgeTab.tsx | 11 +- .../client-ui-forge/src/client/host-viewed.ts | 147 +++++ .../client-ui-forge/src/client/locales.ts | 440 ++++++++++++- .../client-ui-forge/src/client/mount.ts | 25 + .../experimental/client-ui-forge/src/index.ts | 123 +++- .../experimental/client-ui-forge/src/types.ts | 8 +- .../tests/change-request-card.client.spec.tsx | 135 ++-- .../change-request-overview.client.spec.tsx | 326 ++++++++++ .../tests/changes-tab.client.spec.tsx | 139 ++++ .../tests/client-fixtures.client.ts | 8 + .../tests/controller.host.spec.ts | 80 ++- .../tests/diff-review.client.spec.tsx | 2 +- .../tests/forge-tab.client.spec.tsx | 8 +- .../client-ui-forge/tests/harness.ts | 7 + .../tests/mount.client.spec.ts | 81 ++- 29 files changed, 2758 insertions(+), 306 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/host-viewed.ts create mode 100644 packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx 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/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 60642f1499..e81ec88e77 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -52,12 +52,16 @@ const run = promisify(execFile) * 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, with the viewer `lin`, who may write - * to the repository and did not open either pull request, or no threads without it. Review mutations, which arrive as + * 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, and the pending review of `lin` with its new threads, which a - * submission publishes. Each mutation is appended to - * `mutations.jsonl`, and every invocation to `calls.jsonl`. + * 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' @@ -134,6 +138,12 @@ 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) @@ -153,7 +163,24 @@ if (args[0] === 'api' && args[1] === 'graphql' && args.includes('--input')) { const draft = thread => ({ id: 'new-' + (current.published.length + (current.pending?.threads.length ?? 0) + 1), path: thread.path, side: thread.side, line: thread.line, startLine: thread.startLine ?? null, body: thread.body }) let payload - if (field === 'addPullRequestReview') { + 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 === 'requestReviewsByLogin') { + state.requested = [...new Set([...state.requested ?? [], ...variables.input.userLogins ?? []])] + 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' } } @@ -193,18 +220,27 @@ if (args[0] === 'api' && args[1] === 'graphql') { 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', @@ -215,6 +251,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')) { @@ -228,6 +266,30 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } } })) process.exit(0) } + 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('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 current = review() @@ -264,8 +326,9 @@ if (args[0] === 'api' && args[1] === 'graphql') { 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)')) { @@ -276,7 +339,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 @@ -636,7 +700,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 () => { @@ -723,7 +787,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) @@ -732,7 +796,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') @@ -1551,7 +1617,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'), @@ -1607,38 +1673,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([]) @@ -1878,6 +1942,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) @@ -2167,3 +2233,185 @@ 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 === 'requestReviewsByLogin').map(entry => entry.variables.input)) + .toEqual([ + { pullRequestId: 'pull-7', union: true, userLogins: ['mona'] }, + { pullRequestId: 'pull-7', union: true, userLogins: ['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([]) +}) diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 3affdf7c58..76123a0151 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: 78e5f4f2b3faeb7a - zh: 6d0e381fc385d6c7 + en: b45a642c0eb37698 + zh: 0be7bd131142943b /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0feae5f8c5ef559f - zh: 5334adff35e3bebd + en: dfb2d6533c6ead77 + zh: 26f39a0792d10da3 /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: da0e90e368524e68 - zh: 1763d9c607926013 + en: 913b4dd2cc8f2a40 + zh: 2794e247c0063717 /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 8c24bf2687..85249abfc0 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,11 +36,11 @@ 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; 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, and Update branch report their outcome in a toast, 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. -- **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 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. 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. 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. @@ -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`, and another refusal with `forgePanel/action-failed` and the host's reason. `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 until the host saves or refuses it; a write that settles after another diff loaded changes nothing in that diff. + `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,7 @@ 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/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 | @@ -148,7 +152,7 @@ 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. +- **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. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 6960bca568..aa9b780e7a 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,11 +36,11 @@ 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 下重新打开、刷新与导航都不会再从托管平台读取。 -- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.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 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.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` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 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 提交不一致的响应。 @@ -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` 并附托管平台的原因。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 保存读者设置的每个标记,直到托管平台保存或拒绝;另一个 diff 加载后才结束的写入不会改动该 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,7 @@ 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/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -148,7 +152,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 -- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 +- **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 - **评审讨论的写入**——在一个变更视图中的写操作,会在该变更请求的其他已打开视图收到下一次状态时显示;解决讨论不会改变 pull request 的更新时间,要等到 `reviewRefreshMs` 之后才显示。GitHub 每个用户在每个 pull request 上只保留一个待提交评审。早期版本保存在浏览器中的评论草稿,只有其文件和行仍与所显示的 diff 一致时才能加入待提交评审,否则只能编辑或删除。对所选提交的评论只能添加到输入框。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index a5f1abbab2..227e18448e 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,9 +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 { @@ -101,16 +101,7 @@ 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 +112,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 +125,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 +202,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 +328,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 +342,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..71e602700a --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css @@ -0,0 +1,195 @@ +/* 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%; + 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..0f84d7868d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -0,0 +1,610 @@ +/** + * 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 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 +} + +/** + * 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 + && displayed.checks.some(check => check.state === 'failure' && check.rerun !== null) ? 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, or that the listing failed. */ +type Listing = { 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({ ok: true, value }) }, + () => { if (!controller.signal.aborted) setListing({ 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) } + }, []) + const candidates = listing !== null && listing.ok ? listing.value : [] + let body: ReactNode + if (listing === null) { + body =
{t('reviewers.loading')}
+ } else if (!listing.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) => { + if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() + if (event.key !== 'Enter' || event.nativeEvent.isComposing || first === undefined) return + event.preventDefault() + 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/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 9183d560e4..6ea692bf97 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -528,6 +528,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; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index babc227996..f142afea80 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -33,7 +33,7 @@ import type { } from '../types.ts' import type { ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, - ForgeThreadId, + ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -46,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' @@ -100,8 +101,15 @@ 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. */ @@ -154,6 +162,8 @@ 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. */ @@ -218,11 +228,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') { @@ -231,10 +253,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. */ @@ -455,7 +482,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, + changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -615,23 +642,25 @@ 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. @@ -656,7 +685,14 @@ 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 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 @@ -927,7 +963,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 } @@ -1075,6 +1113,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} /> @@ -1198,6 +1239,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..ff5993f11b 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. */ @@ -504,7 +508,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 +559,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..6ca8d2fd40 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,22 @@ 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/host-viewed.ts b/packages/experimental/client-ui-forge/src/client/host-viewed.ts new file mode 100644 index 0000000000..b9d0c76130 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/host-viewed.ts @@ -0,0 +1,147 @@ +/** + * Viewed marks a code host keeps for a whole change request. The changes view reads them with the diff and shows each + * mark the reader sets at once, while the host saves it; a mark the host refuses returns to what the host keeps. + */ + +import { useMemo, useState } from 'react' +import type { ForgeViewedFiles, ForgeViewedRequest, ForgeViewedState } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeDiffFile } from '../types.ts' +import type { ViewedMarks } from './viewed-files.ts' + +/** The host's marks on the files of one diff, or why the view could not read them. */ +export type HostViewed = + | { readonly kind: 'read'; readonly files: Readonly> } + | { readonly kind: 'failed'; readonly message: string } + +/** A loaded change request diff whose marks the host keeps. */ +export interface HostViewedOwner { + /** Binding URL of the change request. */ + readonly url: string + /** Head commit the diff and its marks were read at. */ + readonly headSha: string + /** Files of the diff with the digest of each change. */ + readonly files: readonly ForgeDiffFile[] + /** The host's marks. */ + readonly viewed: HostViewed +} + +/** Why a mark the host did not save returned to its previous state. */ +export type HostViewedFailure = { readonly kind: 'stale' } | { readonly kind: 'failed'; readonly message: string } + +/** The host's marks of the shown diff with the reader's writes. */ +export interface HostViewedMarks { + /** Marks as digests, so a mark of the current change matches the file's digest and a dismissed mark matches none. */ + readonly marks: ViewedMarks + /** Whether the host's marks could not be read, so no file can be marked. */ + readonly unavailable: boolean + /** Whether a write of the file's mark is in flight. */ + readonly saving: (path: string) => boolean + /** + * Show a mark at once and save it on the host. + * @param path - the file's path. + * @param viewed - whether the file is viewed. + * @returns false, changing nothing, while the marks are unavailable or the file's previous write is in flight. + */ + readonly mark: (path: string, viewed: boolean) => boolean +} + +const NO_CHOICES: Readonly> = {} +const NO_MARKS: ViewedMarks = new Map() +const NO_PATHS: ReadonlySet = new Set() + +/** Digest a dismissed mark records: no file change digests to it, so the file reads as changed since it was viewed. */ +const DISMISSED = '' + +/** + * Convert the host's marks of a diff to digests, with the reader's choices taking the place of the host's. + * @param files - files of the diff with the digest of each change. + * @param host - the host's state of each file the host listed. + * @param chosen - the reader's marks since the diff loaded, by path. + * @returns the digest of each file marked viewed or dismissed. + */ +export function hostMarksOf( + files: readonly ForgeDiffFile[], + host: Readonly>, + chosen: Readonly>, +): ViewedMarks { + const marks = new Map() + for (const file of files) { + const choice = chosen[file.path] + const state = choice === undefined ? host[file.path] : choice ? 'viewed' : 'unviewed' + if (state === 'viewed') marks.set(file.path, file.digest) + else if (state === 'dismissed') marks.set(file.path, DISMISSED) + } + return marks +} + +/** + * Convert a read of the host's marks to the state the view keeps for a diff read at `headSha`. + * @param result - the read, or null when the diff shows chosen commits, which the host keeps no marks for. + * @param headSha - head commit the diff was read at. + * @returns the marks, why they could not be read, or null when the browser keeps the marks instead. + */ +export function hostViewedOf(result: RemoteResult | null, headSha: string): HostViewed | null { + if (result === null) return null + if (!result.ok) return { kind: 'failed', message: result.error.message } + if (result.value === null) return null + return result.value.headSha === headSha ? { kind: 'read', files: result.value.files } + // The diff and the marks were read at two heads, so neither matches the other. + : { kind: 'failed', message: `viewed marks were read at ${result.value.headSha}, the diff at ${headSha}` } +} + +/** + * Keep the reader's marks of one diff over the host's until the next diff loads, saving each on the host. + * @param owner - the shown diff when the host keeps its marks, else null. + * @param save - saves one mark on the host. + * @param failed - reports a mark the host did not save after it returned to its previous state. + * @returns the marks and the write action, or null when the browser keeps the marks. + */ +export function useHostViewed( + owner: HostViewedOwner | null, + save: (url: string, request: ForgeViewedRequest) => Promise>, + failed: (failure: HostViewedFailure) => void, +): HostViewedMarks | null { + const [chosen, setChosen] = useState<{ readonly owner: HostViewedOwner | null; readonly marks: Readonly> }>( + { owner: null, marks: {} }) + const [saving, setSaving] = useState<{ readonly owner: HostViewedOwner | null; readonly paths: ReadonlySet }>( + { owner: null, paths: new Set() }) + const marks = chosen.owner === owner ? chosen.marks : NO_CHOICES + const shown = useMemo(() => owner?.viewed.kind === 'read' ? hostMarksOf(owner.files, owner.viewed.files, marks) : NO_MARKS, [owner, marks]) + if (owner === null) return null + const inFlight = saving.owner === owner ? saving.paths : NO_PATHS + const { viewed } = owner + // A choice made for an earlier diff never applies to a later one, whose read already holds what the host saved, and a + // write of an earlier diff that settles late leaves the later diff's choices alone. + const choose = (path: string, value: boolean): void => { + setChosen(current => ({ owner, marks: { ...current.owner === owner ? current.marks : {}, [path]: value } })) + } + const restore = (path: string, previous: boolean | undefined): void => { + setChosen((current) => { + if (current.owner !== owner) return current + const { [path]: _mark, ...rest } = current.marks + return { owner, marks: previous === undefined ? rest : { ...rest, [path]: previous } } + }) + } + const settle = (path: string): void => { + setSaving(value => value.owner === owner ? { owner, paths: new Set([...value.paths].filter(item => item !== path)) } : value) + } + return { + marks: shown, + unavailable: viewed.kind === 'failed', + saving: path => inFlight.has(path), + mark: (path, value) => { + if (viewed.kind === 'failed' || inFlight.has(path)) return false + const previous = marks[path] + choose(path, value) + setSaving(current => ({ owner, paths: new Set([...current.owner === owner ? current.paths : [], path]) })) + void save(owner.url, { path, viewed: value, headSha: owner.headSha }).then((result) => { + settle(path) + if (result.ok) return + restore(path, previous) + failed(result.error.code === 'forgePanel/stale-head' ? { kind: 'stale' } : { kind: 'failed', message: result.error.message }) + }) + return true + }, + } +} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 66fef1960d..88f06492a9 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -137,7 +137,6 @@ export const zh = { 'change.review.changesRequested': '要求修改', 'change.review.required': '等待评审', 'change.review.none': '尚未请求评审', - 'change.review.threads': '{review} · {count} 条未解决讨论', 'change.merge.mergeable': '无冲突', 'change.merge.conflicting': '与 {base} 有冲突', 'change.merge.unknown': '正在检查冲突', @@ -153,6 +152,54 @@ export const zh = { 'change.mergeNote.rebase': '把提交逐个变基到 {base}', 'change.mergeConfirm': '确认合并', 'change.mergeChanged': '提交已更新,请重新检查后再打开合并菜单', + 'checks.allPassed': '{count} 项检查全部通过', + 'checks.showQuiet': '显示其余 {count} 项(通过、跳过)', + 'reviewers.requestMore': '请求其他人评审…', + 'change.threads': '{count} 条未解决讨论', + 'issues.label': '关联 issue', + 'issues.separator': '、', + 'issues.more': ' 等', + 'issues.aria': '打开 issue {label}:{title}', + 'checks.group.failed': '失败', + 'checks.group.running': '进行中', + 'checks.group.passed': '通过', + 'checks.group.cancelled': '已取消', + 'checks.group.other': '跳过与其他', + 'checks.rerunFailed': '重跑失败项', + 'toast.rerunRequested': '已请求重跑 {name} 的检查', + 'toast.rerunFailed': '无法重跑检查:{message}', + 'toast.rerunStale': '{name} 已有新提交,请查看新提交的检查后再重跑', + 'reviewers.rerequestAria': '重新请求 {login} 评审', + 'reviewers.pending': '待评审', + 'reviewers.approved': '已批准', + 'reviewers.changesRequested': '要求修改', + 'reviewers.commented': '已评论', + 'reviewers.dismissed': '已被撤销', + 'reviewers.older': '早于最新提交', + 'reviewers.codeOwner': '代码所有者', + 'reviewers.team': '团队', + 'reviewers.bot': 'bot', + 'reviewers.truncated': '评审者较多,完整列表请在浏览器中查看', + 'reviewers.none': '还没有评审者', + 'reviewers.search': '搜索成员', + 'reviewers.loading': '正在加载成员', + 'reviewers.loadFailed': '无法列出成员', + 'reviewers.empty': '没有匹配的成员', + 'reviewers.suggested': '建议', + 'toast.reviewRequested': '已请求 {login} 评审 {name}', + 'toast.reviewRequestFailed': '无法请求评审:{message}', + 'branch.behind': '落后于 {base}', + 'branch.update': '更新分支', + 'branch.updateTitle': '用 {base} 的新提交更新 {head}', + 'branch.method.merge': '合并更新', + 'branch.method.rebase': '变基更新', + 'branch.note.merge': '在分支上新增一个合并提交', + 'branch.note.rebase': '把分支上的提交逐个变基到 {base},会改写这些提交', + 'branch.confirm': '确认更新', + 'branch.changed': '提交已更新,请重新检查后再打开更新菜单', + 'toast.branchUpdated': '已开始更新 {name} 的分支', + 'toast.branchUpdateFailed': '无法更新分支:{message}', + 'toast.branchUpdateStale': '{name} 已有新提交,请重新检查后再更新', 'diff.tab': '变更', 'diff.tabNumbered': '#{number} 的变更', 'diff.scope.branch': '分支', @@ -194,6 +241,12 @@ export const zh = { 'viewed.progress': '已审阅 {viewed} / {total}', 'viewed.progressAria': '已审阅的文件', 'viewed.saveFailed': '无法保存已审阅状态', + 'viewed.hintHost': '保存在 GitHub · 按 V 切换当前文件', + 'viewed.saving': '正在保存到 GitHub…', + 'viewed.unavailable': '未能读取 GitHub 上的已审阅状态', + 'viewed.readFailed': '未能读取 GitHub 上的已审阅状态,暂时不能标记文件:{message}', + 'viewed.syncFailed': '已审阅状态未能保存到 GitHub:{message}', + 'viewed.syncStale': 'PR 已有新提交,已审阅状态未保存。请刷新后再标记', 'commits.all': '全部提交', 'commits.range': '{from}…{to}', 'commits.count': '{count} 个提交', @@ -512,7 +565,6 @@ export const en: Record = { 'change.review.changesRequested': 'Changes requested', 'change.review.required': 'Review required', 'change.review.none': 'No review requested', - 'change.review.threads': '{review} · {count} unresolved', 'change.merge.mergeable': 'No conflicts', 'change.merge.conflicting': 'Conflicts with {base}', 'change.merge.unknown': 'Checking for conflicts', @@ -528,6 +580,54 @@ export const en: Record = { 'change.mergeNote.rebase': 'Replay each commit onto {base}', 'change.mergeConfirm': 'Confirm merge', 'change.mergeChanged': 'New commits arrived. Review them before reopening the merge menu.', + 'checks.allPassed': 'All {count} checks passed', + 'checks.showQuiet': 'Show {count} more (passed, skipped)', + 'reviewers.requestMore': 'Request a review from someone else…', + 'change.threads': '{count} unresolved threads', + 'issues.label': 'Linked issues', + 'issues.separator': ', ', + 'issues.more': ' and more', + 'issues.aria': 'Open issue {label}: {title}', + 'checks.group.failed': 'Failed', + 'checks.group.running': 'Running', + 'checks.group.passed': 'Passed', + 'checks.group.cancelled': 'Cancelled', + 'checks.group.other': 'Skipped and other', + 'checks.rerunFailed': 'Rerun failed', + 'toast.rerunRequested': 'Requested a rerun of the checks of {name}', + 'toast.rerunFailed': 'Could not rerun the checks: {message}', + 'toast.rerunStale': '{name} has new commits. Check the new commit\'s checks before rerunning.', + 'reviewers.rerequestAria': 'Re-request a review from {login}', + 'reviewers.pending': 'Awaiting review', + 'reviewers.approved': 'Approved', + 'reviewers.changesRequested': 'Changes requested', + 'reviewers.commented': 'Commented', + 'reviewers.dismissed': 'Dismissed', + 'reviewers.older': 'Before the latest commit', + 'reviewers.codeOwner': 'Code owner', + 'reviewers.team': 'Team', + 'reviewers.bot': 'Bot', + 'reviewers.truncated': 'Some reviewers are not listed; open the change request for all of them', + 'reviewers.none': 'No reviewers yet', + 'reviewers.search': 'Search people', + 'reviewers.loading': 'Loading people', + 'reviewers.loadFailed': 'Could not list people', + 'reviewers.empty': 'No matching people', + 'reviewers.suggested': 'Suggested', + 'toast.reviewRequested': 'Requested a review of {name} from {login}', + 'toast.reviewRequestFailed': 'Could not request the review: {message}', + 'branch.behind': 'Behind {base}', + 'branch.update': 'Update branch', + 'branch.updateTitle': 'Update {head} with new commits from {base}', + 'branch.method.merge': 'Update with merge commit', + 'branch.method.rebase': 'Update with rebase', + 'branch.note.merge': 'Adds a merge commit to the branch', + 'branch.note.rebase': 'Rebases the branch\'s commits onto {base}, rewriting them', + 'branch.confirm': 'Confirm update', + 'branch.changed': 'New commits arrived. Review them, then open this menu again.', + 'toast.branchUpdated': 'Started updating the branch of {name}', + 'toast.branchUpdateFailed': 'Could not update the branch: {message}', + 'toast.branchUpdateStale': '{name} has new commits. Review them before updating.', 'diff.tab': 'Changes', 'diff.tabNumbered': 'Changes in #{number}', 'diff.scope.branch': 'Branch', @@ -569,6 +669,12 @@ export const en: Record = { 'viewed.progress': '{viewed} / {total} viewed', 'viewed.progressAria': 'Viewed files', 'viewed.saveFailed': 'Could not save the viewed state', + 'viewed.hintHost': 'Saved on GitHub · Press V to toggle the current file', + 'viewed.saving': 'Saving to GitHub…', + 'viewed.unavailable': 'Could not read viewed files from GitHub', + 'viewed.readFailed': 'Could not read viewed files from GitHub, so files cannot be marked: {message}', + 'viewed.syncFailed': 'Could not save the viewed mark to GitHub: {message}', + 'viewed.syncStale': 'The PR has new commits, so the viewed mark was not saved. Refresh and mark the file again.', 'commits.all': 'All commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -891,7 +997,6 @@ export const ja: Record = { 'change.review.changesRequested': '変更が要求されています', 'change.review.required': 'レビュー待ち', 'change.review.none': 'レビュー未依頼', - 'change.review.threads': '{review} · 未解決 {count} 件', 'change.merge.mergeable': '競合なし', 'change.merge.conflicting': '{base} と競合', 'change.merge.unknown': '競合を確認中', @@ -907,6 +1012,54 @@ export const ja: Record = { 'change.mergeNote.rebase': '各コミットを {base} 上にリベース', 'change.mergeConfirm': 'マージを確認', 'change.mergeChanged': '新しいコミットがあります。確認してからマージメニューを開き直してください', + 'checks.allPassed': '{count} 件のチェックがすべて成功', + 'checks.showQuiet': '残り {count} 件を表示(成功・スキップ)', + 'reviewers.requestMore': 'ほかの人にレビューを依頼…', + 'change.threads': '未解決のスレッド {count} 件', + 'issues.label': '関連 issue', + 'issues.separator': '、', + 'issues.more': ' ほか', + 'issues.aria': 'issue {label} を開く:{title}', + 'checks.group.failed': '失敗', + 'checks.group.running': '実行中', + 'checks.group.passed': '成功', + 'checks.group.cancelled': 'キャンセル済み', + 'checks.group.other': 'スキップとその他', + 'checks.rerunFailed': '失敗分を再実行', + 'toast.rerunRequested': '{name} のチェックの再実行を依頼しました', + 'toast.rerunFailed': 'チェックを再実行できませんでした:{message}', + 'toast.rerunStale': '{name} に新しいコミットがあります。新しいコミットのチェックを確認してから再実行してください。', + 'reviewers.rerequestAria': '{login} にレビューを再依頼', + 'reviewers.pending': 'レビュー待ち', + 'reviewers.approved': '承認済み', + 'reviewers.changesRequested': '修正を依頼', + 'reviewers.commented': 'コメント済み', + 'reviewers.dismissed': '取り消し済み', + 'reviewers.older': '最新コミットより前', + 'reviewers.codeOwner': 'コードオーナー', + 'reviewers.team': 'チーム', + 'reviewers.bot': 'bot', + 'reviewers.truncated': 'レビュアーが多いため、すべてはブラウザーで確認してください', + 'reviewers.none': 'レビュアーはまだいません', + 'reviewers.search': 'メンバーを検索', + 'reviewers.loading': 'メンバーを読み込んでいます', + 'reviewers.loadFailed': 'メンバーを一覧できませんでした', + 'reviewers.empty': '一致するメンバーはいません', + 'reviewers.suggested': 'おすすめ', + 'toast.reviewRequested': '{login} に {name} のレビューを依頼しました', + 'toast.reviewRequestFailed': 'レビューを依頼できませんでした:{message}', + 'branch.behind': '{base} より遅れています', + 'branch.update': 'ブランチを更新', + 'branch.updateTitle': '{base} の新しいコミットで {head} を更新', + 'branch.method.merge': 'マージコミットで更新', + 'branch.method.rebase': 'リベースで更新', + 'branch.note.merge': 'ブランチにマージコミットを追加します', + 'branch.note.rebase': 'ブランチのコミットを {base} にリベースし、コミットを書き換えます', + 'branch.confirm': '更新を確定', + 'branch.changed': 'コミットが更新されました。確認してからもう一度メニューを開いてください', + 'toast.branchUpdated': '{name} のブランチの更新を開始しました', + 'toast.branchUpdateFailed': 'ブランチを更新できませんでした:{message}', + 'toast.branchUpdateStale': '{name} に新しいコミットがあります。確認してから更新してください。', 'diff.tab': '変更', 'diff.tabNumbered': '#{number} の変更', 'diff.scope.branch': 'ブランチ', @@ -948,6 +1101,12 @@ export const ja: Record = { 'viewed.progress': '確認済み {viewed} / {total}', 'viewed.progressAria': '確認済みのファイル', 'viewed.saveFailed': '確認済みの状態を保存できませんでした', + 'viewed.hintHost': 'GitHub に保存 · V キーで現在のファイルを切り替え', + 'viewed.saving': 'GitHub に保存しています…', + 'viewed.unavailable': 'GitHub の確認済み状態を読み込めませんでした', + 'viewed.readFailed': 'GitHub の確認済み状態を読み込めないため、ファイルに印を付けられません:{message}', + 'viewed.syncFailed': '確認済みの印を GitHub に保存できませんでした:{message}', + 'viewed.syncStale': 'PR に新しいコミットがあるため、確認済みの印は保存されていません。更新してからもう一度付けてください。', 'commits.all': 'すべてのコミット', 'commits.range': '{from}…{to}', 'commits.count': '{count} 件のコミット', @@ -1263,7 +1422,6 @@ export const es: Record = { 'change.review.changesRequested': 'Cambios solicitados', 'change.review.required': 'Revisión requerida', 'change.review.none': 'Sin revisión solicitada', - 'change.review.threads': '{review} · {count} sin resolver', 'change.merge.mergeable': 'Sin conflictos', 'change.merge.conflicting': 'Conflictos con {base}', 'change.merge.unknown': 'Buscando conflictos', @@ -1279,6 +1437,54 @@ export const es: Record = { 'change.mergeNote.rebase': 'Aplicar cada commit sobre {base}', 'change.mergeConfirm': 'Confirmar fusión', 'change.mergeChanged': 'Hay nuevos commits. Revísalos antes de volver a abrir el menú de fusión', + 'checks.allPassed': 'Las {count} comprobaciones se superaron', + 'checks.showQuiet': 'Mostrar {count} más (superadas, omitidas)', + 'reviewers.requestMore': 'Pedir revisión a otra persona…', + 'change.threads': '{count} conversaciones sin resolver', + 'issues.label': 'Incidencias vinculadas', + 'issues.separator': ', ', + 'issues.more': ' y más', + 'issues.aria': 'Abrir incidencia {label}: {title}', + 'checks.group.failed': 'Fallidas', + 'checks.group.running': 'En curso', + 'checks.group.passed': 'Superadas', + 'checks.group.cancelled': 'Canceladas', + 'checks.group.other': 'Omitidas y otras', + 'checks.rerunFailed': 'Repetir fallidas', + 'toast.rerunRequested': 'Se pidió repetir las comprobaciones de {name}', + 'toast.rerunFailed': 'No se pudieron repetir las comprobaciones: {message}', + 'toast.rerunStale': '{name} tiene nuevos commits. Revisa las comprobaciones del nuevo commit antes de repetirlas.', + 'reviewers.rerequestAria': 'Volver a pedir revisión a {login}', + 'reviewers.pending': 'Pendiente', + 'reviewers.approved': 'Aprobado', + 'reviewers.changesRequested': 'Cambios pedidos', + 'reviewers.commented': 'Comentó', + 'reviewers.dismissed': 'Descartada', + 'reviewers.older': 'Anterior al último commit', + 'reviewers.codeOwner': 'Propietario del código', + 'reviewers.team': 'Equipo', + 'reviewers.bot': 'Bot', + 'reviewers.truncated': 'No se muestran todos los revisores; abre la solicitud para verlos', + 'reviewers.none': 'Aún no hay revisores', + 'reviewers.search': 'Buscar personas', + 'reviewers.loading': 'Cargando personas', + 'reviewers.loadFailed': 'No se pudo listar a las personas', + 'reviewers.empty': 'Ninguna persona coincide', + 'reviewers.suggested': 'Sugerido', + 'toast.reviewRequested': 'Se pidió a {login} revisar {name}', + 'toast.reviewRequestFailed': 'No se pudo pedir la revisión: {message}', + 'branch.behind': 'Por detrás de {base}', + 'branch.update': 'Actualizar rama', + 'branch.updateTitle': 'Actualizar {head} con los nuevos commits de {base}', + 'branch.method.merge': 'Actualizar con commit de fusión', + 'branch.method.rebase': 'Actualizar con rebase', + 'branch.note.merge': 'Añade un commit de fusión a la rama', + 'branch.note.rebase': 'Hace rebase de los commits de la rama sobre {base} y los reescribe', + 'branch.confirm': 'Confirmar actualización', + 'branch.changed': 'Llegaron nuevos commits. Revísalos y vuelve a abrir este menú.', + 'toast.branchUpdated': 'Se empezó a actualizar la rama de {name}', + 'toast.branchUpdateFailed': 'No se pudo actualizar la rama: {message}', + 'toast.branchUpdateStale': '{name} tiene nuevos commits. Revísalos antes de actualizar.', 'diff.tab': 'Cambios', 'diff.tabNumbered': 'Cambios en #{number}', 'diff.scope.branch': 'Rama', @@ -1320,6 +1526,12 @@ export const es: Record = { 'viewed.progress': '{viewed} / {total} revisados', 'viewed.progressAria': 'Archivos revisados', 'viewed.saveFailed': 'No se pudo guardar el estado de revisión', + 'viewed.hintHost': 'Se guarda en GitHub · Pulsa V para cambiar el archivo actual', + 'viewed.saving': 'Guardando en GitHub…', + 'viewed.unavailable': 'No se pudo leer de GitHub qué archivos se revisaron', + 'viewed.readFailed': 'No se pudo leer de GitHub qué archivos se revisaron, así que no se pueden marcar: {message}', + 'viewed.syncFailed': 'No se pudo guardar la marca de revisión en GitHub: {message}', + 'viewed.syncStale': 'El PR tiene nuevos commits y la marca de revisión no se guardó. Actualiza y vuelve a marcar el archivo.', 'commits.all': 'Todos los commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -1635,7 +1847,6 @@ export const fr: Record = { 'change.review.changesRequested': 'Modifications demandées', 'change.review.required': 'Revue requise', 'change.review.none': 'Aucune revue demandée', - 'change.review.threads': '{review} · {count} non résolus', 'change.merge.mergeable': 'Aucun conflit', 'change.merge.conflicting': 'Conflits avec {base}', 'change.merge.unknown': 'Recherche de conflits', @@ -1651,6 +1862,54 @@ export const fr: Record = { 'change.mergeNote.rebase': 'Rejouer chaque commit sur {base}', 'change.mergeConfirm': 'Confirmer la fusion', 'change.mergeChanged': 'De nouveaux commits sont arrivés. Vérifiez-les avant de rouvrir le menu de fusion', + 'checks.allPassed': 'Les {count} vérifications ont réussi', + 'checks.showQuiet': 'Afficher {count} de plus (réussies, ignorées)', + 'reviewers.requestMore': 'Demander une revue à quelqu’un d’autre…', + 'change.threads': '{count} discussions non résolues', + 'issues.label': 'Tickets liés', + 'issues.separator': ', ', + 'issues.more': ' et d’autres', + 'issues.aria': 'Ouvrir le ticket {label} : {title}', + 'checks.group.failed': 'En échec', + 'checks.group.running': 'En cours', + 'checks.group.passed': 'Réussies', + 'checks.group.cancelled': 'Annulées', + 'checks.group.other': 'Ignorées et autres', + 'checks.rerunFailed': 'Relancer les échecs', + 'toast.rerunRequested': 'Relance des vérifications de {name} demandée', + 'toast.rerunFailed': 'Impossible de relancer les vérifications : {message}', + 'toast.rerunStale': '{name} contient de nouveaux commits. Consultez les vérifications du nouveau commit avant de relancer.', + 'reviewers.rerequestAria': 'Redemander une revue à {login}', + 'reviewers.pending': 'En attente', + 'reviewers.approved': 'Approuvé', + 'reviewers.changesRequested': 'Modifications demandées', + 'reviewers.commented': 'A commenté', + 'reviewers.dismissed': 'Écartée', + 'reviewers.older': 'Avant le dernier commit', + 'reviewers.codeOwner': 'Propriétaire du code', + 'reviewers.team': 'Équipe', + 'reviewers.bot': 'Bot', + 'reviewers.truncated': 'Tous les relecteurs ne sont pas affichés ; ouvrez la demande pour les voir', + 'reviewers.none': 'Aucun relecteur pour l’instant', + 'reviewers.search': 'Rechercher des personnes', + 'reviewers.loading': 'Chargement des personnes', + 'reviewers.loadFailed': 'Impossible de lister les personnes', + 'reviewers.empty': 'Aucune personne ne correspond', + 'reviewers.suggested': 'Suggéré', + 'toast.reviewRequested': 'Revue de {name} demandée à {login}', + 'toast.reviewRequestFailed': 'Impossible de demander la revue : {message}', + 'branch.behind': 'En retard sur {base}', + 'branch.update': 'Mettre à jour la branche', + 'branch.updateTitle': 'Mettre à jour {head} avec les nouveaux commits de {base}', + 'branch.method.merge': 'Mettre à jour par commit de fusion', + 'branch.method.rebase': 'Mettre à jour par rebase', + 'branch.note.merge': 'Ajoute un commit de fusion à la branche', + 'branch.note.rebase': 'Rebase les commits de la branche sur {base} et les réécrit', + 'branch.confirm': 'Confirmer la mise à jour', + 'branch.changed': 'De nouveaux commits sont arrivés. Vérifiez-les, puis rouvrez ce menu.', + 'toast.branchUpdated': 'Mise à jour de la branche de {name} lancée', + 'toast.branchUpdateFailed': 'Impossible de mettre à jour la branche : {message}', + 'toast.branchUpdateStale': '{name} contient de nouveaux commits. Vérifiez-les avant la mise à jour.', 'diff.tab': 'Modifications', 'diff.tabNumbered': 'Modifications de #{number}', 'diff.scope.branch': 'Branche', @@ -1692,6 +1951,12 @@ export const fr: Record = { 'viewed.progress': '{viewed} / {total} vus', 'viewed.progressAria': 'Fichiers vus', 'viewed.saveFailed': 'Impossible d’enregistrer l’état de revue', + 'viewed.hintHost': 'Enregistré sur GitHub · Appuyez sur V pour basculer le fichier actuel', + 'viewed.saving': 'Enregistrement sur GitHub…', + 'viewed.unavailable': 'Impossible de lire l’état de revue sur GitHub', + 'viewed.readFailed': 'Impossible de lire l’état de revue sur GitHub ; les fichiers ne peuvent pas être marqués : {message}', + 'viewed.syncFailed': 'Impossible d’enregistrer la marque de revue sur GitHub : {message}', + 'viewed.syncStale': 'La PR contient de nouveaux commits ; la marque de revue n’a pas été enregistrée. Actualisez et marquez à nouveau le fichier.', 'commits.all': 'Tous les commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -2007,7 +2272,6 @@ export const de: Record = { 'change.review.changesRequested': 'Änderungen angefordert', 'change.review.required': 'Review erforderlich', 'change.review.none': 'Kein Review angefordert', - 'change.review.threads': '{review} · {count} ungelöst', 'change.merge.mergeable': 'Keine Konflikte', 'change.merge.conflicting': 'Konflikte mit {base}', 'change.merge.unknown': 'Konflikte werden geprüft', @@ -2023,6 +2287,54 @@ export const de: Record = { 'change.mergeNote.rebase': 'Jeden Commit auf {base} neu anwenden', 'change.mergeConfirm': 'Zusammenführung bestätigen', 'change.mergeChanged': 'Neue Commits sind eingetroffen. Vor dem erneuten Öffnen des Merge-Menüs prüfen', + 'checks.allPassed': 'Alle {count} Prüfungen bestanden', + 'checks.showQuiet': '{count} weitere anzeigen (bestanden, übersprungen)', + 'reviewers.requestMore': 'Review bei jemand anderem anfordern…', + 'change.threads': '{count} ungelöste Diskussionen', + 'issues.label': 'Verknüpfte Issues', + 'issues.separator': ', ', + 'issues.more': ' und weitere', + 'issues.aria': 'Issue {label} öffnen: {title}', + 'checks.group.failed': 'Fehlgeschlagen', + 'checks.group.running': 'Laufend', + 'checks.group.passed': 'Bestanden', + 'checks.group.cancelled': 'Abgebrochen', + 'checks.group.other': 'Übersprungen und andere', + 'checks.rerunFailed': 'Fehlgeschlagene erneut ausführen', + 'toast.rerunRequested': 'Erneute Ausführung der Prüfungen von {name} angefordert', + 'toast.rerunFailed': 'Die Prüfungen konnten nicht erneut ausgeführt werden: {message}', + 'toast.rerunStale': '{name} hat neue Commits. Prüfungen des neuen Commits ansehen, bevor sie erneut ausgeführt werden.', + 'reviewers.rerequestAria': 'Review von {login} erneut anfordern', + 'reviewers.pending': 'Ausstehend', + 'reviewers.approved': 'Genehmigt', + 'reviewers.changesRequested': 'Änderungen angefordert', + 'reviewers.commented': 'Kommentiert', + 'reviewers.dismissed': 'Verworfen', + 'reviewers.older': 'Vor dem neuesten Commit', + 'reviewers.codeOwner': 'Code-Owner', + 'reviewers.team': 'Team', + 'reviewers.bot': 'Bot', + 'reviewers.truncated': 'Nicht alle Reviewer sind aufgeführt; die Anfrage im Browser zeigt alle', + 'reviewers.none': 'Noch keine Reviewer', + 'reviewers.search': 'Personen suchen', + 'reviewers.loading': 'Personen werden geladen', + 'reviewers.loadFailed': 'Personen konnten nicht aufgelistet werden', + 'reviewers.empty': 'Keine passenden Personen', + 'reviewers.suggested': 'Vorgeschlagen', + 'toast.reviewRequested': 'Review von {name} bei {login} angefordert', + 'toast.reviewRequestFailed': 'Das Review konnte nicht angefordert werden: {message}', + 'branch.behind': 'Hinter {base}', + 'branch.update': 'Branch aktualisieren', + 'branch.updateTitle': '{head} mit neuen Commits aus {base} aktualisieren', + 'branch.method.merge': 'Mit Merge-Commit aktualisieren', + 'branch.method.rebase': 'Mit Rebase aktualisieren', + 'branch.note.merge': 'Fügt dem Branch einen Merge-Commit hinzu', + 'branch.note.rebase': 'Rebased die Commits des Branches auf {base} und schreibt sie neu', + 'branch.confirm': 'Aktualisierung bestätigen', + 'branch.changed': 'Neue Commits sind eingetroffen. Bitte prüfen und das Menü erneut öffnen.', + 'toast.branchUpdated': 'Aktualisierung des Branches von {name} gestartet', + 'toast.branchUpdateFailed': 'Der Branch konnte nicht aktualisiert werden: {message}', + 'toast.branchUpdateStale': '{name} hat neue Commits. Bitte vor dem Aktualisieren prüfen.', 'diff.tab': 'Änderungen', 'diff.tabNumbered': 'Änderungen in #{number}', 'diff.scope.branch': 'Branch', @@ -2064,6 +2376,12 @@ export const de: Record = { 'viewed.progress': '{viewed} / {total} angesehen', 'viewed.progressAria': 'Angesehene Dateien', 'viewed.saveFailed': 'Der Ansichtsstatus konnte nicht gespeichert werden', + 'viewed.hintHost': 'Auf GitHub gespeichert · V schaltet die aktuelle Datei um', + 'viewed.saving': 'Wird auf GitHub gespeichert…', + 'viewed.unavailable': 'Der Ansichtsstatus konnte nicht von GitHub gelesen werden', + 'viewed.readFailed': 'Der Ansichtsstatus konnte nicht von GitHub gelesen werden, daher lassen sich keine Dateien markieren: {message}', + 'viewed.syncFailed': 'Die Ansichtsmarkierung konnte nicht auf GitHub gespeichert werden: {message}', + 'viewed.syncStale': 'Der PR hat neue Commits, daher wurde die Ansichtsmarkierung nicht gespeichert. Aktualisieren und die Datei erneut markieren.', 'commits.all': 'Alle Commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} Commits', @@ -2379,7 +2697,6 @@ export const ru: Record = { 'change.review.changesRequested': 'Запрошены изменения', 'change.review.required': 'Требуется ревью', 'change.review.none': 'Ревью не запрошено', - 'change.review.threads': '{review} · не решено: {count}', 'change.merge.mergeable': 'Нет конфликтов', 'change.merge.conflicting': 'Конфликты с {base}', 'change.merge.unknown': 'Проверка конфликтов', @@ -2395,6 +2712,54 @@ export const ru: Record = { 'change.mergeNote.rebase': 'Перенести каждый коммит на {base}', 'change.mergeConfirm': 'Подтвердить слияние', 'change.mergeChanged': 'Появились новые коммиты. Проверьте их перед повторным открытием меню слияния', + 'checks.allPassed': 'Все проверки пройдены: {count}', + 'checks.showQuiet': 'Показать ещё {count} (пройдены, пропущены)', + 'reviewers.requestMore': 'Запросить ревью у другого участника…', + 'change.threads': 'Нерешённых обсуждений: {count}', + 'issues.label': 'Связанные задачи', + 'issues.separator': ', ', + 'issues.more': ' и другие', + 'issues.aria': 'Открыть задачу {label}: {title}', + 'checks.group.failed': 'С ошибкой', + 'checks.group.running': 'Выполняются', + 'checks.group.passed': 'Пройдены', + 'checks.group.cancelled': 'Отменены', + 'checks.group.other': 'Пропущены и прочие', + 'checks.rerunFailed': 'Перезапустить упавшие', + 'toast.rerunRequested': 'Запрошен перезапуск проверок {name}', + 'toast.rerunFailed': 'Не удалось перезапустить проверки: {message}', + 'toast.rerunStale': 'В {name} появились новые коммиты. Посмотрите проверки нового коммита перед перезапуском.', + 'reviewers.rerequestAria': 'Снова запросить ревью у {login}', + 'reviewers.pending': 'Ожидает', + 'reviewers.approved': 'Одобрено', + 'reviewers.changesRequested': 'Нужны правки', + 'reviewers.commented': 'Прокомментировал', + 'reviewers.dismissed': 'Отклонено', + 'reviewers.older': 'До последнего коммита', + 'reviewers.codeOwner': 'Владелец кода', + 'reviewers.team': 'Команда', + 'reviewers.bot': 'Бот', + 'reviewers.truncated': 'Показаны не все ревьюеры; откройте запрос, чтобы увидеть всех', + 'reviewers.none': 'Ревьюеров пока нет', + 'reviewers.search': 'Поиск участников', + 'reviewers.loading': 'Загрузка участников', + 'reviewers.loadFailed': 'Не удалось получить список участников', + 'reviewers.empty': 'Нет подходящих участников', + 'reviewers.suggested': 'Предложен', + 'toast.reviewRequested': 'Запрошено ревью {name} у {login}', + 'toast.reviewRequestFailed': 'Не удалось запросить ревью: {message}', + 'branch.behind': 'Отстаёт от {base}', + 'branch.update': 'Обновить ветку', + 'branch.updateTitle': 'Обновить {head} новыми коммитами из {base}', + 'branch.method.merge': 'Обновить коммитом слияния', + 'branch.method.rebase': 'Обновить через rebase', + 'branch.note.merge': 'Добавляет в ветку коммит слияния', + 'branch.note.rebase': 'Переносит коммиты ветки на {base}, переписывая их', + 'branch.confirm': 'Подтвердить обновление', + 'branch.changed': 'Появились новые коммиты. Проверьте их и откройте меню снова.', + 'toast.branchUpdated': 'Начато обновление ветки {name}', + 'toast.branchUpdateFailed': 'Не удалось обновить ветку: {message}', + 'toast.branchUpdateStale': 'В {name} появились новые коммиты. Проверьте их перед обновлением.', 'diff.tab': 'Изменения', 'diff.tabNumbered': 'Изменения в #{number}', 'diff.scope.branch': 'Ветка', @@ -2436,6 +2801,12 @@ export const ru: Record = { 'viewed.progress': 'Просмотрено {viewed} из {total}', 'viewed.progressAria': 'Просмотренные файлы', 'viewed.saveFailed': 'Не удалось сохранить отметку о просмотре', + 'viewed.hintHost': 'Сохраняется на GitHub · V переключает текущий файл', + 'viewed.saving': 'Сохранение на GitHub…', + 'viewed.unavailable': 'Не удалось прочитать отметки о просмотре с GitHub', + 'viewed.readFailed': 'Не удалось прочитать отметки о просмотре с GitHub, поэтому файлы нельзя отметить: {message}', + 'viewed.syncFailed': 'Не удалось сохранить отметку о просмотре на GitHub: {message}', + 'viewed.syncStale': 'В PR появились новые коммиты, поэтому отметка о просмотре не сохранена. Обновите и отметьте файл снова.', 'commits.all': 'Все коммиты', 'commits.range': '{from}…{to}', 'commits.count': 'Коммитов: {count}', @@ -2751,7 +3122,6 @@ export const pt: Record = { 'change.review.changesRequested': 'Alterações solicitadas', 'change.review.required': 'Revisão necessária', 'change.review.none': 'Nenhuma revisão solicitada', - 'change.review.threads': '{review} · {count} não resolvidas', 'change.merge.mergeable': 'Sem conflitos', 'change.merge.conflicting': 'Conflitos com {base}', 'change.merge.unknown': 'Verificando conflitos', @@ -2767,6 +3137,54 @@ export const pt: Record = { 'change.mergeNote.rebase': 'Reaplicar cada commit sobre {base}', 'change.mergeConfirm': 'Confirmar merge', 'change.mergeChanged': 'Há novos commits. Revise-os antes de reabrir o menu de merge', + 'checks.allPassed': 'Todas as {count} verificações passaram', + 'checks.showQuiet': 'Mostrar mais {count} (aprovadas, ignoradas)', + 'reviewers.requestMore': 'Pedir revisão a outra pessoa…', + 'change.threads': '{count} conversas não resolvidas', + 'issues.label': 'Issues vinculadas', + 'issues.separator': ', ', + 'issues.more': ' e outras', + 'issues.aria': 'Abrir issue {label}: {title}', + 'checks.group.failed': 'Com falha', + 'checks.group.running': 'Em andamento', + 'checks.group.passed': 'Aprovadas', + 'checks.group.cancelled': 'Canceladas', + 'checks.group.other': 'Ignoradas e outras', + 'checks.rerunFailed': 'Reexecutar com falha', + 'toast.rerunRequested': 'Reexecução das verificações de {name} solicitada', + 'toast.rerunFailed': 'Não foi possível reexecutar as verificações: {message}', + 'toast.rerunStale': '{name} tem novos commits. Veja as verificações do novo commit antes de reexecutar.', + 'reviewers.rerequestAria': 'Pedir revisão novamente a {login}', + 'reviewers.pending': 'Aguardando', + 'reviewers.approved': 'Aprovado', + 'reviewers.changesRequested': 'Alterações pedidas', + 'reviewers.commented': 'Comentou', + 'reviewers.dismissed': 'Descartada', + 'reviewers.older': 'Anterior ao último commit', + 'reviewers.codeOwner': 'Dono do código', + 'reviewers.team': 'Equipe', + 'reviewers.bot': 'Bot', + 'reviewers.truncated': 'Nem todos os revisores aparecem; abra a solicitação para ver todos', + 'reviewers.none': 'Ainda não há revisores', + 'reviewers.search': 'Pesquisar pessoas', + 'reviewers.loading': 'Carregando pessoas', + 'reviewers.loadFailed': 'Não foi possível listar as pessoas', + 'reviewers.empty': 'Nenhuma pessoa corresponde', + 'reviewers.suggested': 'Sugerido', + 'toast.reviewRequested': 'Revisão de {name} pedida a {login}', + 'toast.reviewRequestFailed': 'Não foi possível pedir a revisão: {message}', + 'branch.behind': 'Atrás de {base}', + 'branch.update': 'Atualizar branch', + 'branch.updateTitle': 'Atualizar {head} com os novos commits de {base}', + 'branch.method.merge': 'Atualizar com commit de merge', + 'branch.method.rebase': 'Atualizar com rebase', + 'branch.note.merge': 'Adiciona um commit de merge ao branch', + 'branch.note.rebase': 'Faz rebase dos commits do branch sobre {base}, reescrevendo-os', + 'branch.confirm': 'Confirmar atualização', + 'branch.changed': 'Chegaram novos commits. Revise-os e abra este menu novamente.', + 'toast.branchUpdated': 'Atualização do branch de {name} iniciada', + 'toast.branchUpdateFailed': 'Não foi possível atualizar o branch: {message}', + 'toast.branchUpdateStale': '{name} tem novos commits. Revise-os antes de atualizar.', 'diff.tab': 'Alterações', 'diff.tabNumbered': 'Alterações em #{number}', 'diff.scope.branch': 'Branch', @@ -2808,6 +3226,12 @@ export const pt: Record = { 'viewed.progress': '{viewed} / {total} revisados', 'viewed.progressAria': 'Arquivos revisados', 'viewed.saveFailed': 'Não foi possível salvar o estado de revisão', + 'viewed.hintHost': 'Salvo no GitHub · Pressione V para alternar o arquivo atual', + 'viewed.saving': 'Salvando no GitHub…', + 'viewed.unavailable': 'Não foi possível ler de GitHub quais arquivos foram revisados', + 'viewed.readFailed': 'Não foi possível ler de GitHub quais arquivos foram revisados, então não é possível marcá-los: {message}', + 'viewed.syncFailed': 'Não foi possível salvar a marca de revisão no GitHub: {message}', + 'viewed.syncStale': 'A PR tem novos commits, então a marca de revisão não foi salva. Atualize e marque o arquivo novamente.', 'commits.all': 'Todos os commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 736831bea2..7dfa5311b4 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -224,6 +224,29 @@ function registerUi(ctx: Context): void { else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.mergeStale', { params: { name: nameOf(entry) } }) else notices.report('toast.mergeFailed', { params: { message: result.error.message } }) }, + rerunChecks: async (entry, request) => { + const result = await ctx.remote.forgePanel.rerunChecks(sessionId, entry.url, request) + if (result.ok) notices.report('toast.rerunRequested', { tone: 'success', params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.rerunStale', { params: { name: nameOf(entry) } }) + else notices.report('toast.rerunFailed', { params: { message: result.error.message } }) + }, + requestReviews: async (entry, reviewers) => { + const result = await ctx.remote.forgePanel.requestReviews(sessionId, entry.url, reviewers) + const login = reviewers.map(reviewer => reviewer.login).join(', ') + if (result.ok) notices.report('toast.reviewRequested', { tone: 'success', params: { name: nameOf(entry), login } }) + else notices.report('toast.reviewRequestFailed', { params: { message: result.error.message } }) + }, + reviewerCandidates: async (url, query, signal) => { + const result = await ctx.remote.forgePanel.reviewerCandidates(sessionId, url, query, signal) + if (!result.ok) throw new Error(result.error.message) + return result.value + }, + updateBranch: async (entry, request) => { + const result = await ctx.remote.forgePanel.updateBranch(sessionId, entry.url, request.method, request.headSha) + if (result.ok) notices.report('toast.branchUpdated', { tone: 'success', params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.branchUpdateStale', { params: { name: nameOf(entry) } }) + else notices.report('toast.branchUpdateFailed', { params: { message: result.error.message } }) + }, restore: () => { void restore(sessionId).then((message) => { if (message !== undefined) notices.report('toast.restoreFailed', { params: { message } }) @@ -248,6 +271,8 @@ function registerUi(ctx: Context): void { changeRequestDiff: (url, commits, signal) => ctx.remote.forgePanel.changeRequestDiff(sessionId, url, commits, signal), changeRequestCommits: (url, signal) => ctx.remote.forgePanel.changeRequestCommits(sessionId, url, signal), viewedFiles: store.viewed, + changeRequestViewed: (url, headSha, signal) => ctx.remote.forgePanel.changeRequestViewed(sessionId, url, headSha, signal), + setFileViewed: (url, request) => ctx.remote.forgePanel.setFileViewed(sessionId, url, request), changeRequestText: (url, commit, path) => ctx.remote.forgePanel.changeRequestText(sessionId, url, commit, path), addReviewToInput: selection => addReviewToInput(sessionId, selection), addThreadToInput: (thread, url, range) => addThreadToInput(sessionId, thread, url, range), diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index c0ebce2347..3e6af9b8ad 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,8 +6,9 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeLineComment, ForgeReviewData, - ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeMethod, + BranchUpdateMethod, ChangeRequestRef, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, + ForgeLineComment, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, + ForgeReviewWriteResult, ForgeViewedFiles, ForgeViewedRequest, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' @@ -461,6 +462,48 @@ export class ForgePanelController extends TypertRemoteService { return text } + /** + * 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 { + signal.throwIfAborted() + const result = await this.home.forge.viewedFiles(this.bound(session, url).ref, headSha, signal) + if (result === undefined) return null + if ('code' in result) { + throw new RemoteError(result.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/viewed-failed', result.message, {}) + } + return result + } + + /** + * 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. + */ + @Remote + async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise { + signal.throwIfAborted() + const { ref } = this.bound(session, url) + if (request.path === '') throw new Error('Invalid viewed file') + const failure = await this.home.forge.setViewed(ref, request, signal) + if (failure !== undefined) throw actionError(failure) + } + /** * 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 @@ -588,6 +631,82 @@ export class ForgePanelController extends TypertRemoteService { if (failure !== undefined) throw actionError(failure) } + /** + * 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. + */ + @Remote + async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise { + signal.throwIfAborted() + const failure = await this.home.forge.rerunChecks(this.bound(session, url).ref, request, signal) + if (failure !== undefined) throw actionError(failure) + } + + /** + * 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. + */ + @Remote + async requestReviews( + session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, + ): Promise { + signal.throwIfAborted() + const { ref } = this.bound(session, url) + if (reviewers.length === 0 || reviewers.some(reviewer => reviewer.login.trim() === '')) throw new Error('Invalid reviewers') + const failure = await this.home.forge.requestReviews(ref, { reviewers }, signal) + if (failure !== undefined) throw actionError(failure) + } + + /** + * 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 { + signal.throwIfAborted() + const result = await this.home.forge.reviewerCandidates(this.bound(session, url).ref, query, signal) + if ('code' in result) throw new RemoteError('forgePanel/reviewers-failed', result.message, {}) + return result + } + + /** + * 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. + */ + @Remote + async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const failure = await this.home.forge.updateBranch(this.bound(session, url).ref, { method, headSha }, signal) + if (failure !== undefined) throw actionError(failure) + } + /** * 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/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 1588277207..4ea0637fdc 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -446,8 +446,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' { /** * The change request's head is no longer the commit the request named: the head the user confirmed for a merge, * the head displayed for complete checks, the head of the latest status for a diff, or the head of the displayed - * diff for review threads. A diff or review read the host refuses polls the change request again at once, so a - * later status names the current head. + * diff for review threads and viewed marks. A diff, review, or viewed mark read the host refuses polls the change + * request again at once, so a later status names the current head. */ 'forgePanel/stale-head': Record /** The code host refused the change or could not be reached; the message gives the host's reason. */ @@ -476,6 +476,10 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/commits-missing': Record /** A chosen commit after the first lacks the commit listed before it as its first parent, so two ends cannot name the run. */ 'forgePanel/commits-not-linear': Record + /** The code host did not provide the signed-in user's viewed marks on the change request's files; the message says why. */ + 'forgePanel/viewed-failed': Record + /** The code host did not list the accounts a review can be requested from; the message says why. */ + 'forgePanel/reviewers-failed': Record /** The code host's provider cannot read review threads, so the changes view shows none. */ 'forgePanel/review-unsupported': Record /** The code host did not provide the change request's review threads, or its status has not been read yet; the message says why. */ diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index 8e11e4c0d8..6736483ad2 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -7,6 +7,7 @@ import type { ForgeFailure, MergeRequest } from '@deepseek-ai/dsh-experimental-f import { ChangeRequestCard, type ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx' import { en } from '../src/client/locales.ts' import css from '../src/client/ForgeTab.module.css' +import overview from '../src/client/ChangeRequestOverview.module.css' import type { ForgePanelChangeRequest } from '../src/types.ts' import { check, entry, snapshot, unserved } from './client-fixtures.client.ts' @@ -45,19 +46,28 @@ function metaOf(b: ReturnType): HTMLElement { return meta } -/** The value a details row shows next to its label. */ +/** The value a details row shows after its name, which only assistive technology reads. */ function rowValue(item: HTMLElement, label: string): HTMLElement { const value = within(item).getByText(label).nextElementSibling - if (!(value instanceof HTMLElement)) throw new Error(`no value next to ${label}`) + if (!(value instanceof HTMLElement)) throw new Error(`no value after ${label}`) return value } -/** Outcome, name, time, and whether it opens a link, of each check the open checks list shows, in display order. */ +/** The tone of the row named `label`. */ +function rowTone(item: HTMLElement, label: string): string | null { + return within(item).getByText(label).closest(`.${css.rowValue}`)?.getAttribute('data-tone') ?? null +} + +/** + * Each row of the open checks menu in display order: a check as its outcome, name, time, and whether it opens a link; + * any other row as its text. + */ function checkRows(): string[] { return screen.queryAllByRole('menuitem').map((row) => { - const [name, time] = row.querySelector(`.${css.checkItem}`)?.children ?? [] - const state = row.querySelector('[data-forge-check]')?.getAttribute('data-forge-check') ?? '' - return [state, name?.textContent, time?.textContent, row.hasAttribute('disabled') ? 'no link' : 'link'].join('|') + const item = row.querySelector('[data-forge-check-item]') + if (item === null) return row.textContent ?? '' + const [name, time] = item.children + return [item.getAttribute('data-forge-check-item'), name?.textContent, time?.textContent, row.hasAttribute('disabled') ? 'no link' : 'link'].join('|') }) } @@ -226,8 +236,12 @@ describe('expanded ChangeRequestCard', () => { expect(rowValue(b.item, en['change.row.checks']).textContent).toBe(en['change.ci.none']) expect(within(b.item).getByText(en['change.row.checks']).closest('button')).toBeNull() expect(rowValue(b.item, en['change.row.review']).textContent).toBe(en['change.review.none']) + // Without reviewers or the right to request reviews, the review row opens nothing. + expect(within(b.item).getByText(en['change.row.review']).closest('button')).toBeNull() expect(rowValue(b.item, en['change.row.merge']).textContent).toBe(en['change.merge.mergeable']) - for (const label of [en['change.row.review'], en['change.row.merge']]) expect(rowValue(b.item, label).getAttribute('data-tone')).toBeNull() + for (const label of [en['change.row.review'], en['change.row.merge']]) expect(rowTone(b.item, label)).toBeNull() + expect(b.item.querySelector('[data-forge-threads]')).toBeNull() + expect(b.item.querySelector('[data-forge-closing-issues]')).toBeNull() expect(within(b.item).getByText('+12,345')).toBeTruthy() expect(within(b.item).getByText(`${MINUS}3`)).toBeTruthy() @@ -249,26 +263,39 @@ describe('expanded ChangeRequestCard', () => { ['merge conflicts', { mergeability: 'conflicting' }, 'Conflicts with main', 'error'], ['an unknown mergeability', { mergeability: 'unknown' }, en['change.merge.unknown'], null], ] as const)('states %s of an open change request', (_label, overrides, text, tone) => { - const value = rowValue(card(entry(1, snapshot(1, overrides)), { expanded: true }).item, en['change.row.merge']) - expect(value.textContent).toBe(text) - expect(value.getAttribute('data-tone')).toBe(tone) + const { item } = card(entry(1, snapshot(1, overrides)), { expanded: true }) + expect(rowValue(item, en['change.row.merge']).textContent).toBe(text) + expect(rowTone(item, en['change.row.merge'])).toBe(tone) }) it.each([ ['an approval', { reviewDecision: 'approved' }, en['change.review.approved'], 'success'], ['a required review', { reviewDecision: 'review-required' }, en['change.review.required'], null], ['requested changes', { reviewDecision: 'changes-requested' }, en['change.review.changesRequested'], 'error'], - ['an approval with unresolved threads', { reviewDecision: 'approved', unresolvedThreads: 2 }, 'Approved · 2 unresolved', 'success'], - ['requested changes with an unresolved thread', { reviewDecision: 'changes-requested', unresolvedThreads: 1 }, - 'Changes requested · 1 unresolved', 'error'], - ['more threads than the provider counted', { reviewDecision: 'review-required', unresolvedThreads: 1200, threadsTruncated: true }, - 'Review required · 1,200+ unresolved', null], - ['uncounted threads after resolved ones', { reviewDecision: 'approved', unresolvedThreads: 0, threadsTruncated: true }, - 'Approved · 0+ unresolved', 'success'], ] as const)('states the review of %s', (_label, overrides, text, tone) => { - const value = rowValue(card(entry(1, snapshot(1, overrides)), { expanded: true }).item, en['change.row.review']) - expect(value.textContent).toBe(text) - expect(value.getAttribute('data-tone')).toBe(tone) + const { item } = card(entry(1, snapshot(1, overrides)), { expanded: true }) + expect(rowValue(item, en['change.row.review']).textContent).toBe(text) + expect(rowTone(item, en['change.row.review'])).toBe(tone) + }) + + it.each([ + ['unresolved threads', { unresolvedThreads: 2 }, '2'], + ['more threads than the provider counted', { unresolvedThreads: 1200, threadsTruncated: true }, '1,200+'], + ['uncounted threads after resolved ones', { unresolvedThreads: 0, threadsTruncated: true }, '0+'], + ] as const)('counts %s at the end of the changes row', (_label, overrides, count) => { + const { item } = card(entry(1, snapshot(1, overrides)), { expanded: true }) + const threads = item.querySelector('[data-forge-threads]') + expect(threads?.getAttribute('data-forge-threads')).toBe(count) + expect(threads?.textContent).toBe(count) + expect(threads?.closest(`.${css.rowTrailing}`)?.parentElement?.textContent).toContain('+12') + }) + + it('names the unresolved threads of a row that opens the changes view in its description', () => { + const { item } = card(entry(1, snapshot(1, { unresolvedThreads: 2 })), { expanded: true, actions: { viewChanges: vi.fn() } }) + const row = within(item).getByRole('button', { name: /^View the changes of #1/ }) + expect(row.getAttribute('aria-describedby')).not.toBeNull() + expect(document.getElementById(row.getAttribute('aria-describedby') ?? '')?.textContent).toBe('2 unresolved threads') + expect(item.querySelector('[data-forge-threads]')?.getAttribute('aria-hidden')).toBe('true') }) it.each([ @@ -276,16 +303,16 @@ describe('expanded ChangeRequestCard', () => { ['closed', { state: 'closed' }, en['change.state.closed']], ] as const)('states a %s change request in one line instead of its checks, review, and merge rows', (tone, overrides, text) => { const b = card(entry(1, snapshot(1, { ...overrides, mergeability: 'conflicting', reviewDecision: 'changes-requested' })), { expanded: true }) - const line = within(b.item).getByText(text, { selector: `.${css.rowValue}` }) - expect(line.getAttribute('data-tone')).toBe(tone) + const line = within(b.item).getByText(text, { selector: `.${css.ellipsis}` }) + expect(line.closest(`.${css.rowValue}`)?.getAttribute('data-tone')).toBe(tone) for (const label of [en['change.row.checks'], en['change.row.review'], en['change.row.merge']]) expect(within(b.item).queryByText(label)).toBeNull() expect(within(b.item).getByText('+12')).toBeTruthy() }) it.each([ ['a partial preview', true, '8 checks loaded; more available', null], - ['a complete list', false, '1 failed · 2 running · 2 passed · 1 cancelled · 2 other', 'error'], - ] as const)('lists %s with failures first, then running checks, and their times and links', (_label, checksTruncated, text, tone) => { + ['a complete list', false, '1 failed · 2 running · 1 cancelled', 'error'], + ] as const)('lists %s by group, the ones needing attention first and the rest on request', (_label, checksTruncated, text, tone) => { const checks = [ check('build'), check('docs', { state: 'neutral' }), @@ -298,10 +325,9 @@ describe('expanded ChangeRequestCard', () => { ] const b = card(entry(1, snapshot(1, { checks, checksRollup: 'failure', checksTruncated })), { expanded: true }) const toggle = within(b.item).getByText(en['change.row.checks']).closest('button') - if (toggle === null) throw new Error('the checks row does not open a list') - const summary = rowValue(b.item, en['change.row.checks']) - expect(summary.textContent).toBe(text) - expect(summary.getAttribute('data-tone')).toBe(tone) + if (toggle === null) throw new Error('the checks row does not open a menu') + expect(rowValue(b.item, en['change.row.checks']).textContent).toBe(text) + expect(rowTone(b.item, en['change.row.checks'])).toBe(tone) // The row leads with the combined outcome. expect(toggle.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('failure') expect(toggle.getAttribute('aria-expanded')).toBe('false') @@ -309,22 +335,29 @@ describe('expanded ChangeRequestCard', () => { fireEvent.click(toggle) expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(screen.getAllByRole('group').map(group => group.getAttribute('aria-label'))).toEqual(['Failed', 'Running', 'Cancelled']) expect(checkRows()).toEqual([ 'failure|lint|1h 0m|link', 'pending|deploy|Queued|no link', 'pending|test|Running|no link', + 'cancelled|perf|1h 30m|no link', + 'Show 4 more (passed, skipped)', + ]) + fireEvent.click(screen.getByRole('menuitem', { name: 'Show 4 more (passed, skipped)' })) + expect(checkRows().slice(4)).toEqual([ 'success|build|1m 5s|no link', 'success|package||no link', 'neutral|docs|1m 5s|no link', 'skipped|e2e||no link', - 'cancelled|perf|1h 30m|no link', ]) - expect(screen.queryAllByText('8 checks loaded; more available')).toHaveLength(checksTruncated ? 2 : 0) fireEvent.click(screen.getAllByRole('menuitem')[0]!) expect(b.openLink).toHaveBeenCalledWith('https://ci.example.test/lint') expect(toggle.getAttribute('aria-expanded')).toBe('false') expect(checkRows()).toEqual([]) + // A reopened menu lists the rest on request again. + fireEvent.click(toggle) + expect(checkRows().at(-1)).toBe('Show 4 more (passed, skipped)') }) it.each([ @@ -341,21 +374,19 @@ describe('expanded ChangeRequestCard', () => { fireEvent.click(within(b.item).getByText(en['change.row.checks'])) expect(readChecks).toHaveBeenCalledWith(partial.url, partial.headSha, expect.any(AbortSignal)) expect(screen.getByText('old lint')).toBeTruthy() - const loading = screen.getByRole('menuitem', { name: en['change.checks.loading'] }) - expect(loading).toHaveProperty('disabled', true) - fireEvent.click(loading) + expect(screen.getByRole('status').textContent).toBe(en['change.checks.loading']) expect(readChecks).toHaveBeenCalledTimes(1) await act(async () => { waiting.reject(failure); await Promise.resolve() }) expect(screen.getByText('old lint')).toBeTruthy() expect(screen.getByText(`Could not load more checks: ${message}`)).toBeTruthy() - await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en['change.checks.retry'] })) }) + await act(async () => { fireEvent.click(screen.getByRole('button', { name: en['change.checks.retry'] })) }) expect(screen.queryByText('old lint')).toBeNull() - expect(screen.getByText('current lint')).toBeTruthy() - expect(rowValue(b.item, en['change.row.checks']).textContent).toBe('1 passed') + expect(checkRows()).toEqual(['Show 1 more (passed, skipped)']) + expect(rowValue(b.item, en['change.row.checks']).textContent).toBe('All 1 checks passed') }) - it('keeps a reopened list loading when its cancelled read rejects late', async () => { - const partial = snapshot(1, { checks: [check('preview')], checksTruncated: true }) + it('keeps a reopened menu loading when its cancelled read rejects late', async () => { + const partial = snapshot(1, { checks: [check('preview', { state: 'failure' })], checksTruncated: true }) const older = Promise.withResolvers>() const newer = Promise.withResolvers>() const readChecks = vi.fn>() @@ -374,9 +405,9 @@ describe('expanded ChangeRequestCard', () => { expect(screen.getByText(en['change.checks.loading'])).toBeTruthy() expect(screen.getByText('preview')).toBeTruthy() expect(screen.queryByText('Could not load more checks: cancelled request')).toBeNull() - expect(screen.queryByRole('menuitem', { name: en['change.checks.retry'] })).toBeNull() + expect(screen.queryByRole('button', { name: en['change.checks.retry'] })).toBeNull() - await act(async () => { newer.resolve(snapshot(1, { checks: [check('current result')] })); await Promise.resolve() }) + await act(async () => { newer.resolve(snapshot(1, { checks: [check('current result', { state: 'failure' })] })); await Promise.resolve() }) expect(screen.getByText('current result')).toBeTruthy() expect(screen.queryByText('preview')).toBeNull() }) @@ -393,38 +424,36 @@ describe('expanded ChangeRequestCard', () => { else b.view.rerender(
) expect(signal.aborted).toBe(true) - await act(async () => { pending.resolve(snapshot(1, { checks: [check('late result')] })); await Promise.resolve() }) + await act(async () => { pending.resolve(snapshot(1, { checks: [check('late result', { state: 'failure' })] })); await Promise.resolve() }) expect(screen.queryByText('late result')).toBeNull() }) - it('closes the checks list from its row and from an outside press', () => { - const b = card(entry(1, snapshot(1, { checks: [check('build')] })), { expanded: true }) + it('closes the checks menu from its row and from an outside press', () => { + const b = card(entry(1, snapshot(1, { checks: [check('build', { state: 'failure' })] })), { expanded: true }) const toggle = within(b.item).getByText(en['change.row.checks']).closest('button') - if (toggle === null) throw new Error('the checks row does not open a list') + if (toggle === null) throw new Error('the checks row does not open a menu') fireEvent.click(toggle) fireEvent.click(toggle) expect(checkRows()).toEqual([]) fireEvent.click(toggle) - expect(checkRows()).toEqual(['success|build|1m 5s|no link']) + expect(checkRows()).toEqual(['failure|build|1m 5s|no link']) fireEvent.pointerDown(document.body) expect(checkRows()).toEqual([]) expect(b.openLink).not.toHaveBeenCalled() }) it.each([ - ['passed checks', [check('build'), check('test')], '2 passed', ['success|build|1m 5s|no link', 'success|test|1m 5s|no link']], + ['passed checks', [check('build'), check('test')], 'All 2 checks passed', ['Show 2 more (passed, skipped)']], ['running and skipped checks', [ check('docs', { state: 'skipped', startedAt: null, completedAt: null }), check('test', { state: 'pending', completedAt: null }), - ], '1 running · 1 other', ['pending|test|Running|no link', 'skipped|docs||no link']], - ])('counts %s without an error tone or a truncation note', (_label, checks, text, rows) => { + ], '1 running', ['pending|test|Running|no link', 'Show 1 more (passed, skipped)']], + ])('summarizes %s without an error tone', (_label, checks, text, rows) => { const b = card(entry(1, snapshot(1, { checks, checksRollup: 'pending' })), { expanded: true }) - const summary = rowValue(b.item, en['change.row.checks']) - expect(summary.textContent).toBe(text) - expect(summary.getAttribute('data-tone')).toBeNull() + expect(rowValue(b.item, en['change.row.checks']).textContent).toBe(text) + expect(rowTone(b.item, en['change.row.checks'])).toBeNull() fireEvent.click(within(b.item).getByText(en['change.row.checks'])) expect(checkRows()).toEqual(rows) - expect(screen.queryByText(/^Only the first/)).toBeNull() }) it('shows only the link actions before the first poll', () => { @@ -604,6 +633,7 @@ describe('ChangeRequestCard changes', () => { const b = card(value, { expanded: true, actions: { viewChanges } }) const button = within(b.item).getByRole('button', { name: 'View the changes of #7: 12,345 lines added, 3 lines deleted' }) expect(button.textContent).toBe(`${en['change.row.changes']}+12,345${MINUS}3`) + expect(button.querySelector(`.${css.rowChevron}`)).not.toBeNull() fireEvent.click(button) expect(viewChanges).toHaveBeenCalledWith(value) }) @@ -632,6 +662,7 @@ describe('ChangeRequestCard layout', () => { const rows = b.item.querySelector(`.${css.rows}`) if (!(rows instanceof HTMLElement)) throw new Error('no rows') expect([...rows.children].map(row => row.textContent)).toEqual([en['change.state.closed'], `${en['change.row.changes']}+12${MINUS}3`]) + expect(rows.querySelector(`.${overview.rowAnchor}`)).toBeNull() }) it('shows a neutral check glyph without checks', () => { diff --git a/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx new file mode 100644 index 0000000000..4e1439ddf2 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx @@ -0,0 +1,326 @@ +// @vitest-environment jsdom +/** + * Overview rows of an expanded change request card: rerunning failed checks, the reviewers and review requests, the branch + * update, and linked issues. + */ +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { + ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCheckId, ForgeReviewerCandidate, +} from '@deepseek-ai/dsh-experimental-forge/types' +import { ChangeRequestCard, type ChangeRequestActions } from '../src/client/ChangeRequestCard.tsx' +import { en } from '../src/client/locales.ts' +import css from '../src/client/ForgeTab.module.css' +import overview from '../src/client/ChangeRequestOverview.module.css' +import { check, entry, snapshot } from './client-fixtures.client.ts' + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +const t = makeTranslate(en) +const HEAD = 'a'.repeat(40) + +function card(value: ChangeRequestSnapshot, actions: Partial = {}) { + const openLink = vi.fn<(url: string) => void>() + const full: ChangeRequestActions = { openLink, copyLink: vi.fn(), retry: vi.fn(), ...actions } + const subject = entry(value.ref.number, value) + const view = render( +
, + ) + const item = view.container.querySelector('[data-forge-change]') + if (!(item instanceof HTMLElement)) throw new Error('no card') + const rerender = (next: ChangeRequestSnapshot): void => { + view.rerender(
) + } + return { view, item, subject, openLink, rerender } +} + +function reviewer(login: string, overrides: Partial = {}): ChangeRequestReviewer { + return { kind: 'user', login, avatarUrl: null, requested: false, codeOwner: false, verdict: null, reviewedSha: null, ...overrides } +} + +/** Settle pending promises and timers of a search. */ +async function wait(ms = 0): Promise { + await act(async () => { await new Promise(resolve => setTimeout(resolve, ms)) }) +} + +describe('rerunning failed checks', () => { + const failed = check('lint', { state: 'failure', rerun: 'actions:7' as ForgeCheckId }) + + it('offers to rerun the failed checks that name a rerun, and runs one rerun at a time', async () => { + const done = Promise.withResolvers() + const rerunChecks = vi.fn>(() => done.promise) + const b = card(snapshot(7, { checks: [failed], checksRollup: 'failure', canRerunChecks: true }), { rerunChecks }) + const row = b.item.querySelector('[data-forge-checks]') as HTMLElement + fireEvent.click(row) + fireEvent.click(screen.getByRole('menuitem', { name: en['checks.rerunFailed'] })) + expect(rerunChecks).toHaveBeenCalledWith(b.subject, { headSha: HEAD }) + expect(screen.queryByRole('menu')).toBeNull() + fireEvent.click(row) + expect(screen.getByRole('menuitem', { name: en['checks.rerunFailed'] }).hasAttribute('disabled')).toBe(true) + await act(async () => { done.resolve(undefined); await Promise.resolve() }) + expect(screen.getByRole('menuitem', { name: en['checks.rerunFailed'] }).hasAttribute('disabled')).toBe(false) + }) + + it.each([ + ['the viewer may not rerun checks', { canRerunChecks: false }, true], + ['no failed check names a rerun', { checks: [check('lint', { state: 'failure' }), check('test', { rerun: 'actions:7' as ForgeCheckId })] }, true], + ['the surface cannot rerun checks', {}, false], + ])('does not offer it when %s', (_label, overrides, withAction) => { + const b = card(snapshot(7, { checks: [failed], checksRollup: 'failure', canRerunChecks: true, ...overrides }), + withAction ? { rerunChecks: vi.fn() } : {}) + fireEvent.click(b.item.querySelector('[data-forge-checks]') as HTMLElement) + expect(screen.queryByRole('menuitem', { name: en['checks.rerunFailed'] })).toBeNull() + }) + + it('opens a menu for a list the poll read only in part, though none of it was read yet', () => { + const b = card(snapshot(7, { checks: [], checksTruncated: true, checksRollup: 'none' })) + const row = b.item.querySelector('[data-forge-checks]') as HTMLElement + expect(row.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('neutral') + fireEvent.click(row) + expect(screen.getByRole('menu')).toBeDefined() + }) + + it('lists only skipped checks on request with the skipped glyph', () => { + const b = card(snapshot(7, { checks: [check('docs', { state: 'skipped' })], checksRollup: 'success' })) + fireEvent.click(b.item.querySelector('[data-forge-checks]') as HTMLElement) + const more = screen.getByRole('menuitem', { name: 'Show 1 more (passed, skipped)' }) + expect(more.querySelector('[data-forge-check]')?.getAttribute('data-forge-check')).toBe('skipped') + }) +}) + +describe('reviewers', () => { + const list = [ + reviewer('lin', { requested: true, avatarUrl: 'https://avatars.example/lin' }), + reviewer('octo/forge', { kind: 'team', requested: true, codeOwner: true }), + reviewer('review-bot', { kind: 'bot', verdict: 'commented', reviewedSha: HEAD }), + reviewer('zhou', { verdict: 'changes-requested', reviewedSha: 'b'.repeat(40) }), + reviewer('qian', { verdict: 'approved', reviewedSha: HEAD }), + reviewer('wang', { verdict: 'dismissed', reviewedSha: null }), + ] + const lines = (): string[] => [...document.querySelectorAll('[data-forge-reviewer]')].map(line => line.textContent ?? '') + + it('shows the first avatars and counts the rest, falling back to an initial when an image fails', () => { + const b = card(snapshot(7, { reviewers: list, reviewDecision: 'review-required' })) + const avatars = b.item.querySelector(`.${overview.avatars}`) as HTMLElement + expect([...avatars.children].map(node => node.tagName === 'IMG' ? 'img' : node.textContent)).toEqual(['img', 'O', 'R', '+3']) + fireEvent.error(avatars.querySelector('img') as HTMLImageElement) + expect(avatars.firstElementChild?.textContent).toBe('L') + }) + + it('lists each reviewer with their kind, outcome, and an outcome on an older commit, read only without the right to request', () => { + const b = card(snapshot(7, { reviewers: list })) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + // Without an avatar image, a line starts with the login's initial. + expect(lines()).toEqual([ + 'linAwaiting review', 'Oocto/forgeCode ownerAwaiting review', 'Rreview-botBotCommented', 'ZzhouChanges requestedBefore the latest commit', + 'QqianApproved', 'WwangDismissed', + ]) + const tones = [...document.querySelectorAll(`.${overview.outcome} > span:first-child`)].map(node => node.getAttribute('data-tone')) + expect(tones).toEqual(['pending', 'pending', null, 'error', 'success', null]) + expect(screen.queryAllByRole('menuitem')).toEqual([]) + }) + + it('names a team that is not a code owner as a team', () => { + const b = card(snapshot(7, { reviewers: [reviewer('octo/docs', { kind: 'team', verdict: 'approved', reviewedSha: HEAD })] })) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + expect(lines()).toEqual(['Oocto/docsTeamApproved']) + }) + + it('asks a reviewer again, leaving out bots and pending requests, and requests one review at a time', async () => { + const done = Promise.withResolvers() + const requestReviews = vi.fn>(() => done.promise) + const b = card(snapshot(7, { reviewers: list, canRequestReviews: true }), { requestReviews, reviewerCandidates: vi.fn() }) + const row = b.item.querySelector('[data-forge-review]') as HTMLButtonElement + fireEvent.click(row) + expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ + 'Re-request a review from zhou', 'Re-request a review from qian', 'Re-request a review from wang', en['reviewers.requestMore'], + ]) + fireEvent.click(screen.getByRole('menuitem', { name: 'Re-request a review from zhou' })) + expect(requestReviews).toHaveBeenCalledWith(b.subject, [list[3]]) + expect(row.disabled).toBe(true) + await act(async () => { done.resolve(undefined); await Promise.resolve() }) + expect(row.disabled).toBe(false) + }) + + it('opens the change request for reviewers it did not read, and states that there are none yet', () => { + const b = card(snapshot(7, { reviewers: [], reviewersTruncated: true, canRequestReviews: true }), { + requestReviews: vi.fn(), reviewerCandidates: vi.fn(), + }) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + expect(screen.getByText(en['reviewers.none'])).toBeDefined() + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.truncated'] })) + expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7') + }) + + it.each([ + ['no reviewers and no right to request', { reviewers: [] }, {}], + ['the right without the surface\'s actions', { reviewers: [], canRequestReviews: true }, { requestReviews: vi.fn() }], + ])('opens nothing with %s', (_label, overrides, actions) => { + const b = card(snapshot(7, overrides), actions) + expect(b.item.querySelector('[data-forge-review]')).toBeNull() + expect(within(b.item).getByText(en['change.row.review']).closest('button')).toBeNull() + }) + + it('searches accounts to request a review from, the suggestions first, and requests the chosen one', async () => { + const requestReviews = vi.fn>(async () => {}) + const people: ForgeReviewerCandidate[] = [ + { login: 'lin', name: 'Lin', avatarUrl: null, suggested: true }, + { login: 'mona', name: 'mona', avatarUrl: null, suggested: false }, + ] + const reviewerCandidates = vi.fn>() + .mockResolvedValueOnce(people) + .mockResolvedValueOnce([people[1]!]) + const b = card(snapshot(7, { canRequestReviews: true }), { requestReviews, reviewerCandidates }) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.requestMore'] })) + expect(screen.getByRole('status').textContent).toBe(en['reviewers.loading']) + await wait() + expect(reviewerCandidates).toHaveBeenCalledWith('https://github.com/octo/demo/pull/7', '', expect.any(AbortSignal)) + expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['LlinLinSuggested', 'Mmona']) + fireEvent.change(screen.getByRole('textbox', { name: en['reviewers.search'] }), { target: { value: 'mo' } }) + await wait(200) + expect(reviewerCandidates).toHaveBeenLastCalledWith('https://github.com/octo/demo/pull/7', 'mo', expect.any(AbortSignal)) + fireEvent.click(screen.getByRole('menuitem', { name: 'mona' })) + expect(requestReviews).toHaveBeenCalledWith(b.subject, [{ kind: 'user', login: 'mona' }]) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('picks the first account with Enter, keeps arrow and edge keys in the field, and leaves composition alone', async () => { + const requestReviews = vi.fn>(async () => {}) + const reviewerCandidates = vi.fn>(async () => [ + { login: 'lin', name: null, avatarUrl: null, suggested: false }, + ]) + const b = card(snapshot(7, { canRequestReviews: true }), { requestReviews, reviewerCandidates }) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.requestMore'] })) + const field = screen.getByRole('textbox', { name: en['reviewers.search'] }) + fireEvent.keyDown(field, { key: 'Enter' }) + expect(requestReviews).not.toHaveBeenCalled() + await wait() + for (const key of ['Home', 'End', 'ArrowLeft', 'ArrowRight', 'a']) fireEvent.keyDown(field, { key }) + fireEvent.keyDown(field, { key: 'Enter', isComposing: true }) + expect(requestReviews).not.toHaveBeenCalled() + fireEvent.keyDown(field, { key: 'Enter' }) + expect(requestReviews).toHaveBeenCalledWith(b.subject, [{ kind: 'user', login: 'lin' }]) + }) + + it('reports an empty or failed listing, retries, and ignores a listing that arrives after the menu closed', async () => { + const late = Promise.withResolvers() + const reviewerCandidates = vi.fn>() + .mockRejectedValueOnce(new Error('down')) + .mockResolvedValueOnce([]) + .mockReturnValueOnce(late.promise) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) + const b = card(snapshot(7, { canRequestReviews: true }), { requestReviews: vi.fn(), reviewerCandidates }) + const row = b.item.querySelector('[data-forge-review]') as HTMLElement + fireEvent.click(row) + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.requestMore'] })) + await wait() + expect(screen.getByText(en['reviewers.loadFailed'])).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: en.retry })) + await wait() + expect(screen.getByText(en['reviewers.empty'])).toBeDefined() + // A touch screen keeps its keyboard closed, so the field is not focused. + expect(document.activeElement).not.toBe(screen.getByRole('textbox', { name: en['reviewers.search'] })) + fireEvent.change(screen.getByRole('textbox', { name: en['reviewers.search'] }), { target: { value: 'x' } }) + await wait(200) + fireEvent.click(row) + await act(async () => { late.resolve([{ login: 'late', name: null, avatarUrl: null, suggested: false }]); await Promise.resolve() }) + late.promise.catch(() => {}) + expect(screen.queryByText('late')).toBeNull() + }) + + it('ignores a failed listing that arrives after the menu closed', async () => { + const late = Promise.withResolvers() + const b = card(snapshot(7, { canRequestReviews: true }), { requestReviews: vi.fn(), reviewerCandidates: vi.fn(() => late.promise) }) + const row = b.item.querySelector('[data-forge-review]') as HTMLElement + fireEvent.click(row) + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.requestMore'] })) + await wait() + fireEvent.click(row) + await act(async () => { late.reject(new Error('late')); await Promise.resolve() }) + expect(screen.queryByText(en['reviewers.loadFailed'])).toBeNull() + }) +}) + +describe('branch updates', () => { + const behind = (overrides: Partial = {}) => snapshot(7, { branchUpdates: ['merge', 'rebase'], ...overrides }) + + it('states that the head is behind and updates it with the chosen method at the confirmed head', async () => { + const done = Promise.withResolvers() + const updateBranch = vi.fn>(() => done.promise) + const b = card(behind(), { updateBranch }) + const row = b.item.querySelector('[data-forge-update-branch]') as HTMLButtonElement + expect(row.textContent).toBe(`${en['change.row.merge']}No conflicts · Behind main${en['branch.update']}`) + fireEvent.click(row) + expect(screen.getByText('Update feat with new commits from main')).toBeDefined() + fireEvent.click(screen.getByRole('menuitem', { name: /^Update with rebase/ })) + fireEvent.click(screen.getByRole('menuitem', { name: en['branch.confirm'] })) + expect(updateBranch).toHaveBeenCalledWith(b.subject, { method: 'rebase', headSha: HEAD }) + expect(row.disabled).toBe(true) + await act(async () => { done.resolve(undefined); await Promise.resolve() }) + expect(row.disabled).toBe(false) + }) + + it('refuses the confirmation once the head moved after the menu opened, and falls back to the usual method', () => { + const updateBranch = vi.fn>(async () => {}) + const b = card(behind(), { updateBranch }) + const row = (): HTMLElement => b.item.querySelector('[data-forge-update-branch]') as HTMLElement + fireEvent.click(row()) + fireEvent.click(screen.getByRole('menuitem', { name: /^Update with rebase/ })) + b.rerender(behind({ headSha: 'b'.repeat(40), branchUpdates: ['merge'] })) + const confirm = screen.getByRole('menuitem', { name: en['branch.changed'] }) + expect(confirm.hasAttribute('disabled')).toBe(true) + fireEvent.click(row()) + fireEvent.click(row()) + fireEvent.click(screen.getByRole('menuitem', { name: en['branch.confirm'] })) + expect(updateBranch).toHaveBeenCalledWith(expect.anything(), { method: 'merge', headSha: 'b'.repeat(40) }) + }) + + it('closes the menu with Escape without updating', () => { + const updateBranch = vi.fn>() + const b = card(behind(), { updateBranch }) + fireEvent.click(b.item.querySelector('[data-forge-update-branch]') as HTMLElement) + fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + expect(updateBranch).not.toHaveBeenCalled() + }) + + it.each([ + ['the head is up to date', snapshot(7), true], + ['the surface cannot update branches', behind(), false], + ])('offers no update when %s', (_label, value, withAction) => { + const b = card(value, withAction ? { updateBranch: vi.fn() } : {}) + expect(b.item.querySelector('[data-forge-update-branch]')).toBeNull() + expect(within(b.item).getByText(en['change.row.merge']).closest('button')).toBeNull() + }) +}) + +describe('linked issues', () => { + const issue = (number: number, owner: string, name: string, state: 'open' | 'closed' = 'open') => ({ + repository: { forge: 'github', host: 'github.com', owner, name }, number, title: `Issue ${number}`, state, + url: `https://github.com/${owner}/${name}/issues/${number}`, + }) + + it('links each issue by its number, naming its repository when it is another one, and notes more than were read', () => { + const b = card(snapshot(7, { closingIssues: [issue(6, 'Octo', 'Demo'), issue(2, 'octo', 'tracker', 'closed')], closingIssuesTruncated: true })) + const row = b.item.querySelector('[data-forge-closing-issues]') as HTMLElement + expect(row.textContent).toBe('Linked issues #6, octo/tracker#2 and more') + const links = within(row).getAllByRole('link') + expect(links.map(link => [link.getAttribute('aria-label'), link.getAttribute('data-state')])).toEqual([ + ['Open issue #6: Issue 6', 'open'], ['Open issue octo/tracker#2: Issue 2', 'closed'], + ]) + fireEvent.click(links[1]!) + expect(b.openLink).toHaveBeenCalledWith('https://github.com/octo/tracker/issues/2') + expect(links[0]?.className).toBe(overview.issue) + expect(row.querySelector(`.${css.visuallyHidden}`)).toBeNull() + }) + + it('shows no row without linked issues', () => { + expect(card(snapshot(7)).item.querySelector('[data-forge-closing-issues]')).toBeNull() + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 25f4443959..4342e36eb0 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -256,6 +256,9 @@ function mount(options: MountOptions = {}) { changeRequestText: vi.fn(async () => ok(APP_TEXT)), localCommits: vi.fn(async () => ok(COMMITS)), changeRequestCommits: vi.fn(async () => ok(COMMITS)), + // Without a host that keeps viewed marks, the browser keeps them, as for local changes. + changeRequestViewed: vi.fn(async () => ok(null)), + setFileViewed: vi.fn(async () => ok(undefined)), openLink: vi.fn(), copyPath: vi.fn(), reviewQueue: vi.fn().mockReturnValue(new ReviewQueue('test-review')), @@ -1791,6 +1794,142 @@ describe('ChangesTab review layers', () => { }) }) +describe('ChangesTab viewed marks the host keeps', () => { + const source = { kind: 'change', url: URL7 } as const + const marks = (m: ReturnType): (string | null)[][] => [...m.view.container.querySelectorAll('[data-forge-diff-file]')] + .map(element => [element.getAttribute('data-forge-diff-file'), element.getAttribute('data-viewed'), element.hasAttribute('data-expanded') ? 'open' : 'closed']) + const hosted = (files: Record, headSha = HEAD) => ok({ headSha, files, truncated: false }) + const box = (m: ReturnType, path: string, name: string): HTMLInputElement => + within(m.section(path)).getByRole('checkbox', { name: `Mark ${name} as viewed` }) + + it('reads the marks with the diff, saves each mark on the host at once, and keeps the browser\'s marks apart', async () => { + const saved = Promise.withResolvers>() + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({ 'src/app.ts': 'viewed', 'docs/notes.txt': 'dismissed' })) + faces.setFileViewed.mockReturnValueOnce(saved.promise) + } }) + await settle() + expect(m.faces.changeRequestViewed).toHaveBeenCalledWith(URL7, HEAD, expect.any(AbortSignal)) + expect(marks(m)).toEqual([['docs/gone.txt', 'unviewed', 'open'], ['docs/notes.txt', 'changed', 'open'], ['src/app.ts', 'viewed', 'closed']]) + expect(m.view.getByRole('progressbar').getAttribute('aria-valuetext')).toBe('1 / 3 viewed') + + const gone = box(m, 'docs/gone.txt', 'gone.txt') + expect(gone.closest('label')?.title).toBe(en['viewed.hintHost']) + fireEvent.click(gone) + expect(m.faces.setFileViewed).toHaveBeenCalledWith(URL7, { path: 'docs/gone.txt', viewed: true, headSha: HEAD }) + expect(marks(m)[0]).toEqual(['docs/gone.txt', 'viewed', 'closed']) + // While its write is in flight the mark stays put, also for V. + expect(gone.disabled).toBe(true) + expect(gone.closest('label')?.title).toBe(en['viewed.saving']) + fireEvent.keyDown(m.section('docs/gone.txt'), { key: 'v' }) + expect(m.faces.setFileViewed).toHaveBeenCalledOnce() + await act(async () => { saved.resolve(ok(undefined)); await Promise.resolve() }) + expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(false) + expect(marks(m)[0]).toEqual(['docs/gone.txt', 'viewed', 'closed']) + expect(m.viewedFiles.marksOf(JSON.stringify(['change', URL7, null])).size).toBe(0) + expect(m.faces.report).not.toHaveBeenCalled() + }) + + it.each([ + ['refused', { ok: false, error: new RemoteError('forgePanel/action-failed', 'Resource not accessible', {}) }, ['viewed.syncFailed', { message: 'Resource not accessible' }]], + ['stale', REFUSED.staleHead, ['viewed.syncStale']], + ] as const)('returns a %s mark to what the host keeps and says why', async (_label, result, report) => { + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({ 'src/app.ts': 'viewed' })) + faces.setFileViewed.mockResolvedValue(result) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + expect(marks(m)[2]).toEqual(['src/app.ts', 'unviewed', 'open']) + await settle() + expect(marks(m)[2]).toEqual(['src/app.ts', 'viewed', 'open']) + expect(m.faces.report).toHaveBeenCalledWith(...report) + // A later choice that fails returns to the earlier saved one. + m.faces.setFileViewed.mockResolvedValueOnce(ok(undefined)) + fireEvent.click(box(m, 'docs/notes.txt', 'notes.txt')) + await settle() + expect(marks(m)[1]?.[1]).toBe('viewed') + fireEvent.click(box(m, 'docs/notes.txt', 'notes.txt')) + expect(marks(m)[1]?.[1]).toBe('unviewed') + await settle() + expect(marks(m)[1]?.[1]).toBe('viewed') + }) + + it('locks every mark and offers to read again when the host\'s marks cannot be read', async () => { + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/viewed-failed', 'API rate limit exceeded', {}) }) + .mockResolvedValueOnce(hosted({}, 'b'.repeat(40))) + .mockResolvedValue(hosted({ 'src/app.ts': 'viewed' })) + } }) + await settle() + const notice = m.view.getByText('Could not read viewed files from GitHub, so files cannot be marked: API rate limit exceeded') + const app = box(m, 'src/app.ts', 'app.ts') + expect(app.disabled).toBe(true) + expect(app.closest('label')?.title).toBe(en['viewed.unavailable']) + fireEvent.click(app) + fireEvent.keyDown(m.section('src/app.ts'), { key: 'v' }) + expect(m.faces.setFileViewed).not.toHaveBeenCalled() + // Marks read at another head than the diff cannot apply either. + fireEvent.click(within(notice.closest('[role="status"]') as HTMLElement).getByRole('button', { name: en.retry })) + await settle() + const message = /^Could not read viewed files from GitHub, so files cannot be marked: viewed marks were read at b{40}/ + expect(m.view.getByText(message)).toBeDefined() + fireEvent.click(m.view.getByRole('button', { name: en.retry })) + await settle() + expect(m.view.queryByText(/^Could not read viewed files/)).toBeNull() + expect(marks(m)[2]).toEqual(['src/app.ts', 'viewed', 'closed']) + }) + + it('waits for a later status when the marks were read at a moved head, as for the diff', async () => { + const m = mount({ source, setup: (faces) => { faces.changeRequestViewed.mockResolvedValueOnce(REFUSED.staleHead) } }) + await settle() + expect(m.paths()).toEqual([]) + const polled = entry(7, snapshot(7, { headSha: HEAD })) + const moved = { ...polled, update: { ...polled.update!, fetchedAt: 2 } } + act(() => { m.panel.set({ state: ready({ changeRequests: [moved] }), disconnected: false }) }) + await settle() + expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts']) + }) + + it('keeps the marks of chosen commits in the browser without reading the host', async () => { + const m = mount({ source, setup: (faces) => { faces.changeRequestViewed.mockResolvedValue(hosted({ 'src/app.ts': 'viewed' })) } }) + await settle() + m.faces.changeRequestViewed.mockClear() + fireEvent.click(m.view.getByRole('button', { name: 'Commits shown: All commits' })) + await settle() + fireEvent.click(within(document.body).getByRole('menuitem', { name: /^3333333/ })) + await settle() + expect(m.faces.changeRequestViewed).not.toHaveBeenCalled() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + expect(m.faces.setFileViewed).not.toHaveBeenCalled() + expect(box(m, 'src/app.ts', 'app.ts').closest('label')?.title).toBe(en['viewed.hint']) + }) + + it('drops the choices of an earlier diff once the next one loads with the host\'s marks', async () => { + const saved = Promise.withResolvers>() + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({})) + faces.setFileViewed.mockReturnValueOnce(saved.promise) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + m.faces.changeRequestViewed.mockResolvedValue(hosted({ 'docs/notes.txt': 'viewed' })) + fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) + await settle() + expect(marks(m).map(row => row[1])).toEqual(['unviewed', 'viewed', 'unviewed']) + // A write of the next diff is in flight when the earlier one settles; only its own settlement unlocks its file. + const next = Promise.withResolvers>() + m.faces.setFileViewed.mockReturnValueOnce(next.promise) + fireEvent.click(box(m, 'docs/gone.txt', 'gone.txt')) + await act(async () => { saved.resolve({ ok: false, error: new RemoteError('forgePanel/action-failed', 'late', {}) }); await Promise.resolve() }) + expect(marks(m).map(row => row[1])).toEqual(['viewed', 'viewed', 'unviewed']) + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) + expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(true) + await act(async () => { next.resolve(ok(undefined)); await Promise.resolve() }) + expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(false) + }) +}) + describe('ChangesTab viewed files', () => { const marks = (m: ReturnType): (string | null)[][] => [...m.view.container.querySelectorAll('[data-forge-diff-file]')] .map(element => [element.getAttribute('data-forge-diff-file'), element.getAttribute('data-viewed'), element.hasAttribute('data-expanded') ? 'open' : 'closed']) diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index dad26b57b0..28c7ad748c 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -34,12 +34,19 @@ export function snapshot(number: number, overrides: Partial = {}) workflow: null, startedAt: '2026-10-09T10:00:00Z', completedAt: '2026-10-09T10:01:05Z', + rerun: null, ...overrides, } } diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 96257f8c29..fae3229789 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -1,7 +1,7 @@ import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ForgeFailure, ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge' +import type { ForgeFailure, ForgeProvider, ForgeReadiness } from '@deepseek-ai/dsh-experimental-forge' import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' import { appendPluginRecord, SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' @@ -1851,6 +1851,84 @@ describe('forgePanel actions', () => { expect(opened.provider.actions).toEqual(['ready 7', `merge 7 squash ${head}`, `merge 7 rebase ${head}`, 'ready 7', `merge 7 merge ${head}`]) }) + it('reads and saves viewed marks of a bound change request through its provider, separating a moved head', async () => { + const { repo } = await project() + const opened = await open(repo) + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => ready(state) && polled(state, pullUrl(7))) + const head = 'a'.repeat(40) + const request = { path: 'src/app.ts', viewed: true, headSha: head } + + await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)).resolves.toBeNull() + await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal)) + .rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider keeps no viewed marks' }) + const marks = { headSha: head, files: { 'src/app.ts': 'dismissed' as const }, truncated: false } + const viewedFiles = vi.fn>(async () => marks) + const setViewed = vi.fn>(async () => undefined) + Object.assign(opened.provider, { viewedFiles, setViewed }) + await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)).resolves.toEqual(marks) + await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal)).resolves.toBeUndefined() + expect(setViewed).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), request, expect.any(AbortSignal)) + + viewedFiles.mockResolvedValueOnce({ code: 'stale', message: 'moved' }).mockResolvedValueOnce({ code: 'unavailable', message: 'rate limited' }) + await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'moved' }) + await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, pullUrl(7), head, signal)) + .rejects.toMatchObject({ code: 'forgePanel/viewed-failed', message: 'rate limited' }) + setViewed.mockResolvedValueOnce({ code: 'stale', message: 'moved' }) + await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), request, signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head' }) + await expect(opened.ctx.forgePanel.setFileViewed(opened.session, pullUrl(7), { ...request, path: '' }, signal)).rejects.toThrow('Invalid viewed file') + for (const url of [pullUrl(8), 'https://unserved.test/a/b/pull/3']) { + await expect(opened.ctx.forgePanel.changeRequestViewed(opened.session, url, head, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.setFileViewed(opened.session, url, request, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + } + expect(setViewed).toHaveBeenCalledTimes(2) + }) + + it('reruns checks, requests reviews, lists reviewers, and updates the branch of a bound change request', async () => { + const { repo } = await project() + const opened = await open(repo) + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => ready(state) && polled(state, pullUrl(7))) + const head = 'a'.repeat(40) + const reviewers = [{ kind: 'user' as const, login: 'mona' }] + + await expect(opened.ctx.forgePanel.rerunChecks(opened.session, pullUrl(7), { headSha: head }, signal)) + .rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'This provider reruns no checks' }) + await expect(opened.ctx.forgePanel.reviewerCandidates(opened.session, pullUrl(7), '', signal)) + .rejects.toMatchObject({ code: 'forgePanel/reviewers-failed', message: 'This provider requests no reviews' }) + const candidates = [{ login: 'mona', name: 'Mona', avatarUrl: null, suggested: true }] + const rerunChecks = vi.fn>(async () => undefined) + const requestReviews = vi.fn>(async () => undefined) + const reviewerCandidates = vi.fn>(async () => candidates) + const updateBranch = vi.fn>(async () => ({ code: 'stale', message: 'moved' })) + Object.assign(opened.provider, { rerunChecks, requestReviews, reviewerCandidates, updateBranch }) + + await expect(opened.ctx.forgePanel.rerunChecks(opened.session, pullUrl(7), { headSha: head }, signal)).resolves.toBeUndefined() + await expect(opened.ctx.forgePanel.requestReviews(opened.session, pullUrl(7), reviewers, signal)).resolves.toBeUndefined() + await expect(opened.ctx.forgePanel.reviewerCandidates(opened.session, pullUrl(7), 'mo', signal)).resolves.toEqual(candidates) + await expect(opened.ctx.forgePanel.updateBranch(opened.session, pullUrl(7), 'rebase', head, signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head', message: 'moved' }) + updateBranch.mockResolvedValueOnce(undefined) + await expect(opened.ctx.forgePanel.updateBranch(opened.session, pullUrl(7), 'merge', head, signal)).resolves.toBeUndefined() + expect(requestReviews).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), { reviewers }, expect.any(AbortSignal)) + expect(updateBranch).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), { method: 'rebase', headSha: head }, expect.any(AbortSignal)) + for (const invalid of [[], [{ kind: 'user' as const, login: ' ' }]]) { + await expect(opened.ctx.forgePanel.requestReviews(opened.session, pullUrl(7), invalid, signal)).rejects.toThrow('Invalid reviewers') + } + requestReviews.mockResolvedValueOnce({ code: 'failed', message: 'Could not resolve user' }) + await expect(opened.ctx.forgePanel.requestReviews(opened.session, pullUrl(7), reviewers, signal)) + .rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'Could not resolve user' }) + for (const url of [pullUrl(8), 'https://unserved.test/a/b/pull/3']) { + await expect(opened.ctx.forgePanel.rerunChecks(opened.session, url, { headSha: head }, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.requestReviews(opened.session, url, reviewers, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.reviewerCandidates(opened.session, url, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.updateBranch(opened.session, url, 'merge', head, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + } + expect(rerunChecks).toHaveBeenCalledTimes(1) + }) + it('publishes a review only for a visible binding and validates wire ranges before calling the provider', async () => { const { repo } = await project() const opened = await open(repo) diff --git a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx index c09d128b5e..3af723cc90 100644 --- a/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/diff-review.client.spec.tsx @@ -27,7 +27,7 @@ function mount(overrides: Partial = {}) { } const props: DiffFileProps = { file, visible: true, expanded: true, large: false, revealed: false, text: undefined, open: new Set(), split: true, wrap: true, badge: '', tooltip: 'a.txt', - viewed: 'unviewed', handlers, review, t, ...overrides } + viewed: 'unviewed', viewedNote: '', viewedDisabled: false, handlers, review, t, ...overrides } const view = render() const line = (name: string) => view.getByRole('button', { name: `Select line ${name}` }) const code = (side: 'L' | 'R', no: number): HTMLElement => { diff --git a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx index c42e197b7d..433f644b1b 100644 --- a/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/forge-tab.client.spec.tsx @@ -55,6 +55,10 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v const markReady = vi.fn<(entry: ForgePanelChangeRequest) => Promise>(async () => {}) const merge = vi.fn<(entry: ForgePanelChangeRequest, request: MergeRequest) => Promise>(async () => {}) const readChecks = vi.fn(async () => snapshot(1)) + const rerunChecks = vi.fn(async () => {}) + const requestReviews = vi.fn(async () => {}) + const reviewerCandidates = vi.fn(async () => []) + const updateBranch = vi.fn(async () => {}) const restore = vi.fn<() => void>() const openLink = vi.fn<(url: string) => void>() const copyText = vi.fn<(text: string) => void>() @@ -68,8 +72,8 @@ function tab(state: ForgePanelState | null, options: { disconnected?: boolean; v usePanel: bindSnapshotSelector(panel), useHost: bindSnapshotSelector(host), useLocale: bindSnapshotSelector(createSnapshotStore('en')), - reconnect, refresh, remove, markReady, merge, readChecks, restore, openLink, copyText, copyPath, reportVisible, createChangeRequest, - t, + reconnect, refresh, remove, markReady, merge, readChecks, rerunChecks, requestReviews, reviewerCandidates, updateBranch, restore, + openLink, copyText, copyPath, reportVisible, createChangeRequest, t, } const view = render() return { diff --git a/packages/experimental/client-ui-forge/tests/harness.ts b/packages/experimental/client-ui-forge/tests/harness.ts index 5eeaaa6e98..9dd5691f15 100644 --- a/packages/experimental/client-ui-forge/tests/harness.ts +++ b/packages/experimental/client-ui-forge/tests/harness.ts @@ -257,12 +257,19 @@ export function snapshot(ref: ChangeRequestRef): ChangeRequestSnapshot { mergeability: 'mergeable', mergeReady: true, mergeMethods: ['squash', 'merge', 'rebase'], + branchUpdates: [], reviewDecision: 'none', + reviewers: [], + reviewersTruncated: false, + canRequestReviews: false, checks: [], checksRollup: 'success', checksTruncated: false, + canRerunChecks: false, unresolvedThreads: 0, threadsTruncated: false, + closingIssues: [], + closingIssuesTruncated: false, updatedAt: '2026-10-09T00:00:00Z', closedAt: null, } diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 39d1f6fe32..8d33c0abbc 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -12,8 +12,8 @@ import type { QuoteSummary } from '@deepseek-ai/dsh-client-ui-primitives' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SidebarRightTabDefinition, TabId } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { - ChangeRequestSnapshot, ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, - ForgeThreadId, + ChangeRequestReviewer, ChangeRequestSnapshot, ForgeCommitList, ForgeRerunRequest, ForgeReviewData, ForgeReviewerCandidate, + ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, type RemoteResult, type TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' @@ -161,6 +161,18 @@ async function base() { dismiss: vi.fn(async (_sessionId: SessionId, _url: string): Promise> => OK), markReady: vi.fn(async (_sessionId: SessionId, _url: string): Promise> => OK), merge: vi.fn(async (_sessionId: SessionId, _url: string, _method: string, _headSha: string): Promise> => OK), + rerunChecks: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeRerunRequest): Promise> => OK), + requestReviews: vi.fn(async ( + _sessionId: SessionId, _url: string, _reviewers: readonly Pick[], + ): Promise> => OK), + reviewerCandidates: vi.fn(async ( + _sessionId: SessionId, _url: string, _query: string, _signal: AbortSignal, + ): Read => ({ ok: true, value: [{ login: 'mona', name: null, avatarUrl: null, suggested: true }] })), + updateBranch: vi.fn(async (_sessionId: SessionId, _url: string, _method: string, _headSha: string): Promise> => OK), + changeRequestViewed: vi.fn(async ( + _sessionId: SessionId, _url: string, _headSha: string, _signal: AbortSignal, + ): Read => ({ ok: true, value: null })), + setFileViewed: vi.fn(async (_sessionId: SessionId, _url: string, _request: ForgeViewedRequest): Promise> => OK), refresh: vi.fn(async (_sessionId: SessionId): Promise> => OK), requestWorktree: vi.fn(async (_sessionId: SessionId, _from: string | null): Promise> => OK), cancelWorktree: vi.fn(async (_sessionId: SessionId): Promise> => OK), @@ -645,6 +657,71 @@ describe('mountForgePanel change request actions', () => { }) }) +describe('mountForgePanel overview actions', () => { + const url = 'https://github.com/octo/demo/pull/7' + + it.each([ + ['confirms it', OK, { key: 'toast.rerunRequested', tone: 'success', params: { name: '#7' } }], + ['says a moved head needs another look', REFUSED.stale, { key: 'toast.rerunStale', tone: 'failure', params: { name: '#7' } }], + ['reports why the host refused', REFUSED.refused, { key: 'toast.rerunFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ])('reruns failed checks through the Remote and %s', async (_label, result, notice) => { + const f = await fixture() + f.forgePanel.rerunChecks.mockResolvedValueOnce(result) + await f.tab(S1).rerunChecks(entry(7, snapshot(7)), { headSha: 'b'.repeat(40) }) + expect(f.forgePanel.rerunChecks).toHaveBeenCalledWith(S1, url, { headSha: 'b'.repeat(40) }) + expect(f.notice()).toMatchObject(notice) + await f.dispose() + }) + + it.each([ + ['confirms it', OK, { key: 'toast.reviewRequested', tone: 'success', params: { name: '#7', login: 'mona, lin' } }], + ['reports why the host refused', REFUSED.refused, { key: 'toast.reviewRequestFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ])('requests reviews through the Remote and %s', async (_label, result, notice) => { + const f = await fixture() + f.forgePanel.requestReviews.mockResolvedValueOnce(result) + const reviewers = [{ kind: 'user' as const, login: 'mona' }, { kind: 'user' as const, login: 'lin' }] + await f.tab(S1).requestReviews(entry(7, snapshot(7)), reviewers) + expect(f.forgePanel.requestReviews).toHaveBeenCalledWith(S1, url, reviewers) + expect(f.notice()).toMatchObject(notice) + await f.dispose() + }) + + it('lists reviewer candidates through the Remote and rejects with the host\'s reason', async () => { + const f = await fixture() + const signal = new AbortController().signal + await expect(f.tab(S1).reviewerCandidates(url, 'mo', signal)).resolves.toEqual([{ login: 'mona', name: null, avatarUrl: null, suggested: true }]) + expect(f.forgePanel.reviewerCandidates).toHaveBeenCalledWith(S1, url, 'mo', signal) + f.forgePanel.reviewerCandidates.mockResolvedValueOnce({ ok: false, error: new RemoteError('forgePanel/reviewers-failed', 'down', {}) }) + await expect(f.tab(S1).reviewerCandidates(url, '', signal)).rejects.toThrow('down') + await f.dispose() + }) + + it.each([ + ['confirms it', OK, { key: 'toast.branchUpdated', tone: 'success', params: { name: '#7' } }], + ['says a moved head needs another look', REFUSED.stale, { key: 'toast.branchUpdateStale', tone: 'failure', params: { name: '#7' } }], + ['reports why the host refused', REFUSED.refused, { key: 'toast.branchUpdateFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ])('updates the branch through the Remote with the confirmed head and %s', async (_label, result, notice) => { + const f = await fixture() + f.forgePanel.updateBranch.mockResolvedValueOnce(result) + await f.tab(S1).updateBranch(entry(7, snapshot(7)), { method: 'rebase', headSha: 'b'.repeat(40) }) + expect(f.forgePanel.updateBranch).toHaveBeenCalledWith(S1, url, 'rebase', 'b'.repeat(40)) + expect(f.notice()).toMatchObject(notice) + await f.dispose() + }) + + it('reads and saves the host\'s viewed marks through the Remote', async () => { + const f = await fixture() + const signal = new AbortController().signal + const view = f.changes(S1) + expect(await view.changeRequestViewed(url, 'a'.repeat(40), signal)).toEqual({ ok: true, value: null }) + expect(f.forgePanel.changeRequestViewed).toHaveBeenCalledWith(S1, url, 'a'.repeat(40), signal) + const request = { path: 'src/a.ts', viewed: true, headSha: 'a'.repeat(40) } + expect(await view.setFileViewed(url, request)).toEqual(OK) + expect(f.forgePanel.setFileViewed).toHaveBeenCalledWith(S1, url, request) + await f.dispose() + }) +}) + describe('mountForgePanel worktree actions', () => { it('requests and withdraws a worktree through the Remote', async () => { const f = await fixture() From b1fae5b32697aa6b6b61fc77863a71fed3fb05c7 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 17:13:17 +0800 Subject: [PATCH 11/15] docs(forge): document the overview and viewed marks The forge subsystem page gains the overview and viewed mark types and contracts, and the generated Cordis, configuration, and event catalogs follow the new service methods and the maxViewedFiles option. --- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/subsystems/forge.i18n.yaml | 9 +- docs/subsystems/forge.md | 325 +++++++++++++++++ docs/subsystems/forge.zh.md | 327 ++++++++++++++++++ .../extensions/tool-cordis/src/api-catalog.ts | 132 ++++++- scripts/gen-cordis-catalog.ts | 8 + scripts/type-equiv.manifest.json | 60 ++++ 10 files changed, 864 insertions(+), 9 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 8ff3224180..5a01c4fa38 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1193,7 +1193,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:432`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:582`](../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 704d37d959..bbbbedee66 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1195,7 +1195,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:432`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:582`](../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 cdc25843df..1d80e1cfe7 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 73677d93b1..9245fa8fab 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 408ac912e6..220edb82ab 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -16,10 +16,13 @@ zh: 9903fcc571104ad8 /forges/review-threads: en: af729af6e59e915f - zh: 62ddae4cfcd4431f + zh: 1b7d7671ec36a5b2 +/forges/overview-and-viewed-marks: + en: 244f4f65d26d98bd + zh: 51caba342a9d6773 /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: 4020149c26661a2d - zh: 56842b057d4f662e + en: 5ac76d3f4b0b0d05 + zh: d23454eff0a6635e diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 3fc9cde00c..cbcb0054da 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -101,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`, while the head is still `request.headSha`, + * resolving to undefined once the host accepted the 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 } ``` @@ -173,6 +205,8 @@ 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. */ + readonly rerun: ForgeCheckId | null } ``` @@ -230,18 +264,35 @@ 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. + */ + 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. */ @@ -517,6 +568,135 @@ type ForgeReviewWriteResult = | { 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, 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 +} +``` + ## Session bindings `ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules. @@ -808,6 +988,8 @@ 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 `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 @@ -1086,6 +1268,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. @@ -1134,6 +1359,29 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P */ 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. @@ -1404,6 +1652,32 @@ 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. + */ +@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 @@ -1475,6 +1749,57 @@ 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. + */ +@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. + */ +@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. + */ +@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 d127005c08..056f115efb 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -101,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`, while the head is still `request.headSha`, + * resolving to undefined once the host accepted the 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 } ``` @@ -173,6 +205,8 @@ 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. */ + readonly rerun: ForgeCheckId | null } ``` @@ -230,18 +264,35 @@ 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. + */ + 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. */ @@ -517,6 +568,137 @@ type ForgeReviewWriteResult = | { 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`,提供方答复后立即轮询被监听的变更请求;重跑与更新指明用户看到的 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 +} +``` + ## Session 绑定 `ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。 @@ -808,6 +990,8 @@ 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` 作用于已绑定的变更请求,`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 @@ -1086,6 +1270,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. @@ -1134,6 +1361,29 @@ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): P */ 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. @@ -1404,6 +1654,32 @@ 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. + */ +@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 @@ -1475,6 +1751,57 @@ 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. + */ +@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. + */ +@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. + */ +@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/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 2f9a9456fd..e332931521 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1262,6 +1262,34 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'undefined once the host merged it, or why it did not.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], }, + { + signature: 'async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'the head commit whose checks the user saw.' }, { name: 'signal', description: '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.'], + }, + { + signature: 'async requestReviews( ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise', + description: 'Request reviews of a change request from more reviewers, then poll it at once when it is watched.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'the reviewers to ask.' }, { name: 'signal', description: '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.'], + }, + { + signature: 'async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSignal, ): Promise', + description: 'List accounts a review of a change request can be requested from.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'query', description: 'text the login or name contains; empty for the host\'s suggestions and first accounts.' }, { name: 'signal', description: '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.'], + }, + { + signature: 'async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'update method and the head commit the user confirmed.' }, { name: 'signal', description: '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.'], + }, { signature: 'async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise', description: 'Read complete check details independently of periodic polling.', @@ -1290,6 +1318,20 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ 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.'], }, + { + signature: 'async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise', + description: '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 ForgeService.diff does.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'headSha', description: 'head commit the marks must be read at, usually the head of the displayed diff.' }, { name: 'signal', description: '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.'], + }, + { + signature: 'async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise', + description: '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 ForgeService.diff does.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'request', description: 'the file, its mark, and the head commit the user saw.' }, { name: 'signal', description: '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.'], + }, { signature: 'async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise', description: 'List the commits of a change request at its current head.', @@ -1447,6 +1489,19 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the text.', throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/diff-too-large` when the host or its provider refuses the file over a size limit; `forgePanel/diff-failed` when the host does not provide the file otherwise.'], }, + { + signature: '@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'headSha', description: 'head commit of the shown diff; marks read at another head are refused.' }, { name: 'signal', description: '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.'], + }, + { + signature: '@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise', + description: 'Set or clear the signed-in user\'s viewed mark on one file of a change request of a Session.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'request', description: 'the file, its mark, and the head commit of the shown diff.' }, { name: 'signal', description: '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.'], + }, { signature: '@Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise', description: 'Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read at the same head commit and update time are reused from memory, for any Session, until they are `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull request\'s update time.', @@ -1479,6 +1534,31 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'method', description: 'how the commits enter the base branch.' }, { name: 'headSha', description: 'head commit the user confirmed.' }, { name: 'signal', description: '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 otherwise or cannot be reached.'], }, + { + signature: '@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'request', description: 'the head commit whose checks the user saw.' }, { name: 'signal', description: '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.'], + }, + { + signature: '@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise', + description: 'Request reviews of a change request of a Session from more reviewers; the change request is polled again once the host answers.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'reviewers', description: 'the reviewers to ask, by kind and login.' }, { name: 'signal', description: '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.'], + }, + { + signature: '@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise', + description: 'List accounts a review of a change request of a Session can be requested from.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'query', description: 'text the login or name contains; empty for the host\'s suggestions and first accounts.' }, { name: 'signal', description: '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.'], + }, + { + signature: '@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise', + description: '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.', + parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'method', description: 'merge commit or rebase.' }, { name: 'headSha', description: 'head commit the user confirmed.' }, { name: 'signal', description: '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.'], + }, { signature: '@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise', description: '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 the inbox, or else at the first step proposal, the panel creates a branch from `from`, or from HEAD of the current checkout when it is null, and enters its checkout. A message that already waits after a failed or stopped attempt keeps waiting for ForgePanelController.retryWorktree.', @@ -6010,6 +6090,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'BoxProps', declaration: 'export interface BoxProps {\n readonly flexDirection?: \'row\' | \'column\' | undefined;\n readonly paddingX?: number | undefined;\n readonly paddingY?: number | undefined;\n readonly padding?: number | undefined;\n readonly gap?: number | undefined;\n readonly border?: boolean | string | undefined;\n readonly borderColor?: string | undefined;\n readonly children?: UiNode | undefined;\n}', }, + { + name: 'BranchUpdateMethod', + declaration: 'export type BranchUpdateMethod = \'merge\' | \'rebase\';', + }, + { + name: 'BranchUpdateRequest', + declaration: 'export interface BranchUpdateRequest {\n readonly method: BranchUpdateMethod;\n readonly headSha: string;\n}', + }, { name: 'Branded', declaration: 'export type Branded = string & {\n readonly [BRAND]: B;\n};', @@ -6040,7 +6128,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ChangeRequestCheck', - declaration: 'export interface ChangeRequestCheck {\n readonly name: string;\n readonly state: CheckState;\n readonly url: string | null;\n readonly workflow: string | null;\n readonly startedAt: string | null;\n readonly completedAt: string | null;\n}', + declaration: 'export interface ChangeRequestCheck {\n readonly name: string;\n readonly state: CheckState;\n readonly url: string | null;\n readonly workflow: string | null;\n readonly startedAt: string | null;\n readonly completedAt: string | null;\n readonly rerun: ForgeCheckId | null;\n}', + }, + { + name: 'ChangeRequestIssue', + declaration: 'export interface ChangeRequestIssue {\n readonly repository: ForgeRepository;\n readonly number: number;\n readonly title: string;\n readonly state: \'open\' | \'closed\';\n readonly url: string;\n}', }, { name: 'ChangeRequestKey', @@ -6054,9 +6146,13 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ChangeRequestRef', declaration: 'export interface ChangeRequestRef {\n readonly repository: ForgeRepository;\n readonly number: number;\n}', }, + { + name: 'ChangeRequestReviewer', + declaration: 'export interface ChangeRequestReviewer {\n readonly kind: \'user\' | \'bot\' | \'team\';\n readonly login: string;\n readonly avatarUrl: string | null;\n readonly requested: boolean;\n readonly codeOwner: boolean;\n readonly verdict: ReviewVerdict | null;\n readonly reviewedSha: string | null;\n}', + }, { name: 'ChangeRequestSnapshot', - declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly baseSha?: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly unresolvedThreads: number;\n readonly threadsTruncated: boolean;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', + declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly baseSha?: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly branchUpdates: readonly BranchUpdateMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly reviewers: readonly ChangeRequestReviewer[];\n readonly reviewersTruncated: boolean;\n readonly canRequestReviews: boolean;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly canRerunChecks: boolean;\n readonly unresolvedThreads: number;\n readonly threadsTruncated: boolean;\n readonly closingIssues: readonly ChangeRequestIssue[];\n readonly closingIssuesTruncated: boolean;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', }, { name: 'ChangeRequestState', @@ -6686,6 +6782,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeChangeRequestStatesFrame', declaration: 'export type ForgeChangeRequestStatesFrame = {\n readonly type: \'baseline\';\n readonly states: readonly ForgeChangeRequestListState[];\n} | {\n readonly type: \'changed\';\n readonly states: readonly ForgeChangeRequestListState[];\n};', }, + { + name: 'ForgeCheckId', + declaration: 'export type ForgeCheckId = Branded<\'ForgeCheckId\'>;', + }, { name: 'ForgeCheckout', declaration: 'export interface ForgeCheckout {\n readonly root: string;\n readonly branch: string | null;\n readonly linked: boolean;\n readonly commit: string | null;\n}', @@ -6786,6 +6886,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeRepository', declaration: 'export interface ForgeRepository {\n readonly forge: string;\n readonly host: string;\n readonly owner: string;\n readonly name: string;\n}', }, + { + name: 'ForgeRerunRequest', + declaration: 'export interface ForgeRerunRequest {\n readonly headSha: string;\n}', + }, { name: 'ForgeReviewComment', declaration: 'export interface ForgeReviewComment {\n readonly id: ForgeCommentId;\n readonly author: ForgeCommentAuthor | null;\n readonly body: string;\n readonly createdAt: string;\n readonly pending: boolean;\n readonly url: string | null;\n readonly viewerCanEdit: boolean;\n readonly viewerCanDelete: boolean;\n}', @@ -6794,6 +6898,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeReviewData', declaration: 'export interface ForgeReviewData {\n readonly headSha: string;\n readonly viewer: string | null;\n readonly threads: readonly ForgeReviewThread[];\n readonly truncated: boolean;\n readonly pendingReview: ForgePendingReview | null;\n readonly viewerCanReview: boolean;\n}', }, + { + name: 'ForgeReviewerCandidate', + declaration: 'export interface ForgeReviewerCandidate {\n readonly login: string;\n readonly name: string | null;\n readonly avatarUrl: string | null;\n readonly suggested: boolean;\n}', + }, + { + name: 'ForgeReviewersRequest', + declaration: 'export interface ForgeReviewersRequest {\n readonly reviewers: readonly Pick[];\n}', + }, { name: 'ForgeReviewEvent', declaration: 'export type ForgeReviewEvent = \'comment\' | \'approve\' | \'request-changes\';', @@ -6830,6 +6942,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ForgeThreadId', declaration: 'export type ForgeThreadId = Branded<\'ForgeThreadId\'>;', }, + { + name: 'ForgeViewedFiles', + declaration: 'export interface ForgeViewedFiles {\n readonly headSha: string;\n readonly files: Readonly>;\n readonly truncated: boolean;\n}', + }, + { + name: 'ForgeViewedRequest', + declaration: 'export interface ForgeViewedRequest {\n readonly path: string;\n readonly viewed: boolean;\n readonly headSha: string;\n}', + }, + { + name: 'ForgeViewedState', + declaration: 'export type ForgeViewedState = \'viewed\' | \'unviewed\' | \'dismissed\';', + }, { name: 'ForgeWorktreeBlocker', declaration: 'export type ForgeWorktreeBlocker = \'not-git\' | \'outside-writable-root\' | \'read-only\';', @@ -8418,6 +8542,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ReviewDecision', declaration: 'export type ReviewDecision = \'approved\' | \'changes-requested\' | \'review-required\' | \'none\';', }, + { + name: 'ReviewVerdict', + declaration: 'export type ReviewVerdict = \'approved\' | \'changes-requested\' | \'commented\' | \'dismissed\';', + }, { name: 'RpcId', declaration: 'export type RpcId = Branded<\'rpc-id\'>;', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 2b89c12b5f..88fc939459 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -431,6 +431,14 @@ export const LINK_MAP: Readonly> = { ForgeReviewData: 'forge.md', ForgeReviewWrite: 'forge.md', ForgeReviewWriteResult: 'forge.md', + BranchUpdateMethod: 'forge.md', + BranchUpdateRequest: 'forge.md', + ChangeRequestReviewer: 'forge.md', + ForgeRerunRequest: 'forge.md', + ForgeReviewerCandidate: 'forge.md', + ForgeReviewersRequest: 'forge.md', + ForgeViewedFiles: 'forge.md', + ForgeViewedRequest: 'forge.md', ForgeCommitRange: 'forge.md', ForgeFileLayer: 'forge.md', ForgeChangeRequestStatesFrame: 'forge.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 96a24baa23..05d5355dcc 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2886,6 +2886,66 @@ "doc": "docs/subsystems/session.md", "symbol": "SessionEventInput", "source": "packages/core/session/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeCheckId", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "BranchUpdateMethod", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ReviewVerdict", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ChangeRequestReviewer", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ChangeRequestIssue", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeRerunRequest", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewersRequest", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeReviewerCandidate", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "BranchUpdateRequest", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeViewedState", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeViewedFiles", + "source": "packages/experimental/forge/src/types.ts" + }, + { + "doc": "docs/subsystems/forge.md", + "symbol": "ForgeViewedRequest", + "source": "packages/experimental/forge/src/types.ts" } ] } From 6a2d06c16c629efe40a463a414c5e1e07fba144b Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 20:56:15 +0800 Subject: [PATCH 12/15] feat(forge-panel): show the viewed progress as a ring The changes toolbar shows how many shown files are viewed with a ring filled to the viewed share and the label beside it, instead of a label and a bar, which saves the bar's width. A narrow toolbar keeps the ring and shortens the label to the bare count, as before. --- .../src/client/ChangesTab.module.css | 2 +- .../src/client/ReviewControls.module.css | 24 ++--------------- .../src/client/ReviewControls.tsx | 27 +++++++------------ .../src/client/toolbar-fold.ts | 2 +- .../tests/review-controls.client.spec.tsx | 10 +++---- 5 files changed, 19 insertions(+), 46 deletions(-) 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 7f621cd815..6b71b2428c 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -277,7 +277,7 @@ /* `observeToolbarFold` sets `data-fold` on the toolbar row to the shallowest level whose items fit on one line: level 1 folds the line totals, expansion, side by side, and wrapping into the More menu; level 2 the test switch, with the - progress shown as a ring; level 3 refresh. */ + progress label shortened to the bare count beside its ring; level 3 refresh. */ .more { display: none; } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css b/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css index 741382f46f..44143a67b7 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewControls.module.css @@ -122,41 +122,21 @@ display: inline-flex; flex: none; align-items: center; - gap: 8px; + gap: 6px; padding: 0 4px; color: var(--dsw-alias-label-secondary); white-space: nowrap; font-variant-numeric: tabular-nums; } -.bar { - position: relative; - width: 64px; - height: 4px; - overflow: hidden; - border-radius: 999px; - corner-shape: round; - background: var(--dsw-alias-border-l3); -} - -.fill { - position: absolute; - inset: 0 auto 0 0; - border-radius: inherit; - corner-shape: round; - background: var(--dsw-alias-state-success-primary); -} - .progressForm { display: inline-flex; align-items: center; - gap: 8px; } -/* A narrow toolbar shows this form in place of the label and bar. */ +/* A narrow toolbar shows this form in place of the label. */ .progressForm[data-forge-progress='compact'] { display: none; - gap: 6px; } /* The ring starts at twelve o’clock and fills clockwise with the viewed share. */ diff --git a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx index 27837f52e6..5168e42fda 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx @@ -159,12 +159,12 @@ export function HideTestsSwitch({ hidden, toggle, t }: PropsLocale & ) } -/** Radius of the compact progress ring, inside its 14px box with a 2px stroke. */ +/** Radius of the progress ring, inside its 14px box with a 2px stroke. */ const RING_RADIUS = 5.5 /** - * Render how many of the shown files the reader marked viewed: a label with a bar, and a ring with the bare count that a - * narrow toolbar shows instead (`data-forge-progress` names each form for the toolbar's styles). + * Render how many of the shown files the reader marked viewed: a ring filled to the viewed share, then a label, or the + * bare count that a narrow toolbar shows instead (`data-forge-progress` names each form for the toolbar's styles). * @param props - the viewed and shown file counts, and copy. * @returns the progress, or nothing without shown files. */ @@ -179,20 +179,13 @@ export function ViewedProgress({ viewed, total, t }: PropsLocale & { return ( - - {label} - - - - {t('viewed.count', counts)} - + + {label} + {t('viewed.count', counts)} ) } diff --git a/packages/experimental/client-ui-forge/src/client/toolbar-fold.ts b/packages/experimental/client-ui-forge/src/client/toolbar-fold.ts index ec0e9c30d5..288a721aad 100644 --- a/packages/experimental/client-ui-forge/src/client/toolbar-fold.ts +++ b/packages/experimental/client-ui-forge/src/client/toolbar-fold.ts @@ -1,7 +1,7 @@ /** Width-driven folding of the changes toolbar into its More menu. */ /** Fold levels, from none to the deepest: level 1 folds the line totals, expansion, side by side, and wrapping; level 2 - * the test switch, with the progress shown as a ring; level 3 refresh. */ + * the test switch, with the progress label shortened to the bare count beside its ring; level 3 refresh. */ export const DEEPEST_FOLD = 3 /** diff --git a/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx index c2d22c77d3..61d9eb82da 100644 --- a/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx @@ -114,12 +114,12 @@ describe('HideTestsSwitch and ViewedProgress', () => { const view = render() const bar = view.getByRole('progressbar', { name: en['viewed.progressAria'] }) expect([bar.getAttribute('aria-valuenow'), bar.getAttribute('aria-valuemax'), bar.getAttribute('aria-valuetext')]).toEqual(['2', '4', '2 / 4 viewed']) - expect(bar.querySelector('[style]')?.style.width).toBe('50%') - // The compact form a narrow toolbar shows: a ring filled to the same share, and the bare count. - const compact = bar.querySelector('[data-forge-progress="compact"]')! - expect(compact.textContent).toBe('2/4') - const [length, gap] = compact.querySelectorAll('circle')[1]!.getAttribute('stroke-dasharray')!.split(' ').map(Number) + // One ring filled to the viewed share, then the label, or the bare count a narrow toolbar shows instead. + const [length, gap] = bar.querySelectorAll('circle')[1]!.getAttribute('stroke-dasharray')!.split(' ').map(Number) expect(length! / gap!).toBeCloseTo(0.5) + expect(bar.querySelectorAll('svg')).toHaveLength(1) + expect([...bar.querySelectorAll('[data-forge-progress]')].map(form => [form.getAttribute('data-forge-progress'), form.textContent])) + .toEqual([['full', '2 / 4 viewed'], ['compact', '2/4']]) view.rerender() expect(view.queryByRole('progressbar')).toBeNull() }) From ef22fbe7d3777c83605b988945362e9f8240ee56 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 20:56:46 +0800 Subject: [PATCH 13/15] fix(forge): report unconfirmed writes and harden the overview actions - ForgeActionFailure gains `unknown` for an answer that does not confirm the outcome; the GitHub provider passes it on instead of `failed`, the panel Remote refuses with `forgePanel/action-unknown`, a viewed mark stays, and the other actions ask the reader to check the browser. - Reruns skip workflow runs with a pending check, try every finished run, and report the refused ones together; the card offers a rerun only when a failed check's run has finished. - Review requests resolve users and teams to node ids and call `requestReviews`, which GitHub Enterprise Server 3.19 and 3.20 have; bots still go through `requestReviewsByLogin`. - Viewed marks are kept per change request and head, so a reread at the same head keeps writes in flight and their locks, and paths named after object properties read only their own entries. - The reviewer search never chooses from the listing of an earlier query. - Documentation states the unknown code, the branch update evidence, and the `canBeRebased` approximation, and drops stray blank lines. --- apps/web/tests/forge-panel.e2e.ts | 16 ++- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/subsystems/forge.i18n.yaml | 8 +- docs/subsystems/forge.md | 38 +++-- docs/subsystems/forge.zh.md | 38 +++-- .../guide.i18n.yaml | 22 +-- .../forge-change-request-overview/guide.md | 9 +- .../forge-change-request-overview/guide.zh.md | 9 +- .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 8 +- .../experimental/client-ui-forge/README.zh.md | 8 +- .../src/client/ChangeRequestCard.tsx | 3 - .../src/client/ChangeRequestOverview.tsx | 32 +++-- .../client-ui-forge/src/client/ChangesTab.tsx | 1 + .../src/client/ForgeTab.module.css | 1 - .../client-ui-forge/src/client/host-viewed.ts | 134 ++++++++++++------ .../client-ui-forge/src/client/locales.ts | 22 ++- .../client-ui-forge/src/client/mount.ts | 9 ++ .../experimental/client-ui-forge/src/index.ts | 16 ++- .../experimental/client-ui-forge/src/types.ts | 2 + .../change-request-overview.client.spec.tsx | 30 +++- .../tests/changes-tab.client.spec.tsx | 91 +++++++++++- .../tests/controller.host.spec.ts | 4 + .../tests/host-viewed.client.spec.ts | 21 +++ .../tests/mount.client.spec.ts | 6 + .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 4 +- .../experimental/forge-github/README.zh.md | 4 +- .../experimental/forge-github/src/graphql.ts | 4 + .../experimental/forge-github/src/mutation.ts | 4 +- .../experimental/forge-github/src/overview.ts | 99 +++++++++++-- .../experimental/forge-github/src/provider.ts | 37 +++-- .../experimental/forge-github/src/viewed.ts | 12 +- .../forge-github/tests/graphql.spec.ts | 4 +- .../forge-github/tests/overview.spec.ts | 69 +++++++-- .../forge-github/tests/provider.spec.ts | 41 ++++-- .../forge-github/tests/viewed.spec.ts | 7 + packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 6 +- packages/experimental/forge/README.zh.md | 6 +- packages/experimental/forge/src/types.ts | 22 +-- .../extensions/tool-cordis/src/api-catalog.ts | 10 +- 43 files changed, 656 insertions(+), 221 deletions(-) create mode 100644 packages/experimental/client-ui-forge/tests/host-viewed.client.spec.ts diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 9e979109ca..389d5a5d8c 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -170,8 +170,9 @@ if (args[0] === 'api' && args[1] === 'graphql' && args.includes('--input')) { } state.viewed = { ...state.viewed, [variables.path]: field === 'unmarkFileAsViewed' ? 'UNVIEWED' : 'VIEWED' } payload = { clientMutationId: null } - } else if (field === 'requestReviewsByLogin') { - state.requested = [...new Set([...state.requested ?? [], ...variables.input.userLogins ?? []])] + } 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)) { @@ -281,6 +282,11 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } } })) 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) @@ -2398,10 +2404,10 @@ it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state 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 === 'requestReviewsByLogin').map(entry => entry.variables.input)) + await expect.poll(async () => (await mutationsOf(root)).filter(entry => entry.field === 'requestReviews').map(entry => entry.variables.input)) .toEqual([ - { pullRequestId: 'pull-7', union: true, userLogins: ['mona'] }, - { pullRequestId: 'pull-7', union: true, userLogins: ['zhou-dev'] }, + { 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. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 5a01c4fa38..41bd0207f3 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1193,7 +1193,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:582`](../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. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index bbbbedee66..a3bb192363 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1195,7 +1195,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:582`](../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. */ diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 220edb82ab..9702f4429c 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -18,11 +18,11 @@ en: af729af6e59e915f zh: 1b7d7671ec36a5b2 /forges/overview-and-viewed-marks: - en: 244f4f65d26d98bd - zh: 51caba342a9d6773 + en: fd5928603c9375b1 + zh: 1a3bca55344ff385 /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: 5ac76d3f4b0b0d05 - zh: d23454eff0a6635e + en: 0e0348e9a38215ed + zh: affcc0231e15d682 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index cbcb0054da..a84fb124a9 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -114,9 +114,9 @@ interface ForgeProvider { */ setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise /** - * Rerun the failed checks of the head commit that name a `rerun`, while the head is still `request.headSha`, - * resolving to undefined once the host accepted the rerun. Omission declares that the provider reruns no checks, and - * its snapshots then name none. + * 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 /** @@ -205,7 +205,10 @@ 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. */ + /** + * 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 } ``` @@ -266,7 +269,8 @@ interface ChangeRequestSnapshot { 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. + * 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. */ @@ -354,13 +358,15 @@ 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 } @@ -570,7 +576,7 @@ type ForgeReviewWriteResult = ## 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, 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. +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. */ @@ -988,7 +994,7 @@ 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 `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. +`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. @@ -1674,7 +1680,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 @@ -1758,7 +1765,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 @@ -1770,7 +1778,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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-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 @@ -1796,7 +1805,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 056f115efb..6ef0264108 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -114,9 +114,9 @@ interface ForgeProvider { */ setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise /** - * Rerun the failed checks of the head commit that name a `rerun`, while the head is still `request.headSha`, - * resolving to undefined once the host accepted the rerun. Omission declares that the provider reruns no checks, and - * its snapshots then name none. + * 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 /** @@ -205,7 +205,10 @@ 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. */ + /** + * 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 } ``` @@ -266,7 +269,8 @@ interface ChangeRequestSnapshot { 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. + * 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. */ @@ -354,13 +358,15 @@ 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 } @@ -572,7 +578,7 @@ type ForgeReviewWriteResult = ## 概览与已审阅标记 -快照还携带变更请求的概览:`reviewers` 及每位评审者最近的结论、合并后托管平台会关闭的 `closingIssues`、能让落后于基线的 head 更新到最新的 `branchUpdates`、当前登录用户能否请求评审或重跑检查,以及每个检查指出的 `rerun`。`ctx.forge.rerunChecks`、`ctx.forge.requestReviews` 与 `ctx.forge.updateBranch` 据此操作,并像上文的操作一样返回 `ForgeActionFailure`,提供方答复后立即轮询被监听的变更请求;重跑与更新指明用户看到的 head 提交,head 移动后以 `stale` 拒绝。提供方同时实现 `requestReviews` 与 `reviewerCandidates`,`ctx.forge.reviewerCandidates` 借后者列出可以请求评审的账号;提供方缺少的操作以 `failed` 失败,`reviewerCandidates` 则返回 `unsupported`。GitHub 如何填写各字段并执行这些操作见 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package)。 +快照还携带变更请求的概览:`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. */ @@ -990,7 +996,7 @@ 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` 作用于已绑定的变更请求,`reviewerCandidates` 列出可请求评审的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随 diff 一起读取整个变更请求的标记,本地变更与所选提交的标记保存在浏览器中;两者以及提供这些操作的卡片行见[面板 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` 同样如此。变更视图一次只发送一个写操作,每个可能改变讨论的写操作之后都会重新读取讨论。 @@ -1676,7 +1682,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 @@ -1760,7 +1767,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 @@ -1772,7 +1780,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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-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 @@ -1798,7 +1807,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @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. + * 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 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 index 6ecd0cfd15..932fdd9720 100644 --- 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 @@ -3,14 +3,14 @@ # 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: 6c0fc046709d9325 - zh: 532328a943b4b9bc -/forge-snapshots-carry-the-change-request-overview: - en: c68b2863aee295e2 - zh: 00caaff4e530872a -/forge-snapshots-carry-the-change-request-overview/change: - en: fd8113f3d0ad2af6 - zh: 9f01008ed1b1a349 -/forge-snapshots-carry-the-change-request-overview/migration: - en: 3fbd619c7646c8df - zh: ebf8ec7f5b3aeb47 + 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 index feca3a50ac..3725460565 100644 --- 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 @@ -1,9 +1,9 @@ --- kind: upgrade-guide -description: "ChangeRequestSnapshot gains required overview fields and ChangeRequestCheck gains the required rerun field." +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 +# Forge snapshots carry the change request overview, and actions report unknown outcomes English | [中文](guide.zh.md) @@ -11,6 +11,8 @@ English | [中文](guide.zh.md) `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`. @@ -20,4 +22,5 @@ This affects third-party `ForgeProvider` implementations registered with `ctx.fo 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. Run your type check; it succeeds when every snapshot and check a provider builds sets the new fields. +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 index 891f735878..6c7ac4933f 100644 --- 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 @@ -1,9 +1,9 @@ --- kind: upgrade-guide -description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestCheck 新增必填的 rerun 字段。" +description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestCheck 新增必填的 rerun 字段,ForgeActionFailure 新增 unknown 代码。" --- -# Forge 快照携带变更请求概览 +# Forge 快照携带变更请求概览,操作报告结果不明 [English](guide.md) | 中文 @@ -11,6 +11,8 @@ description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestC `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`。 @@ -20,4 +22,5 @@ description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestC 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. 运行类型检查;提供方构造的每个快照与检查都设置了新字段时即通过。 +4. 在所有对 `ForgeActionFailure['code']` 做穷举的地方处理 `unknown`:提示需要到主机上核对结果,核对之前不要再次尝试该改动。 +5. 运行类型检查;提供方构造的每个快照与检查都设置了新字段、且没有未处理的 `ForgeActionFailure` 代码时即通过。 diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index fa845a5053..7beff73f1b 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: 58473cf35a05bff7 - zh: ec94e167234a84b3 + en: c3fa707a638717e4 + zh: dfeba8a57c58a8aa /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: dfb2d6533c6ead77 - zh: 26f39a0792d10da3 + en: 34e9adf3a843f969 + zh: 7a04974cf01fa2e7 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index bc28a9842e..0cff619fbf 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,11 +36,11 @@ 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, 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; 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, and Update branch report their outcome in a toast, 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. +- **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. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress shown as a ring and a count, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base 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. 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. 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 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. @@ -72,7 +72,7 @@ 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`, and another refusal with `forgePanel/action-failed` and the host's reason. `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 until the host saves or refuses it; a write that settles after another diff loaded changes nothing in that diff. +`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. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 2d58986c09..b5a53effd0 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,11 +36,11 @@ kind: "package-reference" - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查且有失败检查可重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求与“更新分支”的结果都以 toast 报告;显示的 head 之后有新提交时不会重跑或更新。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 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` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 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 提交不一致的响应。 @@ -72,7 +72,7 @@ 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` 并附托管平台的原因。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 保存读者设置的每个标记,直到托管平台保存或拒绝;另一个 diff 加载后才结束的写入不会改动该 diff。 +`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 存储服务时,流以失败结束。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 227e18448e..4e455c1037 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -90,7 +90,6 @@ const ROLLUP: Record = { failure: 'failure', } - /** 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,8 +100,6 @@ function failureOf(entry: ForgePanelChangeRequest): ForgeFailure | undefined { return entry.update !== null && 'failure' in entry.update ? entry.update.failure : undefined } - - function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapshot; readonly locale: string }): ReactNode { return ( diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx index 0f84d7868d..dd44612e4f 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -148,6 +148,17 @@ export interface ChecksRowProps { 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 @@ -181,8 +192,7 @@ export function ChecksRow({ entry, snapshot, openLink, readChecks, rerunChecks, return
} value={t('change.ci.none')} opens={false} />
} const counts = checkCounts(displayed.checks) - const rerun = displayed.state === 'open' && displayed.canRerunChecks - && displayed.checks.some(check => check.state === 'failure' && check.rerun !== null) ? rerunChecks : undefined + 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) @@ -393,8 +403,9 @@ function ReviewerLine({ reviewer, headSha, t }: { ) } -/** The accounts a reviewer search listed, or that the listing failed. */ -type Listing = { readonly ok: true; readonly value: readonly ForgeReviewerCandidate[] } | { readonly ok: false } +/** 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 }: { @@ -411,8 +422,8 @@ function ReviewerSearch({ url, list, choose, t }: { const controller = new AbortController() const timer = setTimeout(() => { list(url, query, controller.signal).then( - (value) => { if (!controller.signal.aborted) setListing({ ok: true, value }) }, - () => { if (!controller.signal.aborted) setListing({ ok: false }) }, + (value) => { if (!controller.signal.aborted) setListing({ query, ok: true, value }) }, + () => { if (!controller.signal.aborted) setListing({ query, ok: false }) }, ) }, query === '' ? 0 : SEARCH_DELAY_MS) return () => { @@ -425,11 +436,14 @@ function ReviewerSearch({ url, list, choose, t }: { const frame = requestAnimationFrame(() => { search.current?.focus() }) return () => { cancelAnimationFrame(frame) } }, []) - const candidates = listing !== null && listing.ok ? listing.value : [] + // 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 (listing === null) { + if (current === null) { body =
{t('reviewers.loading')}
- } else if (!listing.ok) { + } else if (!current.ok) { body = (
{t('reviewers.loadFailed')} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index dfcf34118a..9fe4e1831d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -692,6 +692,7 @@ export function ChangesTab({ ? { 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 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 6ca8d2fd40..3ce29555e6 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css @@ -616,7 +616,6 @@ color: var(--dsw-alias-label-secondary); } - /* The name of a fact row, read by assistive technology before its value. */ .visuallyHidden { position: absolute; diff --git a/packages/experimental/client-ui-forge/src/client/host-viewed.ts b/packages/experimental/client-ui-forge/src/client/host-viewed.ts index b9d0c76130..25ac561f0b 100644 --- a/packages/experimental/client-ui-forge/src/client/host-viewed.ts +++ b/packages/experimental/client-ui-forge/src/client/host-viewed.ts @@ -1,9 +1,10 @@ /** * Viewed marks a code host keeps for a whole change request. The changes view reads them with the diff and shows each - * mark the reader sets at once, while the host saves it; a mark the host refuses returns to what the host keeps. + * mark the reader sets at once, while the host saves it; a mark the host refuses returns to what the host keeps, and a + * mark the host may have saved stays. */ -import { useMemo, useState } from 'react' +import { useMemo, useRef, useState } from 'react' import type { ForgeViewedFiles, ForgeViewedRequest, ForgeViewedState } from '@deepseek-ai/dsh-experimental-forge/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeDiffFile } from '../types.ts' @@ -26,8 +27,14 @@ export interface HostViewedOwner { readonly viewed: HostViewed } -/** Why a mark the host did not save returned to its previous state. */ -export type HostViewedFailure = { readonly kind: 'stale' } | { readonly kind: 'failed'; readonly message: string } +/** + * Why a mark the host did not save returned to its previous state, or why the view cannot tell whether the host saved + * a mark it keeps showing. + */ +export type HostViewedFailure = + | { readonly kind: 'stale' } + | { readonly kind: 'failed'; readonly message: string } + | { readonly kind: 'unknown'; readonly message: string } /** The host's marks of the shown diff with the reader's writes. */ export interface HostViewedMarks { @@ -46,29 +53,51 @@ export interface HostViewedMarks { readonly mark: (path: string, viewed: boolean) => boolean } -const NO_CHOICES: Readonly> = {} +/** + * The reader's mark of one file over the host's. It applies to every read of its change request and head while its + * write is in flight, and once settled only to `read`, the read shown when it settled, which may not hold it yet. + */ +interface Choice { + readonly viewed: boolean + readonly read: HostViewedOwner + readonly saving: boolean +} + +/** The reader's marks of one change request at one head, by path. */ +interface Choices { + readonly key: string | null + readonly files: ReadonlyMap +} + +const NO_CHOICES: ReadonlyMap = new Map() const NO_MARKS: ViewedMarks = new Map() -const NO_PATHS: ReadonlySet = new Set() /** Digest a dismissed mark records: no file change digests to it, so the file reads as changed since it was viewed. */ const DISMISSED = '' +/** Identity of the marks a read holds: one change request at one head commit. */ +function keyOf(owner: HostViewedOwner): string { + return `${owner.url}\n${owner.headSha}` +} + /** * Convert the host's marks of a diff to digests, with the reader's choices taking the place of the host's. * @param files - files of the diff with the digest of each change. * @param host - the host's state of each file the host listed. - * @param chosen - the reader's marks since the diff loaded, by path. + * @param chosen - the reader's marks that apply to the diff, by path. * @returns the digest of each file marked viewed or dismissed. */ export function hostMarksOf( files: readonly ForgeDiffFile[], host: Readonly>, - chosen: Readonly>, + chosen: ReadonlyMap, ): ViewedMarks { const marks = new Map() for (const file of files) { - const choice = chosen[file.path] - const state = choice === undefined ? host[file.path] : choice ? 'viewed' : 'unviewed' + const choice = chosen.get(file.path) + // Only the host's own entries count, so a path such as `constructor` never reads an inherited property. + const state = choice === undefined ? Object.hasOwn(host, file.path) ? host[file.path] : undefined + : choice ? 'viewed' : 'unviewed' if (state === 'viewed') marks.set(file.path, file.digest) else if (state === 'dismissed') marks.set(file.path, DISMISSED) } @@ -91,10 +120,13 @@ export function hostViewedOf(result: RemoteResult | nul } /** - * Keep the reader's marks of one diff over the host's until the next diff loads, saving each on the host. + * Keep the reader's marks of a change request at one head over the host's, saving each on the host. A read at the same + * head keeps the marks whose writes are in flight and their locks; a mark whose write settled stays until the next read, + * which then holds what the host saved. A read at another head or of another change request starts without choices. * @param owner - the shown diff when the host keeps its marks, else null. * @param save - saves one mark on the host. - * @param failed - reports a mark the host did not save after it returned to its previous state. + * @param failed - reports a mark the host did not save after it returned to its previous state, or a mark the host may + * not have saved. * @returns the marks and the write action, or null when the browser keeps the marks. */ export function useHostViewed( @@ -102,44 +134,60 @@ export function useHostViewed( save: (url: string, request: ForgeViewedRequest) => Promise>, failed: (failure: HostViewedFailure) => void, ): HostViewedMarks | null { - const [chosen, setChosen] = useState<{ readonly owner: HostViewedOwner | null; readonly marks: Readonly> }>( - { owner: null, marks: {} }) - const [saving, setSaving] = useState<{ readonly owner: HostViewedOwner | null; readonly paths: ReadonlySet }>( - { owner: null, paths: new Set() }) - const marks = chosen.owner === owner ? chosen.marks : NO_CHOICES - const shown = useMemo(() => owner?.viewed.kind === 'read' ? hostMarksOf(owner.files, owner.viewed.files, marks) : NO_MARKS, [owner, marks]) - if (owner === null) return null - const inFlight = saving.owner === owner ? saving.paths : NO_PATHS + const [choices, setChoices] = useState({ key: null, files: new Map() }) + // The read a write that settles later finds shown; assigned in render so a settlement after this render sees it. + const shown = useRef(owner) + shown.current = owner + const key = owner === null ? null : keyOf(owner) + const applying = useMemo(() => { + if (owner === null || choices.key !== key) return new Map() + return new Map([...choices.files].filter(([, choice]) => choice.saving || choice.read === owner)) + }, [owner, key, choices]) + const marks = useMemo(() => { + if (owner?.viewed.kind !== 'read') return NO_MARKS + const chosen = applying.size === 0 ? NO_CHOICES : new Map([...applying].map(([path, choice]) => [path, choice.viewed])) + return hostMarksOf(owner.files, owner.viewed.files, chosen) + }, [owner, applying]) + if (owner === null || key === null) return null const { viewed } = owner - // A choice made for an earlier diff never applies to a later one, whose read already holds what the host saved, and a - // write of an earlier diff that settles late leaves the later diff's choices alone. - const choose = (path: string, value: boolean): void => { - setChosen(current => ({ owner, marks: { ...current.owner === owner ? current.marks : {}, [path]: value } })) - } - const restore = (path: string, previous: boolean | undefined): void => { - setChosen((current) => { - if (current.owner !== owner) return current - const { [path]: _mark, ...rest } = current.marks - return { owner, marks: previous === undefined ? rest : { ...rest, [path]: previous } } + const saving = (path: string): boolean => applying.get(path)?.saving === true + /** Settle the write of `path` at this key: keep `next` for the read shown now, or drop the choice. */ + const settle = (path: string, next: boolean | undefined): void => { + setChoices((current) => { + if (current.key !== key) return current + const files = new Map(current.files) + // A read at another key never takes these choices, so only a view without the host's marks keeps the original read. + const read = shown.current ?? owner + if (next === undefined) files.delete(path) + else files.set(path, { viewed: next, read, saving: false }) + return { key, files } }) } - const settle = (path: string): void => { - setSaving(value => value.owner === owner ? { owner, paths: new Set([...value.paths].filter(item => item !== path)) } : value) - } return { - marks: shown, + marks, unavailable: viewed.kind === 'failed', - saving: path => inFlight.has(path), + saving, mark: (path, value) => { - if (viewed.kind === 'failed' || inFlight.has(path)) return false - const previous = marks[path] - choose(path, value) - setSaving(current => ({ owner, paths: new Set([...current.owner === owner ? current.paths : [], path]) })) + if (viewed.kind === 'failed' || saving(path)) return false + const previous = applying.get(path)?.viewed + setChoices((current) => { + const files = new Map(current.key === key ? current.files : []) + return { key, files: files.set(path, { viewed: value, read: owner, saving: true }) } + }) void save(owner.url, { path, viewed: value, headSha: owner.headSha }).then((result) => { - settle(path) - if (result.ok) return - restore(path, previous) - failed(result.error.code === 'forgePanel/stale-head' ? { kind: 'stale' } : { kind: 'failed', message: result.error.message }) + if (result.ok) { + settle(path, value) + return + } + const { code, message } = result.error + // The host may have saved a mark it did not confirm, so the mark stays and the reader is told to check. + if (code === 'forgePanel/action-unknown') { + settle(path, value) + failed({ kind: 'unknown', message }) + return + } + settle(path, previous) + failed(code === 'forgePanel/stale-head' ? { kind: 'stale' } : { kind: 'failed', message }) }) return true }, diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index efaa51cffd..bb31556a50 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -199,6 +199,7 @@ export const zh = { 'branch.changed': '提交已更新,请重新检查后再打开更新菜单', 'toast.branchUpdated': '已开始更新 {name} 的分支', 'toast.branchUpdateFailed': '无法更新分支:{message}', + 'toast.actionUnknown': '未能确认对 {name} 的操作是否已生效,请在浏览器中查看后再重试', 'toast.branchUpdateStale': '{name} 已有新提交,请重新检查后再更新', 'diff.tab': '变更', 'diff.tabNumbered': '#{number} 的变更', @@ -248,6 +249,7 @@ export const zh = { 'viewed.readFailed': '未能读取 GitHub 上的已审阅状态,暂时不能标记文件:{message}', 'viewed.syncFailed': '已审阅状态未能保存到 GitHub:{message}', 'viewed.syncStale': 'PR 已有新提交,已审阅状态未保存。请刷新后再标记', + 'viewed.syncUnknown': '未能确认已审阅状态是否已保存:{message}。刷新后可查看实际状态', 'commits.all': '全部提交', 'commits.range': '{from}…{to}', 'commits.count': '{count} 个提交', @@ -629,6 +631,7 @@ export const en: Record = { 'branch.changed': 'New commits arrived. Review them, then open this menu again.', 'toast.branchUpdated': 'Started updating the branch of {name}', 'toast.branchUpdateFailed': 'Could not update the branch: {message}', + 'toast.actionUnknown': 'Could not confirm whether the action on {name} took effect. Check it in the browser before trying again.', 'toast.branchUpdateStale': '{name} has new commits. Review them before updating.', 'diff.tab': 'Changes', 'diff.tabNumbered': 'Changes in #{number}', @@ -678,6 +681,7 @@ export const en: Record = { 'viewed.readFailed': 'Could not read viewed files from GitHub, so files cannot be marked: {message}', 'viewed.syncFailed': 'Could not save the viewed mark to GitHub: {message}', 'viewed.syncStale': 'The PR has new commits, so the viewed mark was not saved. Refresh and mark the file again.', + 'viewed.syncUnknown': 'Could not confirm that the viewed mark was saved: {message}. Refresh to see where it stands.', 'commits.all': 'All commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -1063,6 +1067,7 @@ export const ja: Record = { 'branch.changed': 'コミットが更新されました。確認してからもう一度メニューを開いてください', 'toast.branchUpdated': '{name} のブランチの更新を開始しました', 'toast.branchUpdateFailed': 'ブランチを更新できませんでした:{message}', + 'toast.actionUnknown': '{name} への操作が反映されたか確認できませんでした。もう一度試す前にブラウザーで確認してください。', 'toast.branchUpdateStale': '{name} に新しいコミットがあります。確認してから更新してください。', 'diff.tab': '変更', 'diff.tabNumbered': '#{number} の変更', @@ -1112,6 +1117,7 @@ export const ja: Record = { 'viewed.readFailed': 'GitHub の確認済み状態を読み込めないため、ファイルに印を付けられません:{message}', 'viewed.syncFailed': '確認済みの印を GitHub に保存できませんでした:{message}', 'viewed.syncStale': 'PR に新しいコミットがあるため、確認済みの印は保存されていません。更新してからもう一度付けてください。', + 'viewed.syncUnknown': '確認済みの印が保存されたか確認できませんでした:{message}。更新すると実際の状態を確認できます。', 'commits.all': 'すべてのコミット', 'commits.range': '{from}…{to}', 'commits.count': '{count} 件のコミット', @@ -1490,6 +1496,7 @@ export const es: Record = { 'branch.changed': 'Llegaron nuevos commits. Revísalos y vuelve a abrir este menú.', 'toast.branchUpdated': 'Se empezó a actualizar la rama de {name}', 'toast.branchUpdateFailed': 'No se pudo actualizar la rama: {message}', + 'toast.actionUnknown': 'No se pudo confirmar si la acción sobre {name} se aplicó. Compruébalo en el navegador antes de volver a intentarlo.', 'toast.branchUpdateStale': '{name} tiene nuevos commits. Revísalos antes de actualizar.', 'diff.tab': 'Cambios', 'diff.tabNumbered': 'Cambios en #{number}', @@ -1539,6 +1546,7 @@ export const es: Record = { 'viewed.readFailed': 'No se pudo leer de GitHub qué archivos se revisaron, así que no se pueden marcar: {message}', 'viewed.syncFailed': 'No se pudo guardar la marca de revisión en GitHub: {message}', 'viewed.syncStale': 'El PR tiene nuevos commits y la marca de revisión no se guardó. Actualiza y vuelve a marcar el archivo.', + 'viewed.syncUnknown': 'No se pudo confirmar que la marca de revisión se guardara: {message}. Actualiza para ver su estado real.', 'commits.all': 'Todos los commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -1917,6 +1925,7 @@ export const fr: Record = { 'branch.changed': 'De nouveaux commits sont arrivés. Vérifiez-les, puis rouvrez ce menu.', 'toast.branchUpdated': 'Mise à jour de la branche de {name} lancée', 'toast.branchUpdateFailed': 'Impossible de mettre à jour la branche : {message}', + 'toast.actionUnknown': 'Impossible de confirmer si l’action sur {name} a pris effet. Vérifiez dans le navigateur avant de réessayer.', 'toast.branchUpdateStale': '{name} contient de nouveaux commits. Vérifiez-les avant la mise à jour.', 'diff.tab': 'Modifications', 'diff.tabNumbered': 'Modifications de #{number}', @@ -1966,6 +1975,7 @@ export const fr: Record = { 'viewed.readFailed': 'Impossible de lire l’état de revue sur GitHub ; les fichiers ne peuvent pas être marqués : {message}', 'viewed.syncFailed': 'Impossible d’enregistrer la marque de revue sur GitHub : {message}', 'viewed.syncStale': 'La PR contient de nouveaux commits ; la marque de revue n’a pas été enregistrée. Actualisez et marquez à nouveau le fichier.', + 'viewed.syncUnknown': 'Impossible de confirmer que la marque de revue a été enregistrée : {message}. Actualisez pour voir son état réel.', 'commits.all': 'Tous les commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', @@ -2344,6 +2354,7 @@ export const de: Record = { 'branch.changed': 'Neue Commits sind eingetroffen. Bitte prüfen und das Menü erneut öffnen.', 'toast.branchUpdated': 'Aktualisierung des Branches von {name} gestartet', 'toast.branchUpdateFailed': 'Der Branch konnte nicht aktualisiert werden: {message}', + 'toast.actionUnknown': 'Ob die Aktion für {name} wirksam wurde, ließ sich nicht bestätigen. Vor einem neuen Versuch im Browser prüfen.', 'toast.branchUpdateStale': '{name} hat neue Commits. Bitte vor dem Aktualisieren prüfen.', 'diff.tab': 'Änderungen', 'diff.tabNumbered': 'Änderungen in #{number}', @@ -2393,6 +2404,7 @@ export const de: Record = { 'viewed.readFailed': 'Der Ansichtsstatus konnte nicht von GitHub gelesen werden, daher lassen sich keine Dateien markieren: {message}', 'viewed.syncFailed': 'Die Ansichtsmarkierung konnte nicht auf GitHub gespeichert werden: {message}', 'viewed.syncStale': 'Der PR hat neue Commits, daher wurde die Ansichtsmarkierung nicht gespeichert. Aktualisieren und die Datei erneut markieren.', + 'viewed.syncUnknown': 'Es ließ sich nicht bestätigen, dass die Ansichtsmarkierung gespeichert wurde: {message}. Zum Prüfen des tatsächlichen Stands aktualisieren.', 'commits.all': 'Alle Commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} Commits', @@ -2771,6 +2783,7 @@ export const ru: Record = { 'branch.changed': 'Появились новые коммиты. Проверьте их и откройте меню снова.', 'toast.branchUpdated': 'Начато обновление ветки {name}', 'toast.branchUpdateFailed': 'Не удалось обновить ветку: {message}', + 'toast.actionUnknown': 'Не удалось подтвердить, применено ли действие для {name}. Проверьте это в браузере, прежде чем пробовать снова.', 'toast.branchUpdateStale': 'В {name} появились новые коммиты. Проверьте их перед обновлением.', 'diff.tab': 'Изменения', 'diff.tabNumbered': 'Изменения в #{number}', @@ -2820,6 +2833,7 @@ export const ru: Record = { 'viewed.readFailed': 'Не удалось прочитать отметки о просмотре с GitHub, поэтому файлы нельзя отметить: {message}', 'viewed.syncFailed': 'Не удалось сохранить отметку о просмотре на GitHub: {message}', 'viewed.syncStale': 'В PR появились новые коммиты, поэтому отметка о просмотре не сохранена. Обновите и отметьте файл снова.', + 'viewed.syncUnknown': 'Не удалось подтвердить, что отметка о просмотре сохранена: {message}. Обновите, чтобы увидеть фактическое состояние.', 'commits.all': 'Все коммиты', 'commits.range': '{from}…{to}', 'commits.count': 'Коммитов: {count}', @@ -3198,6 +3212,7 @@ export const pt: Record = { 'branch.changed': 'Chegaram novos commits. Revise-os e abra este menu novamente.', 'toast.branchUpdated': 'Atualização do branch de {name} iniciada', 'toast.branchUpdateFailed': 'Não foi possível atualizar o branch: {message}', + 'toast.actionUnknown': 'Não foi possível confirmar se a ação em {name} teve efeito. Verifique no navegador antes de tentar novamente.', 'toast.branchUpdateStale': '{name} tem novos commits. Revise-os antes de atualizar.', 'diff.tab': 'Alterações', 'diff.tabNumbered': 'Alterações em #{number}', @@ -3243,10 +3258,11 @@ export const pt: Record = { 'viewed.saveFailed': 'Não foi possível salvar o estado de revisão', 'viewed.hintHost': 'Salvo no GitHub · Pressione V para alternar o arquivo atual', 'viewed.saving': 'Salvando no GitHub…', - 'viewed.unavailable': 'Não foi possível ler de GitHub quais arquivos foram revisados', - 'viewed.readFailed': 'Não foi possível ler de GitHub quais arquivos foram revisados, então não é possível marcá-los: {message}', + 'viewed.unavailable': 'Não foi possível ler do GitHub quais arquivos foram revisados', + 'viewed.readFailed': 'Não foi possível ler do GitHub quais arquivos foram revisados, então não é possível marcá-los: {message}', 'viewed.syncFailed': 'Não foi possível salvar a marca de revisão no GitHub: {message}', - 'viewed.syncStale': 'A PR tem novos commits, então a marca de revisão não foi salva. Atualize e marque o arquivo novamente.', + 'viewed.syncStale': 'O PR tem novos commits, então a marca de revisão não foi salva. Atualize e marque o arquivo novamente.', + 'viewed.syncUnknown': 'Não foi possível confirmar se a marca de revisão foi salva: {message}. Atualize para ver o estado real.', 'commits.all': 'Todos os commits', 'commits.range': '{from}…{to}', 'commits.count': '{count} commits', diff --git a/packages/experimental/client-ui-forge/src/client/mount.ts b/packages/experimental/client-ui-forge/src/client/mount.ts index 7dfa5311b4..d9304ea46a 100644 --- a/packages/experimental/client-ui-forge/src/client/mount.ts +++ b/packages/experimental/client-ui-forge/src/client/mount.ts @@ -170,6 +170,10 @@ function registerUi(ctx: Context): void { const number = numberOf(entry) return number === null ? entry.snapshot?.title ?? entry.url : t('change.number', { number }) } + /** Tell the reader that the code host may have applied an action it did not confirm, which they should check there. */ + const reportUnknown = (entry: ForgePanelChangeRequest): void => { + notices.report('toast.actionUnknown', { params: { name: nameOf(entry) } }) + } const remove = (sessionId: SessionId, entry: ForgePanelChangeRequest): void => { void ctx.remote.forgePanel.dismiss(sessionId, entry.url).then((result) => { if (!settled(result, 'toast.removeFailed')) return @@ -216,24 +220,28 @@ function registerUi(ctx: Context): void { markReady: async (entry) => { const result = await ctx.remote.forgePanel.markReady(sessionId, entry.url) if (result.ok) notices.report('toast.markedReady', { tone: 'success', params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/action-unknown') reportUnknown(entry) else notices.report('toast.markReadyFailed', { params: { message: result.error.message } }) }, merge: async (entry, request) => { const result = await ctx.remote.forgePanel.merge(sessionId, entry.url, request.method, request.headSha) if (result.ok) notices.report('toast.merged', { tone: 'success', params: { name: nameOf(entry) } }) else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.mergeStale', { params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/action-unknown') reportUnknown(entry) else notices.report('toast.mergeFailed', { params: { message: result.error.message } }) }, rerunChecks: async (entry, request) => { const result = await ctx.remote.forgePanel.rerunChecks(sessionId, entry.url, request) if (result.ok) notices.report('toast.rerunRequested', { tone: 'success', params: { name: nameOf(entry) } }) else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.rerunStale', { params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/action-unknown') reportUnknown(entry) else notices.report('toast.rerunFailed', { params: { message: result.error.message } }) }, requestReviews: async (entry, reviewers) => { const result = await ctx.remote.forgePanel.requestReviews(sessionId, entry.url, reviewers) const login = reviewers.map(reviewer => reviewer.login).join(', ') if (result.ok) notices.report('toast.reviewRequested', { tone: 'success', params: { name: nameOf(entry), login } }) + else if (result.error.code === 'forgePanel/action-unknown') reportUnknown(entry) else notices.report('toast.reviewRequestFailed', { params: { message: result.error.message } }) }, reviewerCandidates: async (url, query, signal) => { @@ -245,6 +253,7 @@ function registerUi(ctx: Context): void { const result = await ctx.remote.forgePanel.updateBranch(sessionId, entry.url, request.method, request.headSha) if (result.ok) notices.report('toast.branchUpdated', { tone: 'success', params: { name: nameOf(entry) } }) else if (result.error.code === 'forgePanel/stale-head') notices.report('toast.branchUpdateStale', { params: { name: nameOf(entry) } }) + else if (result.error.code === 'forgePanel/action-unknown') reportUnknown(entry) else notices.report('toast.branchUpdateFailed', { params: { message: result.error.message } }) }, restore: () => { diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 3e6af9b8ad..3e42c6cfc6 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -493,7 +493,8 @@ export class ForgePanelController extends TypertRemoteService { * @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. + * 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 { @@ -640,7 +641,8 @@ export class ForgePanelController extends TypertRemoteService { * @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. + * 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 { @@ -657,7 +659,8 @@ export class ForgePanelController extends TypertRemoteService { * @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-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( @@ -698,7 +701,8 @@ export class ForgePanelController extends TypertRemoteService { * @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. + * 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 { @@ -1133,7 +1137,9 @@ async function diffing(reading: Promise): Promise { * @returns the Remote error to throw. */ function actionError(failure: ForgeActionFailure): RemoteError { - return new RemoteError(failure.code === 'stale' ? 'forgePanel/stale-head' : 'forgePanel/action-failed', failure.message, {}) + const code = failure.code === 'stale' ? 'forgePanel/stale-head' : failure.code === 'unknown' ? 'forgePanel/action-unknown' + : 'forgePanel/action-failed' + return new RemoteError(code, failure.message, {}) } /** diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 4ea0637fdc..22c641e0d3 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -452,6 +452,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/stale-head': Record /** The code host refused the change or could not be reached; the message gives the host's reason. */ 'forgePanel/action-failed': Record + /** The code host did not confirm whether it applied the change, which must be checked there before trying again. */ + 'forgePanel/action-unknown': Record /** The Session's directory is not inside a Git checkout, so it has no local changes. */ 'forgePanel/not-a-checkout': Record /** diff --git a/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx index 4e1439ddf2..91366522ec 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-overview.client.spec.tsx @@ -53,7 +53,9 @@ describe('rerunning failed checks', () => { it('offers to rerun the failed checks that name a rerun, and runs one rerun at a time', async () => { const done = Promise.withResolvers() const rerunChecks = vi.fn>(() => done.promise) - const b = card(snapshot(7, { checks: [failed], checksRollup: 'failure', canRerunChecks: true }), { rerunChecks }) + // A check still running under another rerun leaves this one free. + const running = check('e2e', { state: 'pending', rerun: 'actions:8' as ForgeCheckId }) + const b = card(snapshot(7, { checks: [failed, running], checksRollup: 'failure', canRerunChecks: true }), { rerunChecks }) const row = b.item.querySelector('[data-forge-checks]') as HTMLElement fireEvent.click(row) fireEvent.click(screen.getByRole('menuitem', { name: en['checks.rerunFailed'] })) @@ -68,6 +70,8 @@ describe('rerunning failed checks', () => { it.each([ ['the viewer may not rerun checks', { canRerunChecks: false }, true], ['no failed check names a rerun', { checks: [check('lint', { state: 'failure' }), check('test', { rerun: 'actions:7' as ForgeCheckId })] }, true], + ['every failed check waits for a check of its rerun still in progress', + { checks: [failed, check('e2e', { state: 'pending', rerun: 'actions:7' as ForgeCheckId })] }, true], ['the surface cannot rerun checks', {}, false], ])('does not offer it when %s', (_label, overrides, withAction) => { const b = card(snapshot(7, { checks: [failed], checksRollup: 'failure', canRerunChecks: true, ...overrides }), @@ -208,6 +212,30 @@ describe('reviewers', () => { expect(requestReviews).toHaveBeenCalledWith(b.subject, [{ kind: 'user', login: 'lin' }]) }) + it('chooses nothing with Enter until the listing of the current query arrives', async () => { + const requestReviews = vi.fn>(async () => {}) + const bob = Promise.withResolvers() + const reviewerCandidates = vi.fn>() + .mockResolvedValueOnce([{ login: 'alice', name: null, avatarUrl: null, suggested: true }]) + .mockReturnValueOnce(bob.promise) + const b = card(snapshot(7, { canRequestReviews: true }), { requestReviews, reviewerCandidates }) + fireEvent.click(b.item.querySelector('[data-forge-review]') as HTMLElement) + fireEvent.click(screen.getByRole('menuitem', { name: en['reviewers.requestMore'] })) + await wait() + const field = screen.getByRole('textbox', { name: en['reviewers.search'] }) + fireEvent.change(field, { target: { value: 'bob' } }) + // The earlier listing is gone at once, before the search delay ends. + expect(screen.getByRole('status').textContent).toBe(en['reviewers.loading']) + expect(screen.queryByRole('menuitem', { name: /alice/ })).toBeNull() + fireEvent.keyDown(field, { key: 'Enter' }) + await wait(200) + fireEvent.keyDown(field, { key: 'Enter' }) + expect(requestReviews).not.toHaveBeenCalled() + await act(async () => { bob.resolve([{ login: 'bob', name: null, avatarUrl: null, suggested: false }]); await Promise.resolve() }) + fireEvent.keyDown(field, { key: 'Enter' }) + expect(requestReviews).toHaveBeenCalledWith(b.subject, [{ kind: 'user', login: 'bob' }]) + }) + it('reports an empty or failed listing, retries, and ignores a listing that arrives after the menu closed', async () => { const late = Promise.withResolvers() const reviewerCandidates = vi.fn>() diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index d83ff1a820..495ca88e83 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -1906,7 +1906,30 @@ describe('ChangesTab viewed marks the host keeps', () => { expect(box(m, 'src/app.ts', 'app.ts').closest('label')?.title).toBe(en['viewed.hint']) }) - it('drops the choices of an earlier diff once the next one loads with the host\'s marks', async () => { + it('keeps a write in flight and its lock across a read at the same head, and the saved choice until the next read', async () => { + const saved = Promise.withResolvers>() + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({})) + faces.setFileViewed.mockReturnValueOnce(saved.promise) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + // The read the refresh starts predates the write, so it holds no mark for the file. + fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) + await settle() + expect(m.faces.changeRequestViewed).toHaveBeenCalledTimes(2) + expect(marks(m)[2]?.[1]).toBe('viewed') + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(true) + await act(async () => { saved.resolve(ok(undefined)); await Promise.resolve() }) + expect(marks(m)[2]?.[1]).toBe('viewed') + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) + // The next read holds what the host keeps, which wins over the settled choice. + fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) + await settle() + expect(marks(m)[2]?.[1]).toBe('unviewed') + }) + + it('returns a mark refused after a read at the same head to that read, leaving other writes in flight locked', async () => { const saved = Promise.withResolvers>() const m = mount({ source, setup: (faces) => { faces.changeRequestViewed.mockResolvedValue(hosted({})) @@ -1917,8 +1940,7 @@ describe('ChangesTab viewed marks the host keeps', () => { m.faces.changeRequestViewed.mockResolvedValue(hosted({ 'docs/notes.txt': 'viewed' })) fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) await settle() - expect(marks(m).map(row => row[1])).toEqual(['unviewed', 'viewed', 'unviewed']) - // A write of the next diff is in flight when the earlier one settles; only its own settlement unlocks its file. + expect(marks(m).map(row => row[1])).toEqual(['unviewed', 'viewed', 'viewed']) const next = Promise.withResolvers>() m.faces.setFileViewed.mockReturnValueOnce(next.promise) fireEvent.click(box(m, 'docs/gone.txt', 'gone.txt')) @@ -1926,9 +1948,72 @@ describe('ChangesTab viewed marks the host keeps', () => { expect(marks(m).map(row => row[1])).toEqual(['viewed', 'viewed', 'unviewed']) expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(true) + expect(m.faces.report).toHaveBeenCalledWith('viewed.syncFailed', { message: 'late' }) await act(async () => { next.resolve(ok(undefined)); await Promise.resolve() }) expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(false) }) + + it('starts the diff of another head without the earlier choices, which a late write leaves alone', async () => { + const saved = Promise.withResolvers>() + const moved = 'b'.repeat(40) + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({})) + faces.setFileViewed.mockReturnValueOnce(saved.promise) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + m.faces.changeRequestDiff.mockResolvedValue(ok({ ...CHANGE, headSha: moved })) + m.faces.changeRequestViewed.mockResolvedValue(hosted({}, moved)) + const polled = entry(7, snapshot(7, { headSha: moved })) + const status = { ...polled, update: { ...polled.update!, fetchedAt: 2 } } + act(() => { m.panel.set({ state: ready({ changeRequests: [status] }), disconnected: false }) }) + await settle() + expect(m.faces.changeRequestViewed).toHaveBeenLastCalledWith(URL7, moved, expect.any(AbortSignal)) + expect(marks(m)[2]?.[1]).toBe('unviewed') + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) + // A write at the new head is in flight when the earlier one settles, which leaves it and its lock alone. + const next = Promise.withResolvers>() + m.faces.setFileViewed.mockReturnValueOnce(next.promise) + fireEvent.click(box(m, 'docs/gone.txt', 'gone.txt')) + await act(async () => { saved.resolve(ok(undefined)); await Promise.resolve() }) + expect(marks(m).map(row => row[1])).toEqual(['viewed', 'unviewed', 'unviewed']) + expect(box(m, 'docs/gone.txt', 'gone.txt').disabled).toBe(true) + }) + + it('keeps a write that settles while chosen commits show for the read it was made on', async () => { + const saved = Promise.withResolvers>() + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({})) + faces.setFileViewed.mockReturnValueOnce(saved.promise) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + fireEvent.click(m.view.getByRole('button', { name: 'Commits shown: All commits' })) + await settle() + fireEvent.click(within(document.body).getByRole('menuitem', { name: /^3333333/ })) + await settle() + await act(async () => { saved.resolve(ok(undefined)); await Promise.resolve() }) + // Returning to all commits reads the host's marks again, which then decide. + fireEvent.click(m.view.getByRole('button', { name: /^Commits shown: 3333333/ })) + await settle() + fireEvent.click(within(document.body).getByRole('menuitem', { name: /^All commits/ })) + await settle() + expect(marks(m)[2]?.[1]).toBe('unviewed') + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) + }) + + it('keeps a mark the host may have saved and tells the reader to check', async () => { + const m = mount({ source, setup: (faces) => { + faces.changeRequestViewed.mockResolvedValue(hosted({})) + faces.setFileViewed.mockResolvedValue({ ok: false, error: new RemoteError('forgePanel/action-unknown', 'Something went wrong', {}) }) + } }) + await settle() + fireEvent.click(box(m, 'src/app.ts', 'app.ts')) + await settle() + expect(marks(m)[2]?.[1]).toBe('viewed') + expect(box(m, 'src/app.ts', 'app.ts').disabled).toBe(false) + expect(m.faces.report).toHaveBeenCalledWith('viewed.syncUnknown', { message: 'Something went wrong' }) + }) }) describe('ChangesTab viewed files', () => { diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index fae3229789..064d66d112 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -1920,6 +1920,10 @@ describe('forgePanel actions', () => { requestReviews.mockResolvedValueOnce({ code: 'failed', message: 'Could not resolve user' }) await expect(opened.ctx.forgePanel.requestReviews(opened.session, pullUrl(7), reviewers, signal)) .rejects.toMatchObject({ code: 'forgePanel/action-failed', message: 'Could not resolve user' }) + // An outcome the host did not confirm keeps its own code, so the reader is told to check it there. + requestReviews.mockResolvedValueOnce({ code: 'unknown', message: 'Something went wrong' }) + await expect(opened.ctx.forgePanel.requestReviews(opened.session, pullUrl(7), reviewers, signal)) + .rejects.toMatchObject({ code: 'forgePanel/action-unknown', message: 'Something went wrong' }) for (const url of [pullUrl(8), 'https://unserved.test/a/b/pull/3']) { await expect(opened.ctx.forgePanel.rerunChecks(opened.session, url, { headSha: head }, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) await expect(opened.ctx.forgePanel.requestReviews(opened.session, url, reviewers, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) diff --git a/packages/experimental/client-ui-forge/tests/host-viewed.client.spec.ts b/packages/experimental/client-ui-forge/tests/host-viewed.client.spec.ts new file mode 100644 index 0000000000..d4a9ee56c7 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/host-viewed.client.spec.ts @@ -0,0 +1,21 @@ +/** The host's viewed marks of a diff as digests, with the reader's choices taking their place. */ +import { describe, expect, it } from 'vitest' +import type { ForgeViewedState } from '@deepseek-ai/dsh-experimental-forge/types' +import { hostMarksOf } from '../src/client/host-viewed.ts' +import type { ForgeDiffFile } from '../src/types.ts' + +function file(path: string): ForgeDiffFile { + return { path, previousPath: null, status: 'modified', binary: false, oversized: false, untracked: false, layer: 'implementation', + digest: `digest-${path}`, additions: 1, deletions: 0, hunks: [] } +} + +describe('hostMarksOf', () => { + it('reads only the host\'s own entries and the reader\'s choices for paths named after object properties', () => { + const files = ['__proto__', 'constructor', 'toString', 'hasOwnProperty'].map(file) + // Parsed as the transport does, so `__proto__` is the host's own entry. + const host = JSON.parse('{"__proto__":"viewed","toString":"dismissed"}') as Record + expect([...hostMarksOf(files, host, new Map())]).toEqual([['__proto__', 'digest-__proto__'], ['toString', '']]) + expect([...hostMarksOf(files, host, new Map([['constructor', true], ['__proto__', false]]))]) + .toEqual([['constructor', 'digest-constructor'], ['toString', '']]) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts index 8d33c0abbc..5124c90ea3 100644 --- a/packages/experimental/client-ui-forge/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/mount.client.spec.ts @@ -94,6 +94,7 @@ const REFUSED = { failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }, stale: { ok: false, error: new RemoteError('forgePanel/stale-head', 'Head branch was modified', {}) }, refused: { ok: false, error: new RemoteError('forgePanel/action-failed', 'Pull Request is not mergeable', {}) }, + unknown: { ok: false, error: new RemoteError('forgePanel/action-unknown', 'Something went wrong', {}) }, } satisfies Record> function isTabFace(value: Record): value is Record & ForgeTabInjected { @@ -634,6 +635,7 @@ describe('mountForgePanel change request actions', () => { it.each([ ['confirms it', OK, { key: 'toast.markedReady', tone: 'success', params: { name: '#7' } }], ['reports why the host refused', REFUSED.refused, { key: 'toast.markReadyFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ['tells the reader to check an outcome the host did not confirm', REFUSED.unknown, { key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }], ])('marks a draft ready through the Remote and %s', async (_label, result, notice) => { const f = await fixture() f.forgePanel.markReady.mockResolvedValueOnce(result) @@ -647,6 +649,7 @@ describe('mountForgePanel change request actions', () => { ['confirms it', OK, { key: 'toast.merged', tone: 'success', params: { name: '#7' } }], ['says a moved head needs another look', REFUSED.stale, { key: 'toast.mergeStale', tone: 'failure', params: { name: '#7' } }], ['reports why the host refused', REFUSED.refused, { key: 'toast.mergeFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ['tells the reader to check an outcome the host did not confirm', REFUSED.unknown, { key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }], ])('merges through the Remote with the confirmed head and %s', async (_label, result, notice) => { const f = await fixture() f.forgePanel.merge.mockResolvedValueOnce(result) @@ -664,6 +667,7 @@ describe('mountForgePanel overview actions', () => { ['confirms it', OK, { key: 'toast.rerunRequested', tone: 'success', params: { name: '#7' } }], ['says a moved head needs another look', REFUSED.stale, { key: 'toast.rerunStale', tone: 'failure', params: { name: '#7' } }], ['reports why the host refused', REFUSED.refused, { key: 'toast.rerunFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ['tells the reader to check an outcome the host did not confirm', REFUSED.unknown, { key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }], ])('reruns failed checks through the Remote and %s', async (_label, result, notice) => { const f = await fixture() f.forgePanel.rerunChecks.mockResolvedValueOnce(result) @@ -676,6 +680,7 @@ describe('mountForgePanel overview actions', () => { it.each([ ['confirms it', OK, { key: 'toast.reviewRequested', tone: 'success', params: { name: '#7', login: 'mona, lin' } }], ['reports why the host refused', REFUSED.refused, { key: 'toast.reviewRequestFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ['tells the reader to check an outcome the host did not confirm', REFUSED.unknown, { key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }], ])('requests reviews through the Remote and %s', async (_label, result, notice) => { const f = await fixture() f.forgePanel.requestReviews.mockResolvedValueOnce(result) @@ -700,6 +705,7 @@ describe('mountForgePanel overview actions', () => { ['confirms it', OK, { key: 'toast.branchUpdated', tone: 'success', params: { name: '#7' } }], ['says a moved head needs another look', REFUSED.stale, { key: 'toast.branchUpdateStale', tone: 'failure', params: { name: '#7' } }], ['reports why the host refused', REFUSED.refused, { key: 'toast.branchUpdateFailed', tone: 'failure', params: { message: 'Pull Request is not mergeable' } }], + ['tells the reader to check an outcome the host did not confirm', REFUSED.unknown, { key: 'toast.actionUnknown', tone: 'failure', params: { name: '#7' } }], ])('updates the branch through the Remote with the confirmed head and %s', async (_label, result, notice) => { const f = await fixture() f.forgePanel.updateBranch.mockResolvedValueOnce(result) diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 52977df4e4..0cee1a4f70 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: ba6f281a24f3cce0 - zh: b99a3c479b250402 + en: d19ccf4e026491ad + zh: b70fa4b2affa8340 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 9b639e511e850042 zh: 25a1a3bde330e7da diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index d272b7bc67..829cf388aa 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -56,9 +56,9 @@ The same first page reads what the signed-in viewer may write: each thread's `vi `writeReview` first reads the pull request's `headRefOid` and the viewer's pending review in one GraphQL query and returns `stale` without writing when the head is not `write.headSha`. It then sends one mutation with its variables as JSON on stdin: `addPullRequestReviewThreadReply`, inside the pending review for a pending reply; `resolveReviewThread` or `unresolveReviewThread`; `updatePullRequestReviewComment` or `deletePullRequestReviewComment`; `addPullRequestReviewThread` into the pending review, or `addPullRequestReview` at `write.headSha` with the comment as its first thread when the viewer has none; and `submitPullRequestReview` or `deletePullRequestReview` for the pending review the write names, which the check must still find. A pending reply without a pending review first starts an empty one at the head, so it takes two mutations; when the reply then fails, the empty review stays. A write to a thread or comment also reads, in the same check, the pull request that holds it, and returns `failed` without a mutation when that is another pull request. GitHub adds every reply of a user with a pending review to that review, even one sent without its id, so a reply at once returns `failed` without a mutation while the viewer has one; a thread added to a pending review numbers the lines of the current head, whichever commit the review started at. A mutation's payload means GitHub applied it; GraphQL errors whose types all name a refusal (`FORBIDDEN`, `INSUFFICIENT_SCOPES`, `NOT_FOUND`, `RATE_LIMITED`, `UNPROCESSABLE`) and HTTP 400, 401, 403, 404, 409, and 422 refusals return `failed`, as does a `gh` that cannot start; any other GraphQL error, such as GitHub's timeout message, a `gh` timeout, a server error, or an answer without the payload returns `unknown`. No mutation is retried. -Every status read also reads the overview of each pull request: up to 25 review requests, latest reviews, latest opinionated reviews, and closing issue references, each list marked truncated when GitHub counts more. A review request names a user, bot, or team, and whether it is a code owner request. Reviews of the author and reviews without an author are left out; a dismissed review counts as `dismissed`, and a later opinionated review decides the verdict over a comment. `branchUpdates` is empty for a pull request that is not open, that GitHub reports as conflicting, or whose head the signed-in user may not update; otherwise it offers merge, and rebase as well when GitHub can rebase the head. `canRequestReviews` requires triage, write, maintain, or admin permission on an open pull request, and `canRerunChecks` requires write, maintain, or admin permission. A check run of a GitHub Actions workflow names its workflow run as `rerun`; status contexts and other check runs name none. +Every status read also reads the overview of each pull request: up to 25 review requests, latest reviews, latest opinionated reviews, and closing issue references, each list marked truncated when GitHub counts more. A review request names a user, bot, or team, and whether it is a code owner request. Reviews of the author and reviews without an author are left out; a dismissed review counts as `dismissed`, and a later opinionated review decides the verdict over a comment. `branchUpdates` is empty for a pull request that is not open, that GitHub reports as conflicting, or whose head the signed-in user may not update, as GitHub's `viewerCanUpdateBranch` is false both for a head that is up to date and for a user without the right to update it; otherwise it offers merge, and rebase as well when GitHub's `canBeRebased` is true. `canBeRebased` reports whether the pull request can be rebase merged, so it follows the repository's rebase merge setting, and a repository without rebase merges is offered merge only. `mergeStateStatus` does not tell a head behind its base, since BLOCKED, DIRTY, and UNSTABLE take precedence over BEHIND: of 23 open pull requests of this repository whose head was behind its base, none reported BEHIND. `canRequestReviews` requires triage, write, maintain, or admin permission on an open pull request, and `canRerunChecks` requires write, maintain, or admin permission. A check run of a GitHub Actions workflow names its workflow run as `rerun`; status contexts and other check runs name none. -`viewedFiles` lists the pull request's files through GraphQL, 100 per page, up to `maxViewedFiles` (default 3,000) files, and sets `truncated` when GitHub counts more; GitHub's `VIEWED`, `UNVIEWED`, and `DISMISSED` map to `viewed`, `unviewed`, and `dismissed`, and an unknown state to `unviewed`. A page whose head is not the requested commit makes the read `stale`, and a page that does not advance makes it `unavailable`. `setViewed` checks the head, then calls `markFileAsViewed` or `unmarkFileAsViewed`; GitHub keeps one viewed mark per file and user, whatever the commit. `rerunChecks` reads the complete checks, returns `stale` when the head moved, and posts `repos///actions/runs//rerun-failed-jobs` once for each workflow run with a failed check, stopping at the first refusal; GitHub reruns the failed jobs with the jobs that depend on them. `requestReviews` calls `requestReviewsByLogin` with `union: true`, so existing requests stay, and adds the `[bot]` suffix to bot logins. `reviewerCandidates` lists up to 20 assignable users whose login or name contains the query, and with an empty query GitHub's suggested reviewers first; the author is left out. `updateBranch` checks the head, then calls `updatePullRequestBranch` with the update method and `expectedHeadOid`, so GitHub refuses once new commits arrived. These mutations go through the sender `writeReview` uses, with their GraphQL document and variables as JSON on stdin, and are never retried; because each sets a state, a refusal and an outcome GitHub did not confirm both become `failed` with GitHub's message. +`viewedFiles` lists the pull request's files through GraphQL, 100 per page, up to `maxViewedFiles` (default 3,000) files, and sets `truncated` when GitHub counts more; GitHub's `VIEWED`, `UNVIEWED`, and `DISMISSED` map to `viewed`, `unviewed`, and `dismissed`, and an unknown state to `unviewed`. A page whose head is not the requested commit makes the read `stale`, and a page that does not advance makes it `unavailable`. `setViewed` checks the head, then calls `markFileAsViewed` or `unmarkFileAsViewed`; GitHub keeps one viewed mark per file and user, whatever the commit. `rerunChecks` reads the complete checks, returns `stale` when the head moved, and posts `repos///actions/runs//rerun-failed-jobs` once for each workflow run with a failed check and no pending one, as GitHub offers no rerun of a run in progress; it tries every such run, reports the refused ones together, and stops early only for missing credentials. GitHub reruns the failed jobs with the jobs that depend on them. `requestReviews` resolves user logins and `organization/slug` team names to node ids in one GraphQL query and calls `requestReviews` with `union: true`, so existing requests stay; bot logins, given the `[bot]` suffix, go to `requestReviewsByLogin` afterwards, which GitHub Enterprise Server 3.19 and 3.20 lack. `reviewerCandidates` lists up to 20 assignable users whose login or name contains the query, and with an empty query GitHub's suggested reviewers first; the author is left out. `updateBranch` checks the head, then calls `updatePullRequestBranch` with the update method and `expectedHeadOid`, so GitHub refuses once new commits arrived. These mutations go through the sender `writeReview` uses, with their GraphQL document and variables as JSON on stdin, and are never retried: a refusal becomes `failed` and an answer that does not confirm the outcome becomes `unknown`, each with GitHub's message. ----- diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 9750b2846a..997808e78c 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -56,9 +56,9 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `writeReview` 先用一次 GraphQL 查询读出 pull request 的 `headRefOid` 和用户的待提交评审;head 不是 `write.headSha` 时不写入,直接返回 `stale`。随后发送一个 mutation,变量以 JSON 形式经 stdin 传入:回复用 `addPullRequestReviewThreadReply`,待提交的回复加入待提交评审;`resolveReviewThread` 或 `unresolveReviewThread`;`updatePullRequestReviewComment` 或 `deletePullRequestReviewComment`;新评论用 `addPullRequestReviewThread` 加入待提交评审,用户还没有待提交评审时,用 `addPullRequestReview` 在 `write.headSha` 上开始一个评审,并把这条评论作为它的第一个讨论;提交或丢弃用 `submitPullRequestReview` 或 `deletePullRequestReview`,作用于写操作指定的待提交评审,检查时必须仍能找到它。没有待提交评审时,待提交的回复会先在 head 上开始一个空评审,因此需要两个 mutation;回复随后失败时,这个空评审会保留下来。写入讨论或评论时,同一次检查还会读出它所属的 pull request,不是当前 pull request 时不发送 mutation,直接返回 `failed`。用户有待提交评审时,GitHub 会把该用户的每条回复都加入这个评审,即使发送时没有带上评审 id;因此该用户有待提交评审时,立即回复不发送 mutation,直接返回 `failed`。加入待提交评审的讨论使用当前 head 的行号,与评审开始时所在的提交无关。mutation 返回 payload 即表示 GitHub 已执行;错误类型全部表示拒绝(`FORBIDDEN`、`INSUFFICIENT_SCOPES`、`NOT_FOUND`、`RATE_LIMITED`、`UNPROCESSABLE`)的 GraphQL 错误以及 HTTP 400、401、403、404、409、422 拒绝返回 `failed`,`gh` 无法启动时也是如此;其他 GraphQL 错误(例如 GitHub 的超时提示)、`gh` 超时、服务端错误或没有 payload 的响应返回 `unknown`。mutation 从不重试。 -每次状态读取还会读取每个 pull request 的概览:最多 25 个评审请求、最近评审、最近的表态评审与关闭的 issue 引用,GitHub 统计到更多时把对应列表标记为截断。评审请求指向用户、bot 或团队,并说明是否为代码所有者请求。作者本人的评审与没有作者的评审被略去;被驳回的评审记为 `dismissed`,较新的表态评审优先于评论决定结论。pull request 未处于 open、GitHub 报告存在冲突或当前登录用户无权更新其 head 时,`branchUpdates` 为空;否则提供 merge,GitHub 能变基该 head 时也提供 rebase。`canRequestReviews` 要求 open 的 pull request 与 triage、write、maintain 或 admin 权限,`canRerunChecks` 要求 write、maintain 或 admin 权限。GitHub Actions 工作流的 check run 以其工作流运行作为 `rerun`;状态上下文与其他 check run 没有 `rerun`。 +每次状态读取还会读取每个 pull request 的概览:最多 25 个评审请求、最近评审、最近的表态评审与关闭的 issue 引用,GitHub 统计到更多时把对应列表标记为截断。评审请求指向用户、bot 或团队,并说明是否为代码所有者请求。作者本人的评审与没有作者的评审被略去;被驳回的评审记为 `dismissed`,较新的表态评审优先于评论决定结论。pull request 未处于 open、GitHub 报告存在冲突或当前登录用户无权更新其 head 时,`branchUpdates` 为空:head 已是最新、或用户无权更新时,GitHub 的 `viewerCanUpdateBranch` 都为 false。否则提供 merge,GitHub 的 `canBeRebased` 为 true 时也提供 rebase。`canBeRebased` 表示该 pull request 能否以 rebase 方式合并,因此跟随仓库的 rebase 合并设置,不允许 rebase 合并的仓库只提供 merge。`mergeStateStatus` 无法判断 head 是否落后于基线,因为 BLOCKED、DIRTY 与 UNSTABLE 优先于 BEHIND:本仓库 23 个 head 落后于基线的 open pull request 中,没有一个报告 BEHIND。`canRequestReviews` 要求 open 的 pull request 与 triage、write、maintain 或 admin 权限,`canRerunChecks` 要求 write、maintain 或 admin 权限。GitHub Actions 工作流的 check run 以其工作流运行作为 `rerun`;状态上下文与其他 check run 没有 `rerun`。 -`viewedFiles` 经 GraphQL 每页 100 个列出 pull request 的文件,最多 `maxViewedFiles`(默认 3,000)个,GitHub 统计到更多时设置 `truncated`;GitHub 的 `VIEWED`、`UNVIEWED` 与 `DISMISSED` 分别映射为 `viewed`、`unviewed` 与 `dismissed`,未知状态映射为 `unviewed`。某页的 head 不是请求的提交时读取为 `stale`,分页不前进时为 `unavailable`。`setViewed` 先检查 head,再调用 `markFileAsViewed` 或 `unmarkFileAsViewed`;GitHub 对每个文件和用户只保存一个已审阅标记,与提交无关。`rerunChecks` 读取完整检查,head 已移动时返回 `stale`,再对每个含失败检查的工作流运行 POST 一次 `repos///actions/runs//rerun-failed-jobs`,遇到第一次拒绝即停止;GitHub 会重跑失败的 job 及依赖它们的 job。`requestReviews` 以 `union: true` 调用 `requestReviewsByLogin`,保留已有请求,并为 bot 登录名加上 `[bot]` 后缀。`reviewerCandidates` 列出登录名或名称包含查询文本的最多 20 个可指派用户,查询为空时 GitHub 建议的评审者排在最前;作者被略去。`updateBranch` 先检查 head,再以更新方式与 `expectedHeadOid` 调用 `updatePullRequestBranch`,因此新提交到来后 GitHub 会拒绝。这些写操作与 `writeReview` 使用同一个发送方式,把 GraphQL 文档与变量作为 JSON 经标准输入发送,且从不重试;由于每个写操作都只设置一种状态,GitHub 的拒绝与未确认的结果都为 `failed`,并附 GitHub 的原因。 +`viewedFiles` 经 GraphQL 每页 100 个列出 pull request 的文件,最多 `maxViewedFiles`(默认 3,000)个,GitHub 统计到更多时设置 `truncated`;GitHub 的 `VIEWED`、`UNVIEWED` 与 `DISMISSED` 分别映射为 `viewed`、`unviewed` 与 `dismissed`,未知状态映射为 `unviewed`。某页的 head 不是请求的提交时读取为 `stale`,分页不前进时为 `unavailable`。`setViewed` 先检查 head,再调用 `markFileAsViewed` 或 `unmarkFileAsViewed`;GitHub 对每个文件和用户只保存一个已审阅标记,与提交无关。`rerunChecks` 读取完整检查,head 已移动时返回 `stale`,再对每个含失败检查且没有进行中检查的工作流运行 POST 一次 `repos///actions/runs//rerun-failed-jobs`,因为 GitHub 不提供运行中工作流的重跑;它会尝试每个这样的运行,汇总报告被拒绝的运行,只在缺少凭据时提前停止。GitHub 会重跑失败的 job 及依赖它们的 job。`requestReviews` 在一次 GraphQL 查询中把用户登录名与 `organization/slug` 形式的团队名解析为节点 id,再以 `union: true` 调用 `requestReviews`,保留已有请求;bot 登录名加上 `[bot]` 后缀后,随后交给 `requestReviewsByLogin`,GitHub Enterprise Server 3.19 与 3.20 没有该 mutation。`reviewerCandidates` 列出登录名或名称包含查询文本的最多 20 个可指派用户,查询为空时 GitHub 建议的评审者排在最前;作者被略去。`updateBranch` 先检查 head,再以更新方式与 `expectedHeadOid` 调用 `updatePullRequestBranch`,因此新提交到来后 GitHub 会拒绝。这些写操作与 `writeReview` 使用同一个发送方式,把 GraphQL 文档与变量作为 JSON 经标准输入发送,且从不重试:拒绝为 `failed`,无法确认结果的答复为 `unknown`,都附 GitHub 的原因。 ----- diff --git a/packages/experimental/forge-github/src/graphql.ts b/packages/experimental/forge-github/src/graphql.ts index 479c3f3c54..3302c55534 100644 --- a/packages/experimental/forge-github/src/graphql.ts +++ b/packages/experimental/forge-github/src/graphql.ts @@ -536,6 +536,10 @@ function toSnapshot( mergeReady: settings !== undefined && MERGERS.has(settings.viewerPermission ?? '') && node.state === 'OPEN' && !node.isDraft && MERGEABLE_NOW.has(node.mergeStateStatus), mergeMethods: settings === undefined ? [] : mergeMethods(settings), + // GitHub's `viewerCanUpdateBranch` is false while the head is up to date as well as when the viewer may not update + // it; `mergeStateStatus` cannot tell a head behind its base, as BLOCKED and the other states take precedence over + // BEHIND. `canBeRebased` reports whether the pull request can be rebase merged, which follows the repository's rebase + // merge setting, so rebase is offered only where a rebase merge is allowed. branchUpdates: !open || !node.viewerCanUpdateBranch || node.mergeable === 'CONFLICTING' ? [] : node.canBeRebased ? ['merge', 'rebase'] : ['merge'], reviewDecision: reviewDecision(node.reviewDecision), diff --git a/packages/experimental/forge-github/src/mutation.ts b/packages/experimental/forge-github/src/mutation.ts index 0261f8d6e3..a67c17b12d 100644 --- a/packages/experimental/forge-github/src/mutation.ts +++ b/packages/experimental/forge-github/src/mutation.ts @@ -34,8 +34,8 @@ export type MutationResult = | { readonly ok: false; readonly code: 'failed' | 'unknown'; readonly message: string } /** - * Runs one mutation on `host` through {@link sendMutation}; resolves to undefined once GitHub applied it, or to a - * `failed` action failure when GitHub refused it or did not confirm it. + * Runs one mutation on `host` through {@link sendMutation}; resolves to undefined once GitHub applied it, to a `failed` + * action failure when GitHub refused it, or to an `unknown` one when GitHub did not confirm it. */ export type GraphqlWriter = (host: string, mutation: GraphqlMutation, signal: AbortSignal) => Promise diff --git a/packages/experimental/forge-github/src/overview.ts b/packages/experimental/forge-github/src/overview.ts index afba1a1e60..34e21f8b20 100644 --- a/packages/experimental/forge-github/src/overview.ts +++ b/packages/experimental/forge-github/src/overview.ts @@ -9,11 +9,30 @@ import type { GraphqlWriter } from './mutation.ts' import { pullRequestNode } from './pull-request-node.ts' import { checkedRepository, isCommit } from './urls.ts' -/** Add review requests by login; variable `input` is a `RequestReviewsByLoginInput`. */ -export const REQUEST_REVIEWS_MUTATION = `mutation($input: RequestReviewsByLoginInput!) { +/** + * Add review requests from users and teams by node id; variable `input` is a `RequestReviewsInput`. Every supported + * host has it, while GitHub Enterprise Server 3.19 and 3.20 lack `requestReviewsByLogin`. + */ +export const REQUEST_REVIEWS_MUTATION = `mutation($input: RequestReviewsInput!) { + requestReviews(input: $input) { clientMutationId } +}` + +/** Add review requests from bots by login, which only this mutation accepts; variable `input` is a `RequestReviewsByLoginInput`. */ +export const REQUEST_BOT_REVIEWS_MUTATION = `mutation($input: RequestReviewsByLoginInput!) { requestReviewsByLogin(input: $input) { clientMutationId } }` +/** + * Split a team reviewer named `organization/slug`. + * @param login - the team's name. + * @returns the organization and the slug, or undefined for another name. + */ +function teamOf(login: string): readonly [string, string] | undefined { + const [organization, slug, ...rest] = login.split('/') + return organization === undefined || organization === '' || slug === undefined || slug === '' || rest.length > 0 ? undefined + : [organization, slug] +} + /** Merge or rebase the base branch into the head branch; variable `input` is an `UpdatePullRequestBranchInput`. */ export const UPDATE_BRANCH_MUTATION = `mutation($input: UpdatePullRequestBranchInput!) { updatePullRequestBranch(input: $input) { clientMutationId } @@ -45,30 +64,80 @@ const candidatesSchema = z.object({ }) /** - * Request reviews by login with `requestReviewsByLogin`, adding to the requests GitHub holds; a bot is named with - * GitHub's `[bot]` suffix and a team by `organization/slug`. + * Request reviews, adding to the requests GitHub holds. Users and teams are resolved to node ids in one query and asked + * with `requestReviews`; bots, named with or without GitHub's `[bot]` suffix, are asked with `requestReviewsByLogin` + * afterwards, which hosts without it refuse. A team is named `organization/slug`. * @param read - runs one GraphQL query. * @param write - runs one GraphQL mutation. * @param ref - pull request address. * @param request - the reviewers to ask. - * @param signal - cancellation of both requests. - * @returns undefined once GitHub accepted the request, or why it refused. + * @param signal - cancellation of every request. + * @returns undefined once GitHub accepted every request, or why it refused; a refused bot request follows an accepted + * request of the users and teams. */ export async function requestGitHubReviews( read: GraphqlReader, write: GraphqlWriter, ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise { if (request.reviewers.length === 0) return { code: 'failed', message: 'No reviewer was named' } + const logins = (kind: string): string[] => request.reviewers.filter(reviewer => reviewer.kind === kind).map(reviewer => reviewer.login) + const users = logins('user') + const teams: (readonly [string, string])[] = [] + for (const login of logins('team')) { + const team = teamOf(login) + if (team === undefined) return { code: 'failed', message: `Team ${JSON.stringify(login)} is not named organization/slug` } + teams.push(team) + } + const bots = logins('bot').map(login => login.endsWith('[bot]') ? login : `${login}[bot]`) const id = await pullRequestNode(read, ref, null, signal) if (typeof id !== 'string') return id - const logins = (kind: string): string[] => request.reviewers.filter(reviewer => reviewer.kind === kind).map(reviewer => reviewer.login) - const input: Record = { pullRequestId: id, union: true } - const users = logins('user') - const bots = logins('bot').map(login => login.endsWith('[bot]') ? login : `${login}[bot]`) - const teams = logins('team') - if (users.length > 0) input.userLogins = users - if (bots.length > 0) input.botLogins = bots - if (teams.length > 0) input.teamSlugs = teams - return await write(ref.repository.host, { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviewsByLogin', variables: { input } }, signal) + const { host } = ref.repository + if (users.length > 0 || teams.length > 0) { + const ids = await reviewerIds(read, host, users, teams, signal) + if ('code' in ids) return ids + const failure = await write(host, { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviews', variables: { + input: { pullRequestId: id, union: true, ...ids.users.length > 0 ? { userIds: ids.users } : {}, + ...ids.teams.length > 0 ? { teamIds: ids.teams } : {} }, + } }, signal) + if (failure !== undefined) return failure + } + if (bots.length === 0) return undefined + return await write(host, { query: REQUEST_BOT_REVIEWS_MUTATION, field: 'requestReviewsByLogin', + variables: { input: { pullRequestId: id, union: true, botLogins: bots } } }, signal) +} + +const idNode = z.object({ id: z.string() }) + +/** + * Resolve user logins and team slugs to node ids with one aliased query whose names are variables. + * @returns the ids in request order, or why GitHub did not resolve them, as for an unknown login. + */ +async function reviewerIds( + read: GraphqlReader, host: string, users: readonly string[], teams: readonly (readonly [string, string])[], signal: AbortSignal, +): Promise<{ readonly users: readonly string[]; readonly teams: readonly string[] } | ForgeActionFailure> { + const declarations = [...users.map((_, index) => `$u${index}: String!`), ...teams.flatMap((_, index) => [`$o${index}: String!`, `$t${index}: String!`])] + const fields = [...users.map((_, index) => `u${index}: user(login: $u${index}) { id }`), + ...teams.map((_, index) => `t${index}: organization(login: $o${index}) { team(slug: $t${index}) { id } }`)] + const query = `query(${declarations.join(', ')}) { ${fields.join(' ')} }` + const body = await read(['api', 'graphql', '--hostname', host, '-f', `query=${query}`, + ...users.flatMap((login, index) => ['-f', `u${index}=${login}`]), + ...teams.flatMap(([organization, slug], index) => ['-f', `o${index}=${organization}`, '-f', `t${index}=${slug}`])], signal) + if (!body.ok) return { code: body.failure.code === 'unauthenticated' ? 'unauthenticated' : 'failed', message: body.failure.message } + const parsed = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body.body) + if (!parsed.success) return { code: 'failed', message: 'unexpected GitHub response to the reviewer lookup' } + const { data } = parsed.data + const userIds: string[] = [] + for (const [index, login] of users.entries()) { + const user = idNode.safeParse(data[`u${index}`]) + if (!user.success) return { code: 'failed', message: `GitHub has no user ${login}` } + userIds.push(user.data.id) + } + const teamIds: string[] = [] + for (const [index, [organization, slug]] of teams.entries()) { + const team = z.object({ team: idNode }).safeParse(data[`t${index}`]) + if (!team.success) return { code: 'failed', message: `GitHub shows the signed-in user no team ${organization}/${slug}` } + teamIds.push(team.data.team.id) + } + return { users: userIds, teams: teamIds } } /** diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index f3aca26627..84d58344ca 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -272,8 +272,10 @@ export class GitHubProvider implements ForgeProvider { } /** - * Rerun every workflow run with a failed GitHub Actions job on the head commit through the REST API; GitHub reruns - * its failed jobs with the jobs that depend on them. Other checks name no rerun. + * Rerun every finished workflow run with a failed GitHub Actions job on the head commit through the REST API; GitHub + * reruns its failed jobs with the jobs that depend on them. A run with a check still pending waits, as GitHub offers + * no rerun of a run in progress. Every eligible run is tried, and a refusal of one is reported with the others' outcome. + * Other checks name no rerun. */ async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise { const { host, owner, name } = checkedRepository(ref) @@ -286,17 +288,29 @@ export class GitHubProvider implements ForgeProvider { return { code: 'stale', message: `the pull request head moved from ${request.headSha} to ${snapshot.headSha}` } } const endpoint = `repos/${owner}/${name}/actions` - const runs = new Set() + const failed = new Set() + const running = new Set() for (const check of snapshot.checks) { - const run = check.state === 'failure' && check.rerun !== null ? actionsRunOf(check.rerun) : undefined - if (run !== undefined) runs.add(run) + const run = check.rerun === null ? undefined : actionsRunOf(check.rerun) + if (run === undefined) continue + if (check.state === 'failure') failed.add(run) + else if (check.state === 'pending') running.add(run) } - if (runs.size === 0) return { code: 'failed', message: 'No failed GitHub Actions job of the head commit can be rerun' } + const runs = [...failed].filter(run => !running.has(run)) + if (runs.length === 0) { + return { code: 'failed', message: failed.size === 0 ? 'No failed GitHub Actions job of the head commit can be rerun' + : 'Every workflow run with a failed job is still running; rerun it once it finishes' } + } + const refusals: string[] = [] for (const run of runs) { const refused = await this.act(['api', '--hostname', host, '--method', 'POST', `${endpoint}/runs/${run}/rerun-failed-jobs`], signal) - if (refused !== undefined) return refused + if (refused === undefined) continue + if (refused.code === 'unauthenticated') return refused + // The head was checked before the first request, so a conflict here names no new commit. + refusals.push(`run ${run}: ${refused.message}`) } - return undefined + return refusals.length === 0 ? undefined + : { code: 'failed', message: `GitHub refused to rerun ${refusals.length} of ${runs.length} workflow runs: ${refusals.join('; ')}` } } async requestReviews( @@ -372,13 +386,12 @@ export class GitHubProvider implements ForgeProvider { } /** - * Run one GraphQL mutation with its query and variables as JSON on standard input, never in arguments. A refusal, a - * `gh` that cannot start, a body that is not GraphQL, and GraphQL errors become failures; the write is never retried. + * Run one GraphQL mutation through {@link sendMutation}, which never retries it: a refusal or a `gh` that cannot + * start is `failed`, and an answer that does not confirm the outcome is `unknown`. */ - /** Every refusal and every unconfirmed outcome fails: these mutations set a state, so trying again is safe. */ private readonly mutate: GraphqlWriter = async (host, mutation, signal) => { const sent = await sendMutation(this.gh, host, mutation, signal) - return sent.ok ? undefined : { code: 'failed', message: sent.message } + return sent.ok ? undefined : { code: sent.code, message: sent.message } } /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */ diff --git a/packages/experimental/forge-github/src/viewed.ts b/packages/experimental/forge-github/src/viewed.ts index f9cedeeddf..c52d6b8a44 100644 --- a/packages/experimental/forge-github/src/viewed.ts +++ b/packages/experimental/forge-github/src/viewed.ts @@ -32,7 +32,7 @@ export const UNMARK_VIEWED_MUTATION = `mutation($id: ID!, $path: String!) { unmarkFileAsViewed(input: { pullRequestId: $id, path: $path }) { clientMutationId } }` -const STATES: Readonly> = { VIEWED: 'viewed', UNVIEWED: 'unviewed', DISMISSED: 'dismissed' } +const STATES: ReadonlyMap = new Map([['VIEWED', 'viewed'], ['UNVIEWED', 'unviewed'], ['DISMISSED', 'dismissed']]) const pageSchema = z.object({ data: z.object({ @@ -70,7 +70,8 @@ export async function readViewed( ): Promise { const { host, owner, name } = checkedRepository(ref) if (!isCommit(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`) - const files: Record = {} + // A map keeps a path such as `__proto__`, which assignment to a plain object drops. + const files = new Map() let listed = 0 const cursors = new Set() let cursor: string | null = null @@ -90,9 +91,12 @@ export async function readViewed( // GitHub answers null for the files of a pull request whose diff it cannot list. if (pull.files === null) return { code: 'unavailable', message: 'GitHub did not list the pull request files' } const { totalCount, pageInfo: { hasNextPage, endCursor }, nodes } = pull.files - for (const node of nodes) files[node.path] = STATES[node.viewerViewedState] ?? 'unviewed' + for (const node of nodes) files.set(node.path, STATES.get(node.viewerViewedState) ?? 'unviewed') listed += nodes.length - if (!hasNextPage || listed >= limit) return { headSha: pull.headRefOid, files, truncated: totalCount > listed } + // `fromEntries` defines each path as an own property, `__proto__` included. + if (!hasNextPage || listed >= limit) { + return { headSha: pull.headRefOid, files: Object.fromEntries(files), truncated: totalCount > listed } + } if (endCursor === null || cursors.has(endCursor)) return { code: 'unavailable', message: 'GitHub file pagination did not advance' } cursors.add(endCursor) cursor = endCursor diff --git a/packages/experimental/forge-github/tests/graphql.spec.ts b/packages/experimental/forge-github/tests/graphql.spec.ts index 8a1b8ea2a5..b585de8aad 100644 --- a/packages/experimental/forge-github/tests/graphql.spec.ts +++ b/packages/experimental/forge-github/tests/graphql.spec.ts @@ -508,7 +508,9 @@ describe('overview mapping', () => { ['a head that can also be rebased', { canBeRebased: true }, ['merge', 'rebase']], ['a conflicting head', { mergeable: 'CONFLICTING' }, []], ['a closed pull request', { state: 'CLOSED' }, []], - ['a head the viewer may not update', { viewerCanUpdateBranch: false }, []], + // GitHub answers false both for a head that is up to date and for one the viewer may not update. + ['a head up to date or one the viewer may not update', { viewerCanUpdateBranch: false }, []], + ['a head behind its base whose merge state is blocked', { mergeStateStatus: 'BLOCKED' }, ['merge']], ])('offers branch updates for %s', async (_label, overrides, updates) => { expect((await single(pullRequestNode(1, { viewerCanUpdateBranch: true, ...overrides }))).branchUpdates).toEqual(updates) }) diff --git a/packages/experimental/forge-github/tests/overview.spec.ts b/packages/experimental/forge-github/tests/overview.spec.ts index 6890327d7c..32f0974d12 100644 --- a/packages/experimental/forge-github/tests/overview.spec.ts +++ b/packages/experimental/forge-github/tests/overview.spec.ts @@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import type { GraphqlReader } from '../src/commits.ts' import type { GraphqlWriter } from '../src/mutation.ts' import { - CANDIDATES_QUERY, gitHubReviewerCandidates, REQUEST_REVIEWS_MUTATION, requestGitHubReviews, UPDATE_BRANCH_MUTATION, updateGitHubBranch, + CANDIDATES_QUERY, gitHubReviewerCandidates, REQUEST_BOT_REVIEWS_MUTATION, REQUEST_REVIEWS_MUTATION, requestGitHubReviews, + UPDATE_BRANCH_MUTATION, updateGitHubBranch, } from '../src/overview.ts' import { pullRequestNode } from '../src/pull-request-node.ts' import { pull } from './fixtures.ts' @@ -44,25 +45,69 @@ describe('pull request node reads', () => { }) describe('review requests', () => { - it('adds users, bots with the bot suffix, and teams by login to the requests GitHub holds', async () => { + it('asks users and teams by node id, then bots by login with the bot suffix, adding to the requests GitHub holds', async () => { const write = vi.fn(async () => undefined) const reviewers = [ { kind: 'user' as const, login: 'mona' }, { kind: 'bot' as const, login: 'copilot' }, { kind: 'bot' as const, login: 'helper[bot]' }, - { kind: 'team' as const, login: 'octo/forge' }, + { kind: 'team' as const, login: 'octo/forge' }, { kind: 'user' as const, login: 'lin' }, ] - await expect(requestGitHubReviews(reader(node()).read, write, pull(7), { reviewers }, signal)).resolves.toBeUndefined() - expect(write).toHaveBeenCalledWith('github.com', { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviewsByLogin', variables: { input: { - pullRequestId: 'PR_7', union: true, userLogins: ['mona'], botLogins: ['copilot[bot]', 'helper[bot]'], teamSlugs: ['octo/forge'], - } } }, signal) + const ids = { data: { u0: { id: 'U_mona' }, u1: { id: 'U_lin' }, t0: { team: { id: 'T_forge' } } } } + const lookup = reader(node(), ids) + await expect(requestGitHubReviews(lookup.read, write, pull(7), { reviewers }, signal)).resolves.toBeUndefined() + // Names travel as variables, never inside the query text. + expect(lookup.calls[1]).toEqual(['api', 'graphql', '--hostname', 'github.com', '-f', + 'query=query($u0: String!, $u1: String!, $o0: String!, $t0: String!) { u0: user(login: $u0) { id } u1: user(login: $u1) { id } ' + + 't0: organization(login: $o0) { team(slug: $t0) { id } } }', + '-f', 'u0=mona', '-f', 'u1=lin', '-f', 'o0=octo', '-f', 't0=forge']) + expect(write.mock.calls.map(call => call[1])).toEqual([ + { query: REQUEST_REVIEWS_MUTATION, field: 'requestReviews', + variables: { input: { pullRequestId: 'PR_7', union: true, userIds: ['U_mona', 'U_lin'], teamIds: ['T_forge'] } } }, + { query: REQUEST_BOT_REVIEWS_MUTATION, field: 'requestReviewsByLogin', + variables: { input: { pullRequestId: 'PR_7', union: true, botLogins: ['copilot[bot]', 'helper[bot]'] } } }, + ]) }) - it('names only the kinds it requests, at any head', async () => { + it('names only the kinds it requests, at any head, and stops at a refusal', async () => { const write = vi.fn(async () => ({ code: 'failed', message: 'Could not resolve user' })) - await expect(requestGitHubReviews(reader(node('e'.repeat(40))).read, write, pull(7), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)) + const mixed = [{ kind: 'user' as const, login: 'mona' }, { kind: 'bot' as const, login: 'copilot' }] + await expect(requestGitHubReviews(reader(node('e'.repeat(40)), { data: { u0: { id: 'U_mona' } } }).read, write, pull(7), { reviewers: mixed }, signal)) .resolves.toEqual({ code: 'failed', message: 'Could not resolve user' }) - expect(write.mock.calls[0]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, userLogins: ['mona'] } }) - await requestGitHubReviews(reader(node()).read, write, pull(7), { reviewers: [{ kind: 'team', login: 'octo/forge' }] }, signal) - expect(write.mock.calls[1]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, teamSlugs: ['octo/forge'] } }) + expect(write).toHaveBeenCalledOnce() + expect(write.mock.calls[0]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, userIds: ['U_mona'] } }) + await requestGitHubReviews(reader(node(), { data: { t0: { team: { id: 'T_forge' } } } }).read, write, pull(7), + { reviewers: [{ kind: 'team', login: 'octo/forge' }] }, signal) + expect(write.mock.calls[1]?.[1].variables).toEqual({ input: { pullRequestId: 'PR_7', union: true, teamIds: ['T_forge'] } }) + const bots = reader(node()) + await requestGitHubReviews(bots.read, write, pull(7), { reviewers: [{ kind: 'bot', login: 'copilot' }] }, signal) + expect(bots.calls).toHaveLength(1) + expect(write.mock.calls[2]?.[1].field).toBe('requestReviewsByLogin') + }) + + it.each([ + ['an unknown user', [{ kind: 'user' as const, login: 'ghost' }], { data: { u0: null } }, 'GitHub has no user ghost'], + ['a hidden team', [{ kind: 'team' as const, login: 'octo/secret' }], { data: { t0: { team: null } } }, 'GitHub shows the signed-in user no team octo/secret'], + ['an unexpected lookup', [{ kind: 'user' as const, login: 'mona' }], { errors: [] }, 'unexpected GitHub response to the reviewer lookup'], + ])('refuses %s without writing', async (_label, reviewers, ids, message) => { + const write = vi.fn() + await expect(requestGitHubReviews(reader(node(), ids).read, write, pull(7), { reviewers }, signal)).resolves.toEqual({ code: 'failed', message }) + expect(write).not.toHaveBeenCalled() + }) + + it.each([ + ['a refused lookup', new Error('rate limited'), { code: 'failed', message: 'rate limited' }], + ['a lookup without sign-in', new Error('signed out'), { code: 'unauthenticated', message: 'signed out' }], + ])('passes on %s', async (_label, failure, expected) => { + const write = vi.fn() + await expect(requestGitHubReviews(reader(node(), failure).read, write, pull(7), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)) + .resolves.toEqual(expected) + }) + + it.each(['octo', 'octo/', '/forge', 'octo/forge/extra'])('refuses team %s, which is not named organization/slug, without reading', async (login) => { + const write = vi.fn() + const none = reader() + await expect(requestGitHubReviews(none.read, write, pull(7), { reviewers: [{ kind: 'team', login }] }, signal)) + .resolves.toEqual({ code: 'failed', message: `Team ${JSON.stringify(login)} is not named organization/slug` }) + expect(none.calls).toEqual([]) }) it('refuses an empty request without reading, and a failed node read without writing', async () => { diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index a9a3d0c20f..7bea15a154 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -754,10 +754,10 @@ describe('GitHub provider overview and viewed marks', () => { ['a refusing GraphQL error', output({ data: null, errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible by integration' }] }), { code: 'failed', message: 'Resource not accessible by integration' }], ['a GraphQL error that leaves the outcome unknown', output({ data: null, errors: [{ message: 'Something went wrong' }] }), - { code: 'failed', message: 'Something went wrong' }], + { code: 'unknown', message: 'Something went wrong' }], ['a refusal without a body', output('', 1, 'gh: Bad credentials (HTTP 401)'), { code: 'failed', message: 'gh: Bad credentials (HTTP 401)' }], - ['a body that is not GraphQL', output({ message: 'Not Found' }), { code: 'failed', message: 'unexpected GitHub response to unmarkFileAsViewed' }], - ])('reports a mutation refused or not confirmed with %s as failed', async (_label, answer, failure) => { + ['a body that is not GraphQL', output({ message: 'Not Found' }), { code: 'unknown', message: 'unexpected GitHub response to unmarkFileAsViewed' }], + ])('reports a mutation answered with %s as refused or as of unknown outcome', async (_label, answer, failure) => { const gh = double(() => node, () => answer) await expect(provider(gh.run).setViewed(pull(1), { path: 'a', viewed: false, headSha: HEAD }, signal)).resolves.toEqual(failure) }) @@ -777,13 +777,13 @@ describe('GitHub provider overview and viewed marks', () => { it('requests reviews, lists candidates, and updates the branch through GraphQL', async () => { const gh = double(query => query === CANDIDATES_QUERY ? { data: { repository: { assignableUsers: { nodes: [{ login: 'mona', name: null, avatarUrl: null }] }, pullRequest: null } } } - : node) + : query.startsWith('query($u0') ? { data: { u0: { id: 'U_mona' } } } : node) const subject = provider(gh.run) await expect(subject.requestReviews(pull(1), { reviewers: [{ kind: 'user', login: 'mona' }] }, signal)).resolves.toBeUndefined() await expect(subject.reviewerCandidates(pull(1), 'mo', signal)).resolves.toEqual([{ login: 'mona', name: null, avatarUrl: null, suggested: false }]) await expect(subject.updateBranch(pull(1), { method: 'rebase', headSha: HEAD }, signal)).resolves.toBeUndefined() expect(gh.inputs.map(body => (body as { variables: unknown }).variables)).toEqual([ - { input: { pullRequestId: 'PR_1', union: true, userLogins: ['mona'] } }, + { input: { pullRequestId: 'PR_1', union: true, userIds: ['U_mona'] } }, { input: { pullRequestId: 'PR_1', expectedHeadOid: HEAD, updateMethod: 'REBASE' } }, ]) }) @@ -801,14 +801,31 @@ describe('GitHub provider overview and viewed marks', () => { ]) }) - it('stops at the first refused rerun', async () => { - const failed = (run: number) => ({ ...checkRun(`job${run}`, 'COMPLETED', 'FAILURE'), - checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: run, event: 'pull_request', workflow: { id: `w${run}`, name: 'w' } } } }) - const gh = fakeGh(args => args[1] === 'graphql' ? output({ data: { r0: { p0: pullRequestNode(1, {}, [failed(1), failed(2)]) } } }) - : output({ message: 'Must have admin rights to Repository.' }, 1, 'gh: Must have admin rights to Repository. (HTTP 403)')) + it('tries every finished run after a refusal, leaves runs still in progress alone, and reports the refusals', async () => { + const check = (name: string, run: number, status: string, conclusion: string | null) => ({ ...checkRun(name, status, conclusion), + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: run, event: 'pull_request', workflow: { id: `w${run}`, name } } } }) + const contexts = [check('lint', 1, 'COMPLETED', 'FAILURE'), check('test', 2, 'COMPLETED', 'FAILURE'), check('build', 3, 'COMPLETED', 'FAILURE'), + check('e2e', 3, 'IN_PROGRESS', null)] + // A conflict names no new commit here, since the head was checked first. + const gh = fakeGh(args => args[1] === 'graphql' ? output({ data: { r0: { p0: pullRequestNode(1, {}, contexts) } } }) + : args[5]?.includes('/runs/1/') === true ? output({ message: 'Conflict' }, 1, 'gh: Conflict (HTTP 409)') : output('')) await expect(provider(gh.run).rerunChecks(pull(1), { headSha: HEAD }, signal)) - .resolves.toEqual({ code: 'failed', message: 'Must have admin rights to Repository.' }) - expect(gh.calls.filter(args => args[4] === 'POST')).toHaveLength(1) + .resolves.toEqual({ code: 'failed', message: 'GitHub refused to rerun 1 of 2 workflow runs: run 1: Conflict' }) + expect(gh.calls.filter(args => args[4] === 'POST').map(args => args[5])).toEqual([ + 'repos/octo/demo/actions/runs/1/rerun-failed-jobs', 'repos/octo/demo/actions/runs/2/rerun-failed-jobs', + ]) + }) + + it('stops at a rerun refused for credentials, and refuses when every run with a failure still runs', async () => { + const check = (name: string, status: string, conclusion: string | null) => ({ ...checkRun(name, status, conclusion), + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 5, event: 'pull_request', workflow: { id: 'w', name: 'w' } } } }) + const finished = fakeGh(args => args[1] === 'graphql' ? output({ data: { r0: { p0: pullRequestNode(1, {}, [check('lint', 'COMPLETED', 'FAILURE')]) } } }) + : output({ message: 'Bad credentials' }, 1, 'gh: Bad credentials (HTTP 401)')) + await expect(provider(finished.run).rerunChecks(pull(1), { headSha: HEAD }, signal)).resolves.toMatchObject({ code: 'unauthenticated' }) + const running = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1, {}, [check('lint', 'COMPLETED', 'FAILURE'), check('e2e', 'QUEUED', null)]) } } })) + await expect(provider(running.run).rerunChecks(pull(1), { headSha: HEAD }, signal)) + .resolves.toEqual({ code: 'failed', message: 'Every workflow run with a failed job is still running; rerun it once it finishes' }) + expect(running.calls.filter(args => args[4] === 'POST')).toEqual([]) }) it.each([ diff --git a/packages/experimental/forge-github/tests/viewed.spec.ts b/packages/experimental/forge-github/tests/viewed.spec.ts index 9dcf064810..49ab84d4c1 100644 --- a/packages/experimental/forge-github/tests/viewed.spec.ts +++ b/packages/experimental/forge-github/tests/viewed.spec.ts @@ -44,6 +44,13 @@ describe('viewed file reads', () => { expect(calls[1]?.slice(-2)).toEqual(['-f', 'cursor=files-1']) }) + it('keeps paths that name object properties, such as __proto__ and constructor, with their own states', async () => { + const { read } = reader(page([['__proto__', 'VIEWED'], ['constructor', 'UNVIEWED'], ['toString', 'constructor']], { total: 3 })) + const result = await readViewed(read, pull(7), HEAD, 3_000, signal) + if ('code' in result) throw new Error(result.message) + expect(Object.entries(result.files)).toEqual([['__proto__', 'viewed'], ['constructor', 'unviewed'], ['toString', 'unviewed']]) + }) + it('stops at the limit and reports the rest as truncated', async () => { const { read, calls } = reader(page([['src/a.ts', 'VIEWED'], ['src/b.ts', 'UNVIEWED']], { total: 5, next: 'files-1' })) await expect(readViewed(read, pull(7), HEAD, 2, signal)).resolves.toEqual({ diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index b0f3246322..9e385827da 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: fefda1bceb0bfcb9 - zh: 63e30b340db2fba4 + en: 8f8960a20cb74708 + zh: 1fc71e5dc46e3c48 /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index e84cdd28c4..13cd1124d1 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -34,7 +34,7 @@ Mount the registry with at least one provider package, such as the GitHub provid `ctx.forge.register(provider)` is an effect on the calling fiber and returns an async disposer that cancels and drains that registration's calls. Results arriving after cancellation are discarded. One provider serves one forge family; registering a second provider for the same family throws. Registration changes announce `forge/providers-changed`; registering a provider polls its existing watches immediately. `repositoryFromRemote(url)` and `changeRequestFromUrl(url)` ask providers in registration order and return the first match. `changeRequestUrl(ref)`, `findByHead(repository, branch, signal)`, and `readiness(repository, signal)` delegate to the provider of the reference's forge and throw when none is registered; `readiness` reports whether the provider can reach the host with current credentials. -`markReady(ref, signal)` marks a draft ready for review, and `merge(ref, { method, headSha }, signal)` merges a change request only while its head is still `headSha`. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to undefined once the host accepted the change or to a `ForgeActionFailure`: `unauthenticated`, `stale` when the head moved past `headSha`, or `failed` with the host's reason. After either settles, a watched change request is polled at once. Snapshots carry `mergeReady`, whether the host would merge the change request now for the signed-in user, and `mergeMethods`, the methods the repository accepts with that user's usual one first. +`markReady(ref, signal)` marks a draft ready for review, and `merge(ref, { method, headSha }, signal)` merges a change request only while its head is still `headSha`. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to undefined once the host accepted the change or to a `ForgeActionFailure`: `unauthenticated`, `stale` when the head moved past `headSha`, `failed` with the host's reason, or `unknown` when the host's 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. After either settles, a watched change request is polled at once. Snapshots carry `mergeReady`, whether the host would merge the change request now for the signed-in user, and `mergeMethods`, the methods the repository accepts with that user's usual one first. `diff(ref, headSha, signal)` reads the change request's unified patch at head commit `headSha` as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. A provider returns a patch only when it describes `headSha`; once the head is another commit, `diff` resolves to `stale`. The first stale read at a head commit polls a watched change request at once so its next status names the current head; later stale reads at that commit wait for the regular poll, which bounds reads while the host's answers briefly disagree. When the latest status of a watched change request names `headSha` and carries `baseSha`, the base commit the host recorded with that head, `diff` passes it to the provider, which may start reading from it before it confirms the head. Snapshots carry `unresolvedThreads` with `threadsTruncated`, which marks the count as a lower bound when the provider counted only some review threads. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. @@ -42,9 +42,9 @@ Providers may implement `commits` and `compare` together. `commits(ref, signal)` Providers may implement `viewedFiles` and `setViewed` together. `viewedFiles(ref, headSha, signal)` reads the signed-in user's viewed marks on the files of a change request at head commit `headSha`, each `viewed`, `unviewed`, or `dismissed` when the file changed after it was marked, with a `truncated` flag; `setViewed(ref, { path, viewed, headSha }, signal)` sets or clears one file's mark only while the head is still `headSha`. Both report a moved head as `stale`, which polls a watched change request as a stale `diff` does. When the provider lacks either method, `viewedFiles` returns undefined and `setViewed` a `failed` failure, so a consumer keeps viewed marks itself. -Snapshots carry the overview of a change request. `reviewers` lists requested reviewers first, then the latest reviewer of each account with their verdict and the commit it was given at; `closingIssues` lists the issues the host closes when the change request merges; `reviewersTruncated` and `closingIssuesTruncated` mark lists the provider read only in part. `branchUpdates` names the methods that would bring a head behind its base up to date for the signed-in user, empty when the head is current, conflicts, or may not be updated. `canRequestReviews` and `canRerunChecks` state the signed-in user's rights, and each check's `rerun` names the host run that reruns it, or null. +Snapshots carry the overview of a change request. `reviewers` lists requested reviewers first, then the latest reviewer of each account with their verdict and the commit it was given at; `closingIssues` lists the issues the host closes when the change request merges; `reviewersTruncated` and `closingIssuesTruncated` mark lists the provider read only in part. `branchUpdates` names the methods that would bring a head behind its base up to date for the signed-in user, empty when the head is current, conflicts, or may not be updated, so a consumer cannot tell a user without that right that the head is behind. `canRequestReviews` and `canRerunChecks` state the signed-in user's rights, and each check's `rerun` names the host run that reruns it, or null; checks that name one run rerun together once none of them is pending. -Providers may implement `rerunChecks(ref, { headSha }, signal)`, which reruns the failed checks of head commit `headSha`; `requestReviews(ref, { reviewers }, signal)` together with `reviewerCandidates(ref, query, signal)`, which lists accounts a review can be requested from with the host's suggestions first; and `updateBranch(ref, { method, headSha }, signal)`, which merges or rebases the base into the head only while the head is still `headSha`. Each action resolves to undefined once the host accepted it or to a `ForgeActionFailure`, and polls a watched change request once it settles. The registry fails an action the provider lacks with `failed`, and returns `unavailable` from `reviewerCandidates` unless the provider implements both review request methods. +Providers may implement `rerunChecks(ref, { headSha }, signal)`, which reruns the failed checks of head commit `headSha` whose run has no pending check; `requestReviews(ref, { reviewers }, signal)` together with `reviewerCandidates(ref, query, signal)`, which lists accounts a review can be requested from with the host's suggestions first; and `updateBranch(ref, { method, headSha }, signal)`, which merges or rebases the base into the head only while the head is still `headSha`. Each action resolves to undefined once the host accepted it or to a `ForgeActionFailure`, and polls a watched change request once it settles. The registry fails an action the provider lacks with `failed`, without polling, and returns `unsupported` from `reviewerCandidates` unless the provider implements both review request methods. `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 11fa4569a3..fee6351cdc 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -34,7 +34,7 @@ kind: "package-reference" `ctx.forge.register(provider)` 是调用方 fiber 上的 effect,返回异步 disposer,取消并等待该次注册的调用结束。取消后到达的结果会被丢弃。一个提供方服务一个 forge 家族;为同一家族注册第二个提供方会抛错。注册变化会发出 `forge/providers-changed`;注册提供方会立即轮询其已有监听。`repositoryFromRemote(url)` 与 `changeRequestFromUrl(url)` 按注册顺序询问提供方并返回第一个匹配结果。`changeRequestUrl(ref)`、`findByHead(repository, branch, signal)` 与 `readiness(repository, signal)` 委托给引用所属 forge 的提供方,没有注册提供方时抛错;`readiness` 报告提供方能否用当前凭据访问该主机。 -`markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`,或带主机原因的 `failed`。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 +`markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`、带主机原因的 `failed`,或主机的答复无法确认结果时的 `unknown`:此时改动可能已经生效,再次尝试前必须先到主机上核对。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 `diff(ref, headSha, signal)` 读取托管平台计算出的变更请求在 head 提交 `headSha` 处的统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。提供方只在补丁描述 `headSha` 时返回补丁;head 已是其他提交时,`diff` resolve 为 `stale`。同一 head 提交的第一次 stale 读取会让被 watch 的变更请求立即重新轮询,使下一次状态给出当前 head;之后在该提交上的 stale 读取等待常规轮询,从而在托管平台的应答短暂不一致时限制读取次数。被 watch 的变更请求的最新状态给出 `headSha` 并携带 `baseSha`(托管平台随该 head 记录的基准提交)时,`diff` 把它传给提供方,提供方可以在确认 head 之前就从它开始读取。快照携带 `unresolvedThreads` 与 `threadsTruncated`;提供方只统计了部分评审讨论时,后者表示该计数只是下限。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 @@ -42,9 +42,9 @@ kind: "package-reference" 提供方可以同时实现 `viewedFiles` 与 `setViewed`。`viewedFiles(ref, headSha, signal)` 在 head 提交 `headSha` 上读取当前登录用户对变更请求各文件的已审阅标记,每个文件为 `viewed`、`unviewed`,或在标记后又有改动时为 `dismissed`,并带 `truncated` 标志;`setViewed(ref, { path, viewed, headSha }, signal)` 仅在 head 仍是 `headSha` 时设置或清除一个文件的标记。两者都把已移动的 head 报告为 `stale`,并像过期的 `diff` 一样立即轮询被监听的变更请求。提供方缺少其中任一方法时,`viewedFiles` 返回 undefined,`setViewed` 返回 `failed` 失败,因此使用方自行保存已审阅标记。 -快照携带变更请求的概览。`reviewers` 先列出被请求的评审者,再列出每个账号最近一次评审的结论及其所针对的提交;`closingIssues` 列出变更请求合并时代码托管平台会关闭的 issue;`reviewersTruncated` 与 `closingIssuesTruncated` 标记提供方只读取了部分的列表。`branchUpdates` 列出能让落后于基线的 head 为当前登录用户更新的方式;head 已是最新、存在冲突或不允许更新时为空。`canRequestReviews` 与 `canRerunChecks` 说明当前登录用户的权限,每个检查的 `rerun` 指出能重跑它的托管平台运行,否则为 null。 +快照携带变更请求的概览。`reviewers` 先列出被请求的评审者,再列出每个账号最近一次评审的结论及其所针对的提交;`closingIssues` 列出变更请求合并时代码托管平台会关闭的 issue;`reviewersTruncated` 与 `closingIssuesTruncated` 标记提供方只读取了部分的列表。`branchUpdates` 列出能让落后于基线的 head 为当前登录用户更新的方式;head 已是最新、存在冲突或不允许更新时为空,因此使用方无法告诉没有更新权限的用户 head 已落后。`canRequestReviews` 与 `canRerunChecks` 说明当前登录用户的权限,每个检查的 `rerun` 指出能重跑它的托管平台运行,否则为 null;指向同一运行的检查一起重跑,且要等其中没有检查仍在进行。 -提供方可以实现 `rerunChecks(ref, { headSha }, signal)`,重跑 head 提交 `headSha` 的失败检查;可以同时实现 `requestReviews(ref, { reviewers }, signal)` 与 `reviewerCandidates(ref, query, signal)`,后者列出可以请求评审的账号,托管平台的建议排在最前;还可以实现 `updateBranch(ref, { method, headSha }, signal)`,仅在 head 仍是 `headSha` 时把基线合并或变基进 head。每个操作在托管平台接受后返回 undefined,否则返回 `ForgeActionFailure`,结束后会立即轮询被监听的变更请求。提供方缺少某个操作时,注册表以 `failed` 失败返回;除非提供方同时实现两个评审请求方法,`reviewerCandidates` 返回 `unavailable`。 +提供方可以实现 `rerunChecks(ref, { headSha }, signal)`,重跑 head 提交 `headSha` 中所在运行没有进行中检查的失败检查;可以同时实现 `requestReviews(ref, { reviewers }, signal)` 与 `reviewerCandidates(ref, query, signal)`,后者列出可以请求评审的账号,托管平台的建议排在最前;还可以实现 `updateBranch(ref, { method, headSha }, signal)`,仅在 head 仍是 `headSha` 时把基线合并或变基进 head。每个操作在托管平台接受后返回 undefined,否则返回 `ForgeActionFailure`,结束后会立即轮询被监听的变更请求。提供方缺少某个操作时,注册表以 `failed` 失败返回且不轮询;除非提供方同时实现两个评审请求方法,`reviewerCandidates` 返回 `unsupported`。 `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 270358de4e..46da83a266 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -48,7 +48,10 @@ export 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. */ + /** + * 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 } @@ -142,7 +145,8 @@ export interface ChangeRequestSnapshot { 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. + * 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. */ @@ -406,13 +410,15 @@ export type ForgeReviewResult = | { readonly ok: true; readonly url: string } | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } -/** 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. */ export 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 } @@ -551,9 +557,9 @@ export interface ForgeProvider { */ setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise /** - * Rerun the failed checks of the head commit that name a `rerun`, while the head is still `request.headSha`, - * resolving to undefined once the host accepted the rerun. Omission declares that the provider reruns no checks, and - * its snapshots then name none. + * 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 /** diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index e332931521..55c63b384c 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1500,7 +1500,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: '@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise', description: 'Set or clear the signed-in user\'s viewed mark on one file of a change request of a Session.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'request', description: 'the file, its mark, and the head commit of the shown diff.' }, { name: 'signal', description: '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.'], + 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.'], }, { signature: '@Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise', @@ -1538,13 +1538,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: '@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise', description: '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.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'request', description: 'the head commit whose checks the user saw.' }, { name: 'signal', description: '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.'], + 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.'], }, { signature: '@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise', description: 'Request reviews of a change request of a Session from more reviewers; the change request is polled again once the host answers.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'reviewers', description: 'the reviewers to ask, by kind and login.' }, { name: 'signal', description: '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.'], + 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.'], }, { signature: '@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise', @@ -1557,7 +1557,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: '@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise', description: '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.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'method', description: 'merge commit or rebase.' }, { name: 'headSha', description: 'head commit the user confirmed.' }, { name: 'signal', description: '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.'], + 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.'], }, { signature: '@Remote async requestWorktree(session: Session, from: string | null, signal: AbortSignal): Promise', @@ -6744,7 +6744,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeActionFailure', - declaration: 'export interface ForgeActionFailure {\n readonly code: \'unauthenticated\' | \'stale\' | \'failed\';\n readonly message: string;\n}', + declaration: 'export interface ForgeActionFailure {\n readonly code: \'unauthenticated\' | \'stale\' | \'failed\' | \'unknown\';\n readonly message: string;\n}', }, { name: 'ForgeAnchor', From 8da1df07751ac3a77a4bc694aa2a7a9229e7ae4d Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 21:27:06 +0800 Subject: [PATCH 14/15] fix(forge-panel): round reviewer avatars in every engine and share the menu search keys The reviewer avatar pairs its full-round radius with `corner-shape: round`, as the theme requires of every full-round radius. The base branch menu and the reviewer search share one handler for the keys of their search field instead of two copies. --- .../client-ui-forge/README.i18n.yaml | 4 ++-- packages/experimental/client-ui-forge/README.md | 1 + .../experimental/client-ui-forge/README.zh.md | 1 + .../client-ui-forge/src/client/BaseMenu.tsx | 8 ++------ .../src/client/ChangeRequestOverview.module.css | 1 + .../src/client/ChangeRequestOverview.tsx | 8 ++------ .../client-ui-forge/src/client/menu-search.ts | 16 ++++++++++++++++ 7 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/client/menu-search.ts diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 7beff73f1b..61b61e6dc9 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -18,8 +18,8 @@ en: c3fa707a638717e4 zh: dfeba8a57c58a8aa /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 34e9adf3a843f969 - zh: 7a04974cf01fa2e7 + en: c9541603ea971f46 + zh: 15c41326e3fb29e4 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 0cff619fbf..2d95507268 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -106,6 +106,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`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 | diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index b5a53effd0..c7f9d4b994 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -106,6 +106,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`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 缺失卡片 | 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/ChangeRequestOverview.module.css b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css index 71e602700a..3f0cc3ba36 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css @@ -35,6 +35,7 @@ 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; diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx index dd44612e4f..4fb047f74d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -22,6 +22,7 @@ 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' @@ -470,12 +471,7 @@ function ReviewerSearch({ url, list, choose, t }: {
} value={query} aria-label={t('reviewers.search')} placeholder={t('reviewers.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() - choose(first.login) - }} /> + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { choose(first.login) }) }} />
{body}
diff --git a/packages/experimental/client-ui-forge/src/client/menu-search.ts b/packages/experimental/client-ui-forge/src/client/menu-search.ts new file mode 100644 index 0000000000..efd11a2580 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/menu-search.ts @@ -0,0 +1,16 @@ +/** Keys of the search field at the top of a menu that lists what the search matches. */ + +import type { KeyboardEvent } from 'react' + +/** + * Keep the edge and arrow keys in a menu's search field, so they move the caret instead of the menu's focus, and choose + * the first listed row with Enter outside an input method composition. + * @param event - the key event of the search field. + * @param chooseFirst - chooses the first listed row, or undefined while none is listed. + */ +export function searchFieldKeyDown(event: KeyboardEvent, chooseFirst: (() => void) | undefined): void { + if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() + if (event.key !== 'Enter' || event.nativeEvent.isComposing || chooseFirst === undefined) return + event.preventDefault() + chooseFirst() +} From 7d2d22aaf96bb54754209e46579de1735febdf66 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 10 Nov 2026 10:32:03 +0800 Subject: [PATCH 15/15] fix(ui-primitives): look up file types in Maps so prototype keys miss classifyFileType and classifyCodeFileType indexed plain objects by the lowercased basename and extension, so a file named `constructor` or `__proto__` (or with that extension) resolved an inherited Object.prototype member and FileTypeIcon threw from its assertNever, crashing every view that lists the file. The name and extension tables are now Maps, so such names fall through to their real type or `other`. Fixes #8205 --- .../client/ui-primitives/src/FileTypeIcon.tsx | 14 ++++++----- .../ui-primitives/src/code-file-types.ts | 14 ++++++----- .../tests/file-type-icon.client.spec.tsx | 25 +++++++++++++++++++ 3 files changed, 41 insertions(+), 12 deletions(-) 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',